babylon.max.js 3.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. // Methods
  1433. /**
  1434. * Normalize the current Vector3.
  1435. * Returns the updated Vector3.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Returns a new Vector3 copied from the current Vector3.
  1449. */
  1450. Vector3.prototype.clone = function () {
  1451. return new Vector3(this.x, this.y, this.z);
  1452. };
  1453. /**
  1454. * Copies the passed vector coordinates to the current Vector3 ones.
  1455. * Returns the updated Vector3.
  1456. */
  1457. Vector3.prototype.copyFrom = function (source) {
  1458. this.x = source.x;
  1459. this.y = source.y;
  1460. this.z = source.z;
  1461. return this;
  1462. };
  1463. /**
  1464. * Copies the passed floats to the current Vector3 coordinates.
  1465. * Returns the updated Vector3.
  1466. */
  1467. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1468. this.x = x;
  1469. this.y = y;
  1470. this.z = z;
  1471. return this;
  1472. };
  1473. /**
  1474. * Copies the passed floats to the current Vector3 coordinates.
  1475. * Returns the updated Vector3.
  1476. */
  1477. Vector3.prototype.set = function (x, y, z) {
  1478. return this.copyFromFloats(x, y, z);
  1479. };
  1480. // Statics
  1481. /**
  1482. *
  1483. */
  1484. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1485. var d0 = Vector3.Dot(vector0, axis) - size;
  1486. var d1 = Vector3.Dot(vector1, axis) - size;
  1487. var s = d0 / (d0 - d1);
  1488. return s;
  1489. };
  1490. /**
  1491. * Returns a new Vector3 set from the index "offset" of the passed array.
  1492. */
  1493. Vector3.FromArray = function (array, offset) {
  1494. if (!offset) {
  1495. offset = 0;
  1496. }
  1497. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1498. };
  1499. /**
  1500. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1501. * This function is deprecated. Use FromArray instead.
  1502. */
  1503. Vector3.FromFloatArray = function (array, offset) {
  1504. return Vector3.FromArray(array, offset);
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1508. */
  1509. Vector3.FromArrayToRef = function (array, offset, result) {
  1510. result.x = array[offset];
  1511. result.y = array[offset + 1];
  1512. result.z = array[offset + 2];
  1513. };
  1514. /**
  1515. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1516. * This function is deprecated. Use FromArrayToRef instead.
  1517. */
  1518. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1519. return Vector3.FromArrayToRef(array, offset, result);
  1520. };
  1521. /**
  1522. * Sets the passed vector "result" with the passed floats.
  1523. */
  1524. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1525. result.x = x;
  1526. result.y = y;
  1527. result.z = z;
  1528. };
  1529. /**
  1530. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1531. */
  1532. Vector3.Zero = function () {
  1533. return new Vector3(0.0, 0.0, 0.0);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1537. */
  1538. Vector3.One = function () {
  1539. return new Vector3(1.0, 1.0, 1.0);
  1540. };
  1541. /**
  1542. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1543. */
  1544. Vector3.Up = function () {
  1545. return new Vector3(0.0, 1.0, 0.0);
  1546. };
  1547. /**
  1548. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1549. */
  1550. Vector3.Forward = function () {
  1551. return new Vector3(0.0, 0.0, 1.0);
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1555. */
  1556. Vector3.Right = function () {
  1557. return new Vector3(1.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1561. */
  1562. Vector3.Left = function () {
  1563. return new Vector3(-1.0, 0.0, 0.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1567. * This method computes tranformed coordinates only, not transformed direction vectors.
  1568. */
  1569. Vector3.TransformCoordinates = function (vector, transformation) {
  1570. var result = Vector3.Zero();
  1571. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1572. return result;
  1573. };
  1574. /**
  1575. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1576. * This method computes tranformed coordinates only, not transformed direction vectors.
  1577. */
  1578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1583. result.x = x / w;
  1584. result.y = y / w;
  1585. result.z = z / w;
  1586. };
  1587. /**
  1588. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1589. * This method computes tranformed coordinates only, not transformed direction vectors.
  1590. */
  1591. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1592. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1593. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1594. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1595. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1596. result.x = rx / rw;
  1597. result.y = ry / rw;
  1598. result.z = rz / rw;
  1599. };
  1600. /**
  1601. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1602. * This methods computes transformed normalized direction vectors only.
  1603. */
  1604. Vector3.TransformNormal = function (vector, transformation) {
  1605. var result = Vector3.Zero();
  1606. Vector3.TransformNormalToRef(vector, transformation, result);
  1607. return result;
  1608. };
  1609. /**
  1610. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1611. * This methods computes transformed normalized direction vectors only.
  1612. */
  1613. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1614. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1615. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1616. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1617. result.x = x;
  1618. result.y = y;
  1619. result.z = z;
  1620. };
  1621. /**
  1622. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1623. * This methods computes transformed normalized direction vectors only.
  1624. */
  1625. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1626. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1627. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1628. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1629. };
  1630. /**
  1631. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1632. */
  1633. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1634. var squared = amount * amount;
  1635. var cubed = amount * squared;
  1636. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1637. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1638. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1639. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1640. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1641. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1642. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1643. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1644. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1645. return new Vector3(x, y, z);
  1646. };
  1647. /**
  1648. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1649. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1650. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1651. */
  1652. Vector3.Clamp = function (value, min, max) {
  1653. var x = value.x;
  1654. x = (x > max.x) ? max.x : x;
  1655. x = (x < min.x) ? min.x : x;
  1656. var y = value.y;
  1657. y = (y > max.y) ? max.y : y;
  1658. y = (y < min.y) ? min.y : y;
  1659. var z = value.z;
  1660. z = (z > max.z) ? max.z : z;
  1661. z = (z < min.z) ? min.z : z;
  1662. return new Vector3(x, y, z);
  1663. };
  1664. /**
  1665. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1666. */
  1667. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1668. var squared = amount * amount;
  1669. var cubed = amount * squared;
  1670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1672. var part3 = (cubed - (2.0 * squared)) + amount;
  1673. var part4 = cubed - squared;
  1674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1677. return new Vector3(x, y, z);
  1678. };
  1679. /**
  1680. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1681. */
  1682. Vector3.Lerp = function (start, end, amount) {
  1683. var result = new Vector3(0, 0, 0);
  1684. Vector3.LerpToRef(start, end, amount, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1689. */
  1690. Vector3.LerpToRef = function (start, end, amount, result) {
  1691. result.x = start.x + ((end.x - start.x) * amount);
  1692. result.y = start.y + ((end.y - start.y) * amount);
  1693. result.z = start.z + ((end.z - start.z) * amount);
  1694. };
  1695. /**
  1696. * Returns the dot product (float) between the vectors "left" and "right".
  1697. */
  1698. Vector3.Dot = function (left, right) {
  1699. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1700. };
  1701. /**
  1702. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1703. * The cross product is then orthogonal to both "left" and "right".
  1704. */
  1705. Vector3.Cross = function (left, right) {
  1706. var result = Vector3.Zero();
  1707. Vector3.CrossToRef(left, right, result);
  1708. return result;
  1709. };
  1710. /**
  1711. * Sets the passed vector "result" with the cross product of "left" and "right".
  1712. * The cross product is then orthogonal to both "left" and "right".
  1713. */
  1714. Vector3.CrossToRef = function (left, right, result) {
  1715. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1716. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1717. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1718. result.copyFrom(MathTmp.Vector3[0]);
  1719. };
  1720. /**
  1721. * Returns a new Vector3 as the normalization of the passed vector.
  1722. */
  1723. Vector3.Normalize = function (vector) {
  1724. var result = Vector3.Zero();
  1725. Vector3.NormalizeToRef(vector, result);
  1726. return result;
  1727. };
  1728. /**
  1729. * Sets the passed vector "result" with the normalization of the passed first vector.
  1730. */
  1731. Vector3.NormalizeToRef = function (vector, result) {
  1732. result.copyFrom(vector);
  1733. result.normalize();
  1734. };
  1735. Vector3.Project = function (vector, world, transform, viewport) {
  1736. var cw = viewport.width;
  1737. var ch = viewport.height;
  1738. var cx = viewport.x;
  1739. var cy = viewport.y;
  1740. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1741. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1742. var matrix = MathTmp.Matrix[0];
  1743. world.multiplyToRef(transform, matrix);
  1744. matrix.multiplyToRef(viewportMatrix, matrix);
  1745. return Vector3.TransformCoordinates(vector, matrix);
  1746. };
  1747. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1748. var matrix = MathTmp.Matrix[0];
  1749. world.multiplyToRef(transform, matrix);
  1750. matrix.invert();
  1751. source.x = source.x / viewportWidth * 2 - 1;
  1752. source.y = -(source.y / viewportHeight * 2 - 1);
  1753. var vector = Vector3.TransformCoordinates(source, matrix);
  1754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1756. vector = vector.scale(1.0 / num);
  1757. }
  1758. return vector;
  1759. };
  1760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1761. var matrix = MathTmp.Matrix[0];
  1762. world.multiplyToRef(view, matrix);
  1763. matrix.multiplyToRef(projection, matrix);
  1764. matrix.invert();
  1765. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1766. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1767. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1768. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1769. vector = vector.scale(1.0 / num);
  1770. }
  1771. return vector;
  1772. };
  1773. Vector3.Minimize = function (left, right) {
  1774. var min = left.clone();
  1775. min.MinimizeInPlace(right);
  1776. return min;
  1777. };
  1778. Vector3.Maximize = function (left, right) {
  1779. var max = left.clone();
  1780. max.MaximizeInPlace(right);
  1781. return max;
  1782. };
  1783. /**
  1784. * Returns the distance (float) between the vectors "value1" and "value2".
  1785. */
  1786. Vector3.Distance = function (value1, value2) {
  1787. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1788. };
  1789. /**
  1790. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1791. */
  1792. Vector3.DistanceSquared = function (value1, value2) {
  1793. var x = value1.x - value2.x;
  1794. var y = value1.y - value2.y;
  1795. var z = value1.z - value2.z;
  1796. return (x * x) + (y * y) + (z * z);
  1797. };
  1798. /**
  1799. * Returns a new Vector3 located at the center between "value1" and "value2".
  1800. */
  1801. Vector3.Center = function (value1, value2) {
  1802. var center = value1.add(value2);
  1803. center.scaleInPlace(0.5);
  1804. return center;
  1805. };
  1806. /**
  1807. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1808. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1809. * to something in order to rotate it from its local system to the given target system.
  1810. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1811. * Returns a new Vector3.
  1812. */
  1813. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1814. var rotation = Vector3.Zero();
  1815. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1816. return rotation;
  1817. };
  1818. /**
  1819. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1820. */
  1821. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1822. var quat = MathTmp.Quaternion[0];
  1823. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1824. quat.toEulerAnglesToRef(ref);
  1825. };
  1826. return Vector3;
  1827. }());
  1828. BABYLON.Vector3 = Vector3;
  1829. //Vector4 class created for EulerAngle class conversion to Quaternion
  1830. var Vector4 = /** @class */ (function () {
  1831. /**
  1832. * Creates a Vector4 object from the passed floats.
  1833. */
  1834. function Vector4(x, y, z, w) {
  1835. this.x = x;
  1836. this.y = y;
  1837. this.z = z;
  1838. this.w = w;
  1839. }
  1840. /**
  1841. * Returns the string with the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.toString = function () {
  1844. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1845. };
  1846. /**
  1847. * Returns the string "Vector4".
  1848. */
  1849. Vector4.prototype.getClassName = function () {
  1850. return "Vector4";
  1851. };
  1852. /**
  1853. * Returns the Vector4 hash code.
  1854. */
  1855. Vector4.prototype.getHashCode = function () {
  1856. var hash = this.x || 0;
  1857. hash = (hash * 397) ^ (this.y || 0);
  1858. hash = (hash * 397) ^ (this.z || 0);
  1859. hash = (hash * 397) ^ (this.w || 0);
  1860. return hash;
  1861. };
  1862. // Operators
  1863. /**
  1864. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1865. */
  1866. Vector4.prototype.asArray = function () {
  1867. var result = new Array();
  1868. this.toArray(result, 0);
  1869. return result;
  1870. };
  1871. /**
  1872. * Populates the passed array from the passed index with the Vector4 coordinates.
  1873. * Returns the Vector4.
  1874. */
  1875. Vector4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.x;
  1880. array[index + 1] = this.y;
  1881. array[index + 2] = this.z;
  1882. array[index + 3] = this.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Adds the passed vector to the current Vector4.
  1887. * Returns the updated Vector4.
  1888. */
  1889. Vector4.prototype.addInPlace = function (otherVector) {
  1890. this.x += otherVector.x;
  1891. this.y += otherVector.y;
  1892. this.z += otherVector.z;
  1893. this.w += otherVector.w;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1898. */
  1899. Vector4.prototype.add = function (otherVector) {
  1900. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1901. };
  1902. /**
  1903. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1904. * Returns the current Vector4.
  1905. */
  1906. Vector4.prototype.addToRef = function (otherVector, result) {
  1907. result.x = this.x + otherVector.x;
  1908. result.y = this.y + otherVector.y;
  1909. result.z = this.z + otherVector.z;
  1910. result.w = this.w + otherVector.w;
  1911. return this;
  1912. };
  1913. /**
  1914. * Subtract in place the passed vector from the current Vector4.
  1915. * Returns the updated Vector4.
  1916. */
  1917. Vector4.prototype.subtractInPlace = function (otherVector) {
  1918. this.x -= otherVector.x;
  1919. this.y -= otherVector.y;
  1920. this.z -= otherVector.z;
  1921. this.w -= otherVector.w;
  1922. return this;
  1923. };
  1924. /**
  1925. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1926. */
  1927. Vector4.prototype.subtract = function (otherVector) {
  1928. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1929. };
  1930. /**
  1931. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1932. * Returns the current Vector4.
  1933. */
  1934. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1935. result.x = this.x - otherVector.x;
  1936. result.y = this.y - otherVector.y;
  1937. result.z = this.z - otherVector.z;
  1938. result.w = this.w - otherVector.w;
  1939. return this;
  1940. };
  1941. /**
  1942. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1943. */
  1944. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1945. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1946. };
  1947. /**
  1948. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1949. * Returns the current Vector4.
  1950. */
  1951. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1952. result.x = this.x - x;
  1953. result.y = this.y - y;
  1954. result.z = this.z - z;
  1955. result.w = this.w - w;
  1956. return this;
  1957. };
  1958. /**
  1959. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1960. */
  1961. Vector4.prototype.negate = function () {
  1962. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1963. };
  1964. /**
  1965. * Multiplies the current Vector4 coordinates by scale (float).
  1966. * Returns the updated Vector4.
  1967. */
  1968. Vector4.prototype.scaleInPlace = function (scale) {
  1969. this.x *= scale;
  1970. this.y *= scale;
  1971. this.z *= scale;
  1972. this.w *= scale;
  1973. return this;
  1974. };
  1975. /**
  1976. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1977. */
  1978. Vector4.prototype.scale = function (scale) {
  1979. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1980. };
  1981. /**
  1982. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1983. * Returns the current Vector4.
  1984. */
  1985. Vector4.prototype.scaleToRef = function (scale, result) {
  1986. result.x = this.x * scale;
  1987. result.y = this.y * scale;
  1988. result.z = this.z * scale;
  1989. result.w = this.w * scale;
  1990. return this;
  1991. };
  1992. /**
  1993. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1994. */
  1995. Vector4.prototype.equals = function (otherVector) {
  1996. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1997. };
  1998. /**
  1999. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2000. */
  2001. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2002. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2003. return otherVector
  2004. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2005. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2006. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2007. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2008. };
  2009. /**
  2010. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2011. */
  2012. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2013. return this.x === x && this.y === y && this.z === z && this.w === w;
  2014. };
  2015. /**
  2016. * Multiplies in place the current Vector4 by the passed one.
  2017. * Returns the updated Vector4.
  2018. */
  2019. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2020. this.x *= otherVector.x;
  2021. this.y *= otherVector.y;
  2022. this.z *= otherVector.z;
  2023. this.w *= otherVector.w;
  2024. return this;
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2028. */
  2029. Vector4.prototype.multiply = function (otherVector) {
  2030. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2037. result.x = this.x * otherVector.x;
  2038. result.y = this.y * otherVector.y;
  2039. result.z = this.z * otherVector.z;
  2040. result.w = this.w * otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2045. */
  2046. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2047. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2051. */
  2052. Vector4.prototype.divide = function (otherVector) {
  2053. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2054. };
  2055. /**
  2056. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2057. * Returns the current Vector4.
  2058. */
  2059. Vector4.prototype.divideToRef = function (otherVector, result) {
  2060. result.x = this.x / otherVector.x;
  2061. result.y = this.y / otherVector.y;
  2062. result.z = this.z / otherVector.z;
  2063. result.w = this.w / otherVector.w;
  2064. return this;
  2065. };
  2066. /**
  2067. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2068. */
  2069. Vector4.prototype.MinimizeInPlace = function (other) {
  2070. if (other.x < this.x)
  2071. this.x = other.x;
  2072. if (other.y < this.y)
  2073. this.y = other.y;
  2074. if (other.z < this.z)
  2075. this.z = other.z;
  2076. if (other.w < this.w)
  2077. this.w = other.w;
  2078. return this;
  2079. };
  2080. /**
  2081. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2082. */
  2083. Vector4.prototype.MaximizeInPlace = function (other) {
  2084. if (other.x > this.x)
  2085. this.x = other.x;
  2086. if (other.y > this.y)
  2087. this.y = other.y;
  2088. if (other.z > this.z)
  2089. this.z = other.z;
  2090. if (other.w > this.w)
  2091. this.w = other.w;
  2092. return this;
  2093. };
  2094. // Properties
  2095. /**
  2096. * Returns the Vector4 length (float).
  2097. */
  2098. Vector4.prototype.length = function () {
  2099. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2100. };
  2101. /**
  2102. * Returns the Vector4 squared length (float).
  2103. */
  2104. Vector4.prototype.lengthSquared = function () {
  2105. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2106. };
  2107. // Methods
  2108. /**
  2109. * Normalizes in place the Vector4.
  2110. * Returns the updated Vector4.
  2111. */
  2112. Vector4.prototype.normalize = function () {
  2113. var len = this.length();
  2114. if (len === 0)
  2115. return this;
  2116. var num = 1.0 / len;
  2117. this.x *= num;
  2118. this.y *= num;
  2119. this.z *= num;
  2120. this.w *= num;
  2121. return this;
  2122. };
  2123. /**
  2124. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2125. */
  2126. Vector4.prototype.toVector3 = function () {
  2127. return new Vector3(this.x, this.y, this.z);
  2128. };
  2129. /**
  2130. * Returns a new Vector4 copied from the current one.
  2131. */
  2132. Vector4.prototype.clone = function () {
  2133. return new Vector4(this.x, this.y, this.z, this.w);
  2134. };
  2135. /**
  2136. * Updates the current Vector4 with the passed one coordinates.
  2137. * Returns the updated Vector4.
  2138. */
  2139. Vector4.prototype.copyFrom = function (source) {
  2140. this.x = source.x;
  2141. this.y = source.y;
  2142. this.z = source.z;
  2143. this.w = source.w;
  2144. return this;
  2145. };
  2146. /**
  2147. * Updates the current Vector4 coordinates with the passed floats.
  2148. * Returns the updated Vector4.
  2149. */
  2150. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2151. this.x = x;
  2152. this.y = y;
  2153. this.z = z;
  2154. this.w = w;
  2155. return this;
  2156. };
  2157. /**
  2158. * Updates the current Vector4 coordinates with the passed floats.
  2159. * Returns the updated Vector4.
  2160. */
  2161. Vector4.prototype.set = function (x, y, z, w) {
  2162. return this.copyFromFloats(x, y, z, w);
  2163. };
  2164. // Statics
  2165. /**
  2166. * Returns a new Vector4 set from the starting index of the passed array.
  2167. */
  2168. Vector4.FromArray = function (array, offset) {
  2169. if (!offset) {
  2170. offset = 0;
  2171. }
  2172. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2173. };
  2174. /**
  2175. * Updates the passed vector "result" from the starting index of the passed array.
  2176. */
  2177. Vector4.FromArrayToRef = function (array, offset, result) {
  2178. result.x = array[offset];
  2179. result.y = array[offset + 1];
  2180. result.z = array[offset + 2];
  2181. result.w = array[offset + 3];
  2182. };
  2183. /**
  2184. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2185. */
  2186. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2187. Vector4.FromArrayToRef(array, offset, result);
  2188. };
  2189. /**
  2190. * Updates the passed vector "result" coordinates from the passed floats.
  2191. */
  2192. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2193. result.x = x;
  2194. result.y = y;
  2195. result.z = z;
  2196. result.w = w;
  2197. };
  2198. /**
  2199. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2200. */
  2201. Vector4.Zero = function () {
  2202. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2203. };
  2204. /**
  2205. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2206. */
  2207. Vector4.One = function () {
  2208. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2209. };
  2210. /**
  2211. * Returns a new normalized Vector4 from the passed one.
  2212. */
  2213. Vector4.Normalize = function (vector) {
  2214. var result = Vector4.Zero();
  2215. Vector4.NormalizeToRef(vector, result);
  2216. return result;
  2217. };
  2218. /**
  2219. * Updates the passed vector "result" from the normalization of the passed one.
  2220. */
  2221. Vector4.NormalizeToRef = function (vector, result) {
  2222. result.copyFrom(vector);
  2223. result.normalize();
  2224. };
  2225. Vector4.Minimize = function (left, right) {
  2226. var min = left.clone();
  2227. min.MinimizeInPlace(right);
  2228. return min;
  2229. };
  2230. Vector4.Maximize = function (left, right) {
  2231. var max = left.clone();
  2232. max.MaximizeInPlace(right);
  2233. return max;
  2234. };
  2235. /**
  2236. * Returns the distance (float) between the vectors "value1" and "value2".
  2237. */
  2238. Vector4.Distance = function (value1, value2) {
  2239. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2240. };
  2241. /**
  2242. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2243. */
  2244. Vector4.DistanceSquared = function (value1, value2) {
  2245. var x = value1.x - value2.x;
  2246. var y = value1.y - value2.y;
  2247. var z = value1.z - value2.z;
  2248. var w = value1.w - value2.w;
  2249. return (x * x) + (y * y) + (z * z) + (w * w);
  2250. };
  2251. /**
  2252. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2253. */
  2254. Vector4.Center = function (value1, value2) {
  2255. var center = value1.add(value2);
  2256. center.scaleInPlace(0.5);
  2257. return center;
  2258. };
  2259. /**
  2260. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2261. * This methods computes transformed normalized direction vectors only.
  2262. */
  2263. Vector4.TransformNormal = function (vector, transformation) {
  2264. var result = Vector4.Zero();
  2265. Vector4.TransformNormalToRef(vector, transformation, result);
  2266. return result;
  2267. };
  2268. /**
  2269. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2270. * This methods computes transformed normalized direction vectors only.
  2271. */
  2272. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2273. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2274. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2275. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2276. result.x = x;
  2277. result.y = y;
  2278. result.z = z;
  2279. result.w = vector.w;
  2280. };
  2281. /**
  2282. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2283. * This methods computes transformed normalized direction vectors only.
  2284. */
  2285. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2286. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2287. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2288. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2289. result.w = w;
  2290. };
  2291. return Vector4;
  2292. }());
  2293. BABYLON.Vector4 = Vector4;
  2294. var Size = /** @class */ (function () {
  2295. /**
  2296. * Creates a Size object from the passed width and height (floats).
  2297. */
  2298. function Size(width, height) {
  2299. this.width = width;
  2300. this.height = height;
  2301. }
  2302. // Returns a string with the Size width and height.
  2303. Size.prototype.toString = function () {
  2304. return "{W: " + this.width + ", H: " + this.height + "}";
  2305. };
  2306. /**
  2307. * Returns the string "Size"
  2308. */
  2309. Size.prototype.getClassName = function () {
  2310. return "Size";
  2311. };
  2312. /**
  2313. * Returns the Size hash code.
  2314. */
  2315. Size.prototype.getHashCode = function () {
  2316. var hash = this.width || 0;
  2317. hash = (hash * 397) ^ (this.height || 0);
  2318. return hash;
  2319. };
  2320. /**
  2321. * Updates the current size from the passed one.
  2322. * Returns the updated Size.
  2323. */
  2324. Size.prototype.copyFrom = function (src) {
  2325. this.width = src.width;
  2326. this.height = src.height;
  2327. };
  2328. /**
  2329. * Updates in place the current Size from the passed floats.
  2330. * Returns the updated Size.
  2331. */
  2332. Size.prototype.copyFromFloats = function (width, height) {
  2333. this.width = width;
  2334. this.height = height;
  2335. return this;
  2336. };
  2337. /**
  2338. * Updates in place the current Size from the passed floats.
  2339. * Returns the updated Size.
  2340. */
  2341. Size.prototype.set = function (width, height) {
  2342. return this.copyFromFloats(width, height);
  2343. };
  2344. /**
  2345. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2346. */
  2347. Size.prototype.multiplyByFloats = function (w, h) {
  2348. return new Size(this.width * w, this.height * h);
  2349. };
  2350. /**
  2351. * Returns a new Size copied from the passed one.
  2352. */
  2353. Size.prototype.clone = function () {
  2354. return new Size(this.width, this.height);
  2355. };
  2356. /**
  2357. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2358. */
  2359. Size.prototype.equals = function (other) {
  2360. if (!other) {
  2361. return false;
  2362. }
  2363. return (this.width === other.width) && (this.height === other.height);
  2364. };
  2365. Object.defineProperty(Size.prototype, "surface", {
  2366. /**
  2367. * Returns the surface of the Size : width * height (float).
  2368. */
  2369. get: function () {
  2370. return this.width * this.height;
  2371. },
  2372. enumerable: true,
  2373. configurable: true
  2374. });
  2375. /**
  2376. * Returns a new Size set to (0.0, 0.0)
  2377. */
  2378. Size.Zero = function () {
  2379. return new Size(0.0, 0.0);
  2380. };
  2381. /**
  2382. * Returns a new Size set as the addition result of the current Size and the passed one.
  2383. */
  2384. Size.prototype.add = function (otherSize) {
  2385. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2386. return r;
  2387. };
  2388. /**
  2389. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2390. */
  2391. Size.prototype.subtract = function (otherSize) {
  2392. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2393. return r;
  2394. };
  2395. /**
  2396. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2397. */
  2398. Size.Lerp = function (start, end, amount) {
  2399. var w = start.width + ((end.width - start.width) * amount);
  2400. var h = start.height + ((end.height - start.height) * amount);
  2401. return new Size(w, h);
  2402. };
  2403. return Size;
  2404. }());
  2405. BABYLON.Size = Size;
  2406. var Quaternion = /** @class */ (function () {
  2407. /**
  2408. * Creates a new Quaternion from the passed floats.
  2409. */
  2410. function Quaternion(x, y, z, w) {
  2411. if (x === void 0) { x = 0.0; }
  2412. if (y === void 0) { y = 0.0; }
  2413. if (z === void 0) { z = 0.0; }
  2414. if (w === void 0) { w = 1.0; }
  2415. this.x = x;
  2416. this.y = y;
  2417. this.z = z;
  2418. this.w = w;
  2419. }
  2420. /**
  2421. * Returns a string with the Quaternion coordinates.
  2422. */
  2423. Quaternion.prototype.toString = function () {
  2424. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2425. };
  2426. /**
  2427. * Returns the string "Quaternion".
  2428. */
  2429. Quaternion.prototype.getClassName = function () {
  2430. return "Quaternion";
  2431. };
  2432. /**
  2433. * Returns the Quaternion hash code.
  2434. */
  2435. Quaternion.prototype.getHashCode = function () {
  2436. var hash = this.x || 0;
  2437. hash = (hash * 397) ^ (this.y || 0);
  2438. hash = (hash * 397) ^ (this.z || 0);
  2439. hash = (hash * 397) ^ (this.w || 0);
  2440. return hash;
  2441. };
  2442. /**
  2443. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2444. */
  2445. Quaternion.prototype.asArray = function () {
  2446. return [this.x, this.y, this.z, this.w];
  2447. };
  2448. /**
  2449. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2450. */
  2451. Quaternion.prototype.equals = function (otherQuaternion) {
  2452. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2453. };
  2454. /**
  2455. * Returns a new Quaternion copied from the current one.
  2456. */
  2457. Quaternion.prototype.clone = function () {
  2458. return new Quaternion(this.x, this.y, this.z, this.w);
  2459. };
  2460. /**
  2461. * Updates the current Quaternion from the passed one coordinates.
  2462. * Returns the updated Quaterion.
  2463. */
  2464. Quaternion.prototype.copyFrom = function (other) {
  2465. this.x = other.x;
  2466. this.y = other.y;
  2467. this.z = other.z;
  2468. this.w = other.w;
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the current Quaternion from the passed float coordinates.
  2473. * Returns the updated Quaterion.
  2474. */
  2475. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2476. this.x = x;
  2477. this.y = y;
  2478. this.z = z;
  2479. this.w = w;
  2480. return this;
  2481. };
  2482. /**
  2483. * Updates the current Quaternion from the passed float coordinates.
  2484. * Returns the updated Quaterion.
  2485. */
  2486. Quaternion.prototype.set = function (x, y, z, w) {
  2487. return this.copyFromFloats(x, y, z, w);
  2488. };
  2489. /**
  2490. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2491. */
  2492. Quaternion.prototype.add = function (other) {
  2493. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2494. };
  2495. /**
  2496. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2497. */
  2498. Quaternion.prototype.subtract = function (other) {
  2499. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2500. };
  2501. /**
  2502. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2503. */
  2504. Quaternion.prototype.scale = function (value) {
  2505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2506. };
  2507. /**
  2508. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2509. */
  2510. Quaternion.prototype.multiply = function (q1) {
  2511. var result = new Quaternion(0, 0, 0, 1.0);
  2512. this.multiplyToRef(q1, result);
  2513. return result;
  2514. };
  2515. /**
  2516. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2517. * Returns the current Quaternion.
  2518. */
  2519. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2520. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2521. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2522. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2523. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2524. result.copyFromFloats(x, y, z, w);
  2525. return this;
  2526. };
  2527. /**
  2528. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2529. * Returns the updated Quaternion.
  2530. */
  2531. Quaternion.prototype.multiplyInPlace = function (q1) {
  2532. this.multiplyToRef(q1, this);
  2533. return this;
  2534. };
  2535. /**
  2536. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2537. * Returns the current Quaternion.
  2538. */
  2539. Quaternion.prototype.conjugateToRef = function (ref) {
  2540. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2541. return this;
  2542. };
  2543. /**
  2544. * Conjugates in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.conjugateInPlace = function () {
  2548. this.x *= -1;
  2549. this.y *= -1;
  2550. this.z *= -1;
  2551. return this;
  2552. };
  2553. /**
  2554. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2555. */
  2556. Quaternion.prototype.conjugate = function () {
  2557. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2558. return result;
  2559. };
  2560. /**
  2561. * Returns the Quaternion length (float).
  2562. */
  2563. Quaternion.prototype.length = function () {
  2564. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2565. };
  2566. /**
  2567. * Normalize in place the current Quaternion.
  2568. * Returns the updated Quaternion.
  2569. */
  2570. Quaternion.prototype.normalize = function () {
  2571. var length = 1.0 / this.length();
  2572. this.x *= length;
  2573. this.y *= length;
  2574. this.z *= length;
  2575. this.w *= length;
  2576. return this;
  2577. };
  2578. /**
  2579. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2580. */
  2581. Quaternion.prototype.toEulerAngles = function (order) {
  2582. if (order === void 0) { order = "YZX"; }
  2583. var result = Vector3.Zero();
  2584. this.toEulerAnglesToRef(result, order);
  2585. return result;
  2586. };
  2587. /**
  2588. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2589. * Returns the current Quaternion.
  2590. */
  2591. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2592. if (order === void 0) { order = "YZX"; }
  2593. var qz = this.z;
  2594. var qx = this.x;
  2595. var qy = this.y;
  2596. var qw = this.w;
  2597. var sqw = qw * qw;
  2598. var sqz = qz * qz;
  2599. var sqx = qx * qx;
  2600. var sqy = qy * qy;
  2601. var zAxisY = qy * qz - qx * qw;
  2602. var limit = .4999999;
  2603. if (zAxisY < -limit) {
  2604. result.y = 2 * Math.atan2(qy, qw);
  2605. result.x = Math.PI / 2;
  2606. result.z = 0;
  2607. }
  2608. else if (zAxisY > limit) {
  2609. result.y = 2 * Math.atan2(qy, qw);
  2610. result.x = -Math.PI / 2;
  2611. result.z = 0;
  2612. }
  2613. else {
  2614. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2615. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2616. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2617. }
  2618. return this;
  2619. };
  2620. /**
  2621. * Updates the passed rotation matrix with the current Quaternion values.
  2622. * Returns the current Quaternion.
  2623. */
  2624. Quaternion.prototype.toRotationMatrix = function (result) {
  2625. var xx = this.x * this.x;
  2626. var yy = this.y * this.y;
  2627. var zz = this.z * this.z;
  2628. var xy = this.x * this.y;
  2629. var zw = this.z * this.w;
  2630. var zx = this.z * this.x;
  2631. var yw = this.y * this.w;
  2632. var yz = this.y * this.z;
  2633. var xw = this.x * this.w;
  2634. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2635. result.m[1] = 2.0 * (xy + zw);
  2636. result.m[2] = 2.0 * (zx - yw);
  2637. result.m[3] = 0;
  2638. result.m[4] = 2.0 * (xy - zw);
  2639. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2640. result.m[6] = 2.0 * (yz + xw);
  2641. result.m[7] = 0;
  2642. result.m[8] = 2.0 * (zx + yw);
  2643. result.m[9] = 2.0 * (yz - xw);
  2644. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2645. result.m[11] = 0;
  2646. result.m[12] = 0;
  2647. result.m[13] = 0;
  2648. result.m[14] = 0;
  2649. result.m[15] = 1.0;
  2650. result._markAsUpdated();
  2651. return this;
  2652. };
  2653. /**
  2654. * Updates the current Quaternion from the passed rotation matrix values.
  2655. * Returns the updated Quaternion.
  2656. */
  2657. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2658. Quaternion.FromRotationMatrixToRef(matrix, this);
  2659. return this;
  2660. };
  2661. // Statics
  2662. /**
  2663. * Returns a new Quaternion set from the passed rotation matrix values.
  2664. */
  2665. Quaternion.FromRotationMatrix = function (matrix) {
  2666. var result = new Quaternion();
  2667. Quaternion.FromRotationMatrixToRef(matrix, result);
  2668. return result;
  2669. };
  2670. /**
  2671. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2672. */
  2673. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2674. var data = matrix.m;
  2675. var m11 = data[0], m12 = data[4], m13 = data[8];
  2676. var m21 = data[1], m22 = data[5], m23 = data[9];
  2677. var m31 = data[2], m32 = data[6], m33 = data[10];
  2678. var trace = m11 + m22 + m33;
  2679. var s;
  2680. if (trace > 0) {
  2681. s = 0.5 / Math.sqrt(trace + 1.0);
  2682. result.w = 0.25 / s;
  2683. result.x = (m32 - m23) * s;
  2684. result.y = (m13 - m31) * s;
  2685. result.z = (m21 - m12) * s;
  2686. }
  2687. else if (m11 > m22 && m11 > m33) {
  2688. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2689. result.w = (m32 - m23) / s;
  2690. result.x = 0.25 * s;
  2691. result.y = (m12 + m21) / s;
  2692. result.z = (m13 + m31) / s;
  2693. }
  2694. else if (m22 > m33) {
  2695. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2696. result.w = (m13 - m31) / s;
  2697. result.x = (m12 + m21) / s;
  2698. result.y = 0.25 * s;
  2699. result.z = (m23 + m32) / s;
  2700. }
  2701. else {
  2702. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2703. result.w = (m21 - m12) / s;
  2704. result.x = (m13 + m31) / s;
  2705. result.y = (m23 + m32) / s;
  2706. result.z = 0.25 * s;
  2707. }
  2708. };
  2709. /**
  2710. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2711. */
  2712. Quaternion.Zero = function () {
  2713. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2714. };
  2715. /**
  2716. * Returns a new Quaternion as the inverted current Quaternion.
  2717. */
  2718. Quaternion.Inverse = function (q) {
  2719. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2720. };
  2721. /**
  2722. * Returns the identity Quaternion.
  2723. */
  2724. Quaternion.Identity = function () {
  2725. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2726. };
  2727. Quaternion.IsIdentity = function (quaternion) {
  2728. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2729. };
  2730. /**
  2731. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2732. */
  2733. Quaternion.RotationAxis = function (axis, angle) {
  2734. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2735. };
  2736. /**
  2737. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2738. */
  2739. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2740. var sin = Math.sin(angle / 2);
  2741. axis.normalize();
  2742. result.w = Math.cos(angle / 2);
  2743. result.x = axis.x * sin;
  2744. result.y = axis.y * sin;
  2745. result.z = axis.z * sin;
  2746. return result;
  2747. };
  2748. /**
  2749. * Retuns a new Quaternion set from the starting index of the passed array.
  2750. */
  2751. Quaternion.FromArray = function (array, offset) {
  2752. if (!offset) {
  2753. offset = 0;
  2754. }
  2755. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2756. };
  2757. /**
  2758. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2759. */
  2760. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2761. var q = new Quaternion();
  2762. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2763. return q;
  2764. };
  2765. /**
  2766. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2767. */
  2768. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2769. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2770. var halfRoll = roll * 0.5;
  2771. var halfPitch = pitch * 0.5;
  2772. var halfYaw = yaw * 0.5;
  2773. var sinRoll = Math.sin(halfRoll);
  2774. var cosRoll = Math.cos(halfRoll);
  2775. var sinPitch = Math.sin(halfPitch);
  2776. var cosPitch = Math.cos(halfPitch);
  2777. var sinYaw = Math.sin(halfYaw);
  2778. var cosYaw = Math.cos(halfYaw);
  2779. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2780. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2781. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2782. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2783. };
  2784. /**
  2785. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2786. */
  2787. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2788. var result = new Quaternion();
  2789. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2790. return result;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2794. */
  2795. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2796. // Produces a quaternion from Euler angles in the z-x-z orientation
  2797. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2798. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2799. var halfBeta = beta * 0.5;
  2800. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2801. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2802. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2803. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2804. };
  2805. /**
  2806. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2807. * cf to Vector3.RotationFromAxis() documentation.
  2808. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2809. */
  2810. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2811. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2812. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2813. return quat;
  2814. };
  2815. /**
  2816. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2817. * cf to Vector3.RotationFromAxis() documentation.
  2818. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2819. */
  2820. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2821. var rotMat = MathTmp.Matrix[0];
  2822. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2823. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2824. };
  2825. Quaternion.Slerp = function (left, right, amount) {
  2826. var result = Quaternion.Identity();
  2827. Quaternion.SlerpToRef(left, right, amount, result);
  2828. return result;
  2829. };
  2830. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2831. var num2;
  2832. var num3;
  2833. var num = amount;
  2834. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2835. var flag = false;
  2836. if (num4 < 0) {
  2837. flag = true;
  2838. num4 = -num4;
  2839. }
  2840. if (num4 > 0.999999) {
  2841. num3 = 1 - num;
  2842. num2 = flag ? -num : num;
  2843. }
  2844. else {
  2845. var num5 = Math.acos(num4);
  2846. var num6 = (1.0 / Math.sin(num5));
  2847. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2848. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2849. }
  2850. result.x = (num3 * left.x) + (num2 * right.x);
  2851. result.y = (num3 * left.y) + (num2 * right.y);
  2852. result.z = (num3 * left.z) + (num2 * right.z);
  2853. result.w = (num3 * left.w) + (num2 * right.w);
  2854. };
  2855. /**
  2856. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2857. */
  2858. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2859. var squared = amount * amount;
  2860. var cubed = amount * squared;
  2861. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2862. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2863. var part3 = (cubed - (2.0 * squared)) + amount;
  2864. var part4 = cubed - squared;
  2865. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2866. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2867. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2868. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2869. return new Quaternion(x, y, z, w);
  2870. };
  2871. return Quaternion;
  2872. }());
  2873. BABYLON.Quaternion = Quaternion;
  2874. var Matrix = /** @class */ (function () {
  2875. function Matrix() {
  2876. this._isIdentity = false;
  2877. this._isIdentityDirty = true;
  2878. this.m = new Float32Array(16);
  2879. this._markAsUpdated();
  2880. }
  2881. Matrix.prototype._markAsUpdated = function () {
  2882. this.updateFlag = Matrix._updateFlagSeed++;
  2883. this._isIdentityDirty = true;
  2884. };
  2885. // Properties
  2886. /**
  2887. * Boolean : True is the matrix is the identity matrix
  2888. */
  2889. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2890. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2891. if (this._isIdentityDirty) {
  2892. this._isIdentityDirty = false;
  2893. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2894. this._isIdentity = false;
  2895. }
  2896. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2897. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2898. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2899. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2900. this._isIdentity = false;
  2901. }
  2902. else {
  2903. this._isIdentity = true;
  2904. }
  2905. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2906. this._isIdentity = false;
  2907. }
  2908. }
  2909. return this._isIdentity;
  2910. };
  2911. /**
  2912. * Returns the matrix determinant (float).
  2913. */
  2914. Matrix.prototype.determinant = function () {
  2915. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2916. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2917. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2918. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2919. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2920. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2921. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2922. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2923. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2924. };
  2925. // Methods
  2926. /**
  2927. * Returns the matrix underlying array.
  2928. */
  2929. Matrix.prototype.toArray = function () {
  2930. return this.m;
  2931. };
  2932. /**
  2933. * Returns the matrix underlying array.
  2934. */
  2935. Matrix.prototype.asArray = function () {
  2936. return this.toArray();
  2937. };
  2938. /**
  2939. * Inverts in place the Matrix.
  2940. * Returns the Matrix inverted.
  2941. */
  2942. Matrix.prototype.invert = function () {
  2943. this.invertToRef(this);
  2944. return this;
  2945. };
  2946. /**
  2947. * Sets all the matrix elements to zero.
  2948. * Returns the Matrix.
  2949. */
  2950. Matrix.prototype.reset = function () {
  2951. for (var index = 0; index < 16; index++) {
  2952. this.m[index] = 0.0;
  2953. }
  2954. this._markAsUpdated();
  2955. return this;
  2956. };
  2957. /**
  2958. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2959. */
  2960. Matrix.prototype.add = function (other) {
  2961. var result = new Matrix();
  2962. this.addToRef(other, result);
  2963. return result;
  2964. };
  2965. /**
  2966. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2967. * Returns the Matrix.
  2968. */
  2969. Matrix.prototype.addToRef = function (other, result) {
  2970. for (var index = 0; index < 16; index++) {
  2971. result.m[index] = this.m[index] + other.m[index];
  2972. }
  2973. result._markAsUpdated();
  2974. return this;
  2975. };
  2976. /**
  2977. * Adds in place the passed matrix to the current Matrix.
  2978. * Returns the updated Matrix.
  2979. */
  2980. Matrix.prototype.addToSelf = function (other) {
  2981. for (var index = 0; index < 16; index++) {
  2982. this.m[index] += other.m[index];
  2983. }
  2984. this._markAsUpdated();
  2985. return this;
  2986. };
  2987. /**
  2988. * Sets the passed matrix with the current inverted Matrix.
  2989. * Returns the unmodified current Matrix.
  2990. */
  2991. Matrix.prototype.invertToRef = function (other) {
  2992. var l1 = this.m[0];
  2993. var l2 = this.m[1];
  2994. var l3 = this.m[2];
  2995. var l4 = this.m[3];
  2996. var l5 = this.m[4];
  2997. var l6 = this.m[5];
  2998. var l7 = this.m[6];
  2999. var l8 = this.m[7];
  3000. var l9 = this.m[8];
  3001. var l10 = this.m[9];
  3002. var l11 = this.m[10];
  3003. var l12 = this.m[11];
  3004. var l13 = this.m[12];
  3005. var l14 = this.m[13];
  3006. var l15 = this.m[14];
  3007. var l16 = this.m[15];
  3008. var l17 = (l11 * l16) - (l12 * l15);
  3009. var l18 = (l10 * l16) - (l12 * l14);
  3010. var l19 = (l10 * l15) - (l11 * l14);
  3011. var l20 = (l9 * l16) - (l12 * l13);
  3012. var l21 = (l9 * l15) - (l11 * l13);
  3013. var l22 = (l9 * l14) - (l10 * l13);
  3014. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3015. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3016. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3017. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3018. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3019. var l28 = (l7 * l16) - (l8 * l15);
  3020. var l29 = (l6 * l16) - (l8 * l14);
  3021. var l30 = (l6 * l15) - (l7 * l14);
  3022. var l31 = (l5 * l16) - (l8 * l13);
  3023. var l32 = (l5 * l15) - (l7 * l13);
  3024. var l33 = (l5 * l14) - (l6 * l13);
  3025. var l34 = (l7 * l12) - (l8 * l11);
  3026. var l35 = (l6 * l12) - (l8 * l10);
  3027. var l36 = (l6 * l11) - (l7 * l10);
  3028. var l37 = (l5 * l12) - (l8 * l9);
  3029. var l38 = (l5 * l11) - (l7 * l9);
  3030. var l39 = (l5 * l10) - (l6 * l9);
  3031. other.m[0] = l23 * l27;
  3032. other.m[4] = l24 * l27;
  3033. other.m[8] = l25 * l27;
  3034. other.m[12] = l26 * l27;
  3035. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3036. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3037. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3038. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3039. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3040. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3041. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3042. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3043. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3044. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3045. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3046. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3047. other._markAsUpdated();
  3048. return this;
  3049. };
  3050. /**
  3051. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3052. * Returns the updated Matrix.
  3053. */
  3054. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3055. this.m[12] = x;
  3056. this.m[13] = y;
  3057. this.m[14] = z;
  3058. this._markAsUpdated();
  3059. return this;
  3060. };
  3061. /**
  3062. * Inserts the translation vector in the current Matrix.
  3063. * Returns the updated Matrix.
  3064. */
  3065. Matrix.prototype.setTranslation = function (vector3) {
  3066. this.m[12] = vector3.x;
  3067. this.m[13] = vector3.y;
  3068. this.m[14] = vector3.z;
  3069. this._markAsUpdated();
  3070. return this;
  3071. };
  3072. /**
  3073. * Returns a new Vector3 as the extracted translation from the Matrix.
  3074. */
  3075. Matrix.prototype.getTranslation = function () {
  3076. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3077. };
  3078. /**
  3079. * Fill a Vector3 with the extracted translation from the Matrix.
  3080. */
  3081. Matrix.prototype.getTranslationToRef = function (result) {
  3082. result.x = this.m[12];
  3083. result.y = this.m[13];
  3084. result.z = this.m[14];
  3085. return this;
  3086. };
  3087. /**
  3088. * Remove rotation and scaling part from the Matrix.
  3089. * Returns the updated Matrix.
  3090. */
  3091. Matrix.prototype.removeRotationAndScaling = function () {
  3092. this.setRowFromFloats(0, 1, 0, 0, 0);
  3093. this.setRowFromFloats(1, 0, 1, 0, 0);
  3094. this.setRowFromFloats(2, 0, 0, 1, 0);
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3099. */
  3100. Matrix.prototype.multiply = function (other) {
  3101. var result = new Matrix();
  3102. this.multiplyToRef(other, result);
  3103. return result;
  3104. };
  3105. /**
  3106. * Updates the current Matrix from the passed one values.
  3107. * Returns the updated Matrix.
  3108. */
  3109. Matrix.prototype.copyFrom = function (other) {
  3110. for (var index = 0; index < 16; index++) {
  3111. this.m[index] = other.m[index];
  3112. }
  3113. this._markAsUpdated();
  3114. return this;
  3115. };
  3116. /**
  3117. * Populates the passed array from the starting index with the Matrix values.
  3118. * Returns the Matrix.
  3119. */
  3120. Matrix.prototype.copyToArray = function (array, offset) {
  3121. if (offset === void 0) { offset = 0; }
  3122. for (var index = 0; index < 16; index++) {
  3123. array[offset + index] = this.m[index];
  3124. }
  3125. return this;
  3126. };
  3127. /**
  3128. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3129. */
  3130. Matrix.prototype.multiplyToRef = function (other, result) {
  3131. this.multiplyToArray(other, result.m, 0);
  3132. result._markAsUpdated();
  3133. return this;
  3134. };
  3135. /**
  3136. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3137. */
  3138. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3139. var tm0 = this.m[0];
  3140. var tm1 = this.m[1];
  3141. var tm2 = this.m[2];
  3142. var tm3 = this.m[3];
  3143. var tm4 = this.m[4];
  3144. var tm5 = this.m[5];
  3145. var tm6 = this.m[6];
  3146. var tm7 = this.m[7];
  3147. var tm8 = this.m[8];
  3148. var tm9 = this.m[9];
  3149. var tm10 = this.m[10];
  3150. var tm11 = this.m[11];
  3151. var tm12 = this.m[12];
  3152. var tm13 = this.m[13];
  3153. var tm14 = this.m[14];
  3154. var tm15 = this.m[15];
  3155. var om0 = other.m[0];
  3156. var om1 = other.m[1];
  3157. var om2 = other.m[2];
  3158. var om3 = other.m[3];
  3159. var om4 = other.m[4];
  3160. var om5 = other.m[5];
  3161. var om6 = other.m[6];
  3162. var om7 = other.m[7];
  3163. var om8 = other.m[8];
  3164. var om9 = other.m[9];
  3165. var om10 = other.m[10];
  3166. var om11 = other.m[11];
  3167. var om12 = other.m[12];
  3168. var om13 = other.m[13];
  3169. var om14 = other.m[14];
  3170. var om15 = other.m[15];
  3171. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3172. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3173. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3174. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3175. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3176. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3177. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3178. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3179. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3180. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3181. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3182. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3183. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3184. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3185. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3186. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3187. return this;
  3188. };
  3189. /**
  3190. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3191. */
  3192. Matrix.prototype.equals = function (value) {
  3193. return value &&
  3194. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3195. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3196. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3197. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3198. };
  3199. /**
  3200. * Returns a new Matrix from the current Matrix.
  3201. */
  3202. Matrix.prototype.clone = function () {
  3203. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3204. };
  3205. /**
  3206. * Returns the string "Matrix"
  3207. */
  3208. Matrix.prototype.getClassName = function () {
  3209. return "Matrix";
  3210. };
  3211. /**
  3212. * Returns the Matrix hash code.
  3213. */
  3214. Matrix.prototype.getHashCode = function () {
  3215. var hash = this.m[0] || 0;
  3216. for (var i = 1; i < 16; i++) {
  3217. hash = (hash * 397) ^ (this.m[i] || 0);
  3218. }
  3219. return hash;
  3220. };
  3221. /**
  3222. * Decomposes the current Matrix into :
  3223. * - a scale vector3 passed as a reference to update,
  3224. * - a rotation quaternion passed as a reference to update,
  3225. * - a translation vector3 passed as a reference to update.
  3226. * Returns the boolean `true`.
  3227. */
  3228. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3229. translation.x = this.m[12];
  3230. translation.y = this.m[13];
  3231. translation.z = this.m[14];
  3232. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3233. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3234. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3235. if (this.determinant() <= 0) {
  3236. scale.y *= -1;
  3237. }
  3238. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3239. rotation.x = 0;
  3240. rotation.y = 0;
  3241. rotation.z = 0;
  3242. rotation.w = 1;
  3243. return false;
  3244. }
  3245. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3246. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3247. return true;
  3248. };
  3249. /**
  3250. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3251. */
  3252. Matrix.prototype.getRotationMatrix = function () {
  3253. var result = Matrix.Identity();
  3254. this.getRotationMatrixToRef(result);
  3255. return result;
  3256. };
  3257. /**
  3258. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3259. * Returns the current Matrix.
  3260. */
  3261. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3262. var m = this.m;
  3263. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3264. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3265. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3266. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3267. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3268. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3269. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3270. return this;
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Matrix set from the starting index of the passed array.
  3275. */
  3276. Matrix.FromArray = function (array, offset) {
  3277. var result = new Matrix();
  3278. if (!offset) {
  3279. offset = 0;
  3280. }
  3281. Matrix.FromArrayToRef(array, offset, result);
  3282. return result;
  3283. };
  3284. /**
  3285. * Sets the passed "result" matrix from the starting index of the passed array.
  3286. */
  3287. Matrix.FromArrayToRef = function (array, offset, result) {
  3288. for (var index = 0; index < 16; index++) {
  3289. result.m[index] = array[index + offset];
  3290. }
  3291. result._markAsUpdated();
  3292. };
  3293. /**
  3294. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3295. */
  3296. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3297. for (var index = 0; index < 16; index++) {
  3298. result.m[index] = array[index + offset] * scale;
  3299. }
  3300. result._markAsUpdated();
  3301. };
  3302. /**
  3303. * Sets the passed matrix "result" with the 16 passed floats.
  3304. */
  3305. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3306. result.m[0] = initialM11;
  3307. result.m[1] = initialM12;
  3308. result.m[2] = initialM13;
  3309. result.m[3] = initialM14;
  3310. result.m[4] = initialM21;
  3311. result.m[5] = initialM22;
  3312. result.m[6] = initialM23;
  3313. result.m[7] = initialM24;
  3314. result.m[8] = initialM31;
  3315. result.m[9] = initialM32;
  3316. result.m[10] = initialM33;
  3317. result.m[11] = initialM34;
  3318. result.m[12] = initialM41;
  3319. result.m[13] = initialM42;
  3320. result.m[14] = initialM43;
  3321. result.m[15] = initialM44;
  3322. result._markAsUpdated();
  3323. };
  3324. /**
  3325. * Returns the index-th row of the current matrix as a new Vector4.
  3326. */
  3327. Matrix.prototype.getRow = function (index) {
  3328. if (index < 0 || index > 3) {
  3329. return null;
  3330. }
  3331. var i = index * 4;
  3332. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3333. };
  3334. /**
  3335. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3336. * Returns the updated Matrix.
  3337. */
  3338. Matrix.prototype.setRow = function (index, row) {
  3339. if (index < 0 || index > 3) {
  3340. return this;
  3341. }
  3342. var i = index * 4;
  3343. this.m[i + 0] = row.x;
  3344. this.m[i + 1] = row.y;
  3345. this.m[i + 2] = row.z;
  3346. this.m[i + 3] = row.w;
  3347. this._markAsUpdated();
  3348. return this;
  3349. };
  3350. /**
  3351. * Compute the transpose of the matrix.
  3352. * Returns a new Matrix.
  3353. */
  3354. Matrix.prototype.transpose = function () {
  3355. return Matrix.Transpose(this);
  3356. };
  3357. /**
  3358. * Compute the transpose of the matrix.
  3359. * Returns the current matrix.
  3360. */
  3361. Matrix.prototype.transposeToRef = function (result) {
  3362. Matrix.TransposeToRef(this, result);
  3363. return this;
  3364. };
  3365. /**
  3366. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3367. * Returns the updated Matrix.
  3368. */
  3369. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3370. if (index < 0 || index > 3) {
  3371. return this;
  3372. }
  3373. var i = index * 4;
  3374. this.m[i + 0] = x;
  3375. this.m[i + 1] = y;
  3376. this.m[i + 2] = z;
  3377. this.m[i + 3] = w;
  3378. this._markAsUpdated();
  3379. return this;
  3380. };
  3381. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3382. /**
  3383. * Static identity matrix to be used as readonly matrix
  3384. * Must not be updated.
  3385. */
  3386. get: function () {
  3387. return Matrix._identityReadOnly;
  3388. },
  3389. enumerable: true,
  3390. configurable: true
  3391. });
  3392. /**
  3393. * Returns a new Matrix set from the 16 passed floats.
  3394. */
  3395. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3396. var result = new Matrix();
  3397. result.m[0] = initialM11;
  3398. result.m[1] = initialM12;
  3399. result.m[2] = initialM13;
  3400. result.m[3] = initialM14;
  3401. result.m[4] = initialM21;
  3402. result.m[5] = initialM22;
  3403. result.m[6] = initialM23;
  3404. result.m[7] = initialM24;
  3405. result.m[8] = initialM31;
  3406. result.m[9] = initialM32;
  3407. result.m[10] = initialM33;
  3408. result.m[11] = initialM34;
  3409. result.m[12] = initialM41;
  3410. result.m[13] = initialM42;
  3411. result.m[14] = initialM43;
  3412. result.m[15] = initialM44;
  3413. return result;
  3414. };
  3415. /**
  3416. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3417. */
  3418. Matrix.Compose = function (scale, rotation, translation) {
  3419. var result = Matrix.Identity();
  3420. Matrix.ComposeToRef(scale, rotation, translation, result);
  3421. return result;
  3422. };
  3423. /**
  3424. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3425. */
  3426. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3427. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3428. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3429. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3430. result.setTranslation(translation);
  3431. };
  3432. /**
  3433. * Returns a new indentity Matrix.
  3434. */
  3435. Matrix.Identity = function () {
  3436. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3437. };
  3438. /**
  3439. * Sets the passed "result" as an identity matrix.
  3440. */
  3441. Matrix.IdentityToRef = function (result) {
  3442. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3443. };
  3444. /**
  3445. * Returns a new zero Matrix.
  3446. */
  3447. Matrix.Zero = function () {
  3448. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3449. };
  3450. /**
  3451. * Returns a new rotation matrix for "angle" radians around the X axis.
  3452. */
  3453. Matrix.RotationX = function (angle) {
  3454. var result = new Matrix();
  3455. Matrix.RotationXToRef(angle, result);
  3456. return result;
  3457. };
  3458. /**
  3459. * Returns a new Matrix as the passed inverted one.
  3460. */
  3461. Matrix.Invert = function (source) {
  3462. var result = new Matrix();
  3463. source.invertToRef(result);
  3464. return result;
  3465. };
  3466. /**
  3467. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3468. */
  3469. Matrix.RotationXToRef = function (angle, result) {
  3470. var s = Math.sin(angle);
  3471. var c = Math.cos(angle);
  3472. result.m[0] = 1.0;
  3473. result.m[15] = 1.0;
  3474. result.m[5] = c;
  3475. result.m[10] = c;
  3476. result.m[9] = -s;
  3477. result.m[6] = s;
  3478. result.m[1] = 0.0;
  3479. result.m[2] = 0.0;
  3480. result.m[3] = 0.0;
  3481. result.m[4] = 0.0;
  3482. result.m[7] = 0.0;
  3483. result.m[8] = 0.0;
  3484. result.m[11] = 0.0;
  3485. result.m[12] = 0.0;
  3486. result.m[13] = 0.0;
  3487. result.m[14] = 0.0;
  3488. result._markAsUpdated();
  3489. };
  3490. /**
  3491. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3492. */
  3493. Matrix.RotationY = function (angle) {
  3494. var result = new Matrix();
  3495. Matrix.RotationYToRef(angle, result);
  3496. return result;
  3497. };
  3498. /**
  3499. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3500. */
  3501. Matrix.RotationYToRef = function (angle, result) {
  3502. var s = Math.sin(angle);
  3503. var c = Math.cos(angle);
  3504. result.m[5] = 1.0;
  3505. result.m[15] = 1.0;
  3506. result.m[0] = c;
  3507. result.m[2] = -s;
  3508. result.m[8] = s;
  3509. result.m[10] = c;
  3510. result.m[1] = 0.0;
  3511. result.m[3] = 0.0;
  3512. result.m[4] = 0.0;
  3513. result.m[6] = 0.0;
  3514. result.m[7] = 0.0;
  3515. result.m[9] = 0.0;
  3516. result.m[11] = 0.0;
  3517. result.m[12] = 0.0;
  3518. result.m[13] = 0.0;
  3519. result.m[14] = 0.0;
  3520. result._markAsUpdated();
  3521. };
  3522. /**
  3523. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3524. */
  3525. Matrix.RotationZ = function (angle) {
  3526. var result = new Matrix();
  3527. Matrix.RotationZToRef(angle, result);
  3528. return result;
  3529. };
  3530. /**
  3531. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3532. */
  3533. Matrix.RotationZToRef = function (angle, result) {
  3534. var s = Math.sin(angle);
  3535. var c = Math.cos(angle);
  3536. result.m[10] = 1.0;
  3537. result.m[15] = 1.0;
  3538. result.m[0] = c;
  3539. result.m[1] = s;
  3540. result.m[4] = -s;
  3541. result.m[5] = c;
  3542. result.m[2] = 0.0;
  3543. result.m[3] = 0.0;
  3544. result.m[6] = 0.0;
  3545. result.m[7] = 0.0;
  3546. result.m[8] = 0.0;
  3547. result.m[9] = 0.0;
  3548. result.m[11] = 0.0;
  3549. result.m[12] = 0.0;
  3550. result.m[13] = 0.0;
  3551. result.m[14] = 0.0;
  3552. result._markAsUpdated();
  3553. };
  3554. /**
  3555. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3556. */
  3557. Matrix.RotationAxis = function (axis, angle) {
  3558. var result = Matrix.Zero();
  3559. Matrix.RotationAxisToRef(axis, angle, result);
  3560. return result;
  3561. };
  3562. /**
  3563. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3564. */
  3565. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3566. var s = Math.sin(-angle);
  3567. var c = Math.cos(-angle);
  3568. var c1 = 1 - c;
  3569. axis.normalize();
  3570. result.m[0] = (axis.x * axis.x) * c1 + c;
  3571. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3572. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3573. result.m[3] = 0.0;
  3574. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3575. result.m[5] = (axis.y * axis.y) * c1 + c;
  3576. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3577. result.m[7] = 0.0;
  3578. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3579. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3580. result.m[10] = (axis.z * axis.z) * c1 + c;
  3581. result.m[11] = 0.0;
  3582. result.m[15] = 1.0;
  3583. result._markAsUpdated();
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3587. */
  3588. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3589. var result = new Matrix();
  3590. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3591. return result;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3595. */
  3596. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3597. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3598. this._tempQuaternion.toRotationMatrix(result);
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3602. */
  3603. Matrix.Scaling = function (x, y, z) {
  3604. var result = Matrix.Zero();
  3605. Matrix.ScalingToRef(x, y, z, result);
  3606. return result;
  3607. };
  3608. /**
  3609. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3610. */
  3611. Matrix.ScalingToRef = function (x, y, z, result) {
  3612. result.m[0] = x;
  3613. result.m[1] = 0.0;
  3614. result.m[2] = 0.0;
  3615. result.m[3] = 0.0;
  3616. result.m[4] = 0.0;
  3617. result.m[5] = y;
  3618. result.m[6] = 0.0;
  3619. result.m[7] = 0.0;
  3620. result.m[8] = 0.0;
  3621. result.m[9] = 0.0;
  3622. result.m[10] = z;
  3623. result.m[11] = 0.0;
  3624. result.m[12] = 0.0;
  3625. result.m[13] = 0.0;
  3626. result.m[14] = 0.0;
  3627. result.m[15] = 1.0;
  3628. result._markAsUpdated();
  3629. };
  3630. /**
  3631. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3632. */
  3633. Matrix.Translation = function (x, y, z) {
  3634. var result = Matrix.Identity();
  3635. Matrix.TranslationToRef(x, y, z, result);
  3636. return result;
  3637. };
  3638. /**
  3639. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3640. */
  3641. Matrix.TranslationToRef = function (x, y, z, result) {
  3642. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3643. };
  3644. /**
  3645. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3646. */
  3647. Matrix.Lerp = function (startValue, endValue, gradient) {
  3648. var result = Matrix.Zero();
  3649. for (var index = 0; index < 16; index++) {
  3650. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3651. }
  3652. result._markAsUpdated();
  3653. return result;
  3654. };
  3655. /**
  3656. * Returns a new Matrix whose values are computed by :
  3657. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3658. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3659. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3660. */
  3661. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3662. var startScale = new Vector3(0, 0, 0);
  3663. var startRotation = new Quaternion();
  3664. var startTranslation = new Vector3(0, 0, 0);
  3665. startValue.decompose(startScale, startRotation, startTranslation);
  3666. var endScale = new Vector3(0, 0, 0);
  3667. var endRotation = new Quaternion();
  3668. var endTranslation = new Vector3(0, 0, 0);
  3669. endValue.decompose(endScale, endRotation, endTranslation);
  3670. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3671. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3672. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3673. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3674. };
  3675. /**
  3676. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3677. * This methods works for a Left-Handed system.
  3678. */
  3679. Matrix.LookAtLH = function (eye, target, up) {
  3680. var result = Matrix.Zero();
  3681. Matrix.LookAtLHToRef(eye, target, up, result);
  3682. return result;
  3683. };
  3684. /**
  3685. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3686. * This methods works for a Left-Handed system.
  3687. */
  3688. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3689. // Z axis
  3690. target.subtractToRef(eye, this._zAxis);
  3691. this._zAxis.normalize();
  3692. // X axis
  3693. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3694. if (this._xAxis.lengthSquared() === 0) {
  3695. this._xAxis.x = 1.0;
  3696. }
  3697. else {
  3698. this._xAxis.normalize();
  3699. }
  3700. // Y axis
  3701. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3702. this._yAxis.normalize();
  3703. // Eye angles
  3704. var ex = -Vector3.Dot(this._xAxis, eye);
  3705. var ey = -Vector3.Dot(this._yAxis, eye);
  3706. var ez = -Vector3.Dot(this._zAxis, eye);
  3707. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3708. };
  3709. /**
  3710. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3711. * This methods works for a Right-Handed system.
  3712. */
  3713. Matrix.LookAtRH = function (eye, target, up) {
  3714. var result = Matrix.Zero();
  3715. Matrix.LookAtRHToRef(eye, target, up, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3720. * This methods works for a Left-Handed system.
  3721. */
  3722. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3723. // Z axis
  3724. eye.subtractToRef(target, this._zAxis);
  3725. this._zAxis.normalize();
  3726. // X axis
  3727. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3728. if (this._xAxis.lengthSquared() === 0) {
  3729. this._xAxis.x = 1.0;
  3730. }
  3731. else {
  3732. this._xAxis.normalize();
  3733. }
  3734. // Y axis
  3735. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3736. this._yAxis.normalize();
  3737. // Eye angles
  3738. var ex = -Vector3.Dot(this._xAxis, eye);
  3739. var ey = -Vector3.Dot(this._yAxis, eye);
  3740. var ez = -Vector3.Dot(this._zAxis, eye);
  3741. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3742. };
  3743. /**
  3744. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3745. */
  3746. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3747. var matrix = Matrix.Zero();
  3748. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3749. return matrix;
  3750. };
  3751. /**
  3752. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3753. */
  3754. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3755. var n = znear;
  3756. var f = zfar;
  3757. var a = 2.0 / width;
  3758. var b = 2.0 / height;
  3759. var c = 2.0 / (f - n);
  3760. var d = -(f + n) / (f - n);
  3761. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3762. };
  3763. /**
  3764. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3765. */
  3766. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3767. var matrix = Matrix.Zero();
  3768. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3769. return matrix;
  3770. };
  3771. /**
  3772. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3773. */
  3774. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3775. var n = znear;
  3776. var f = zfar;
  3777. var a = 2.0 / (right - left);
  3778. var b = 2.0 / (top - bottom);
  3779. var c = 2.0 / (f - n);
  3780. var d = -(f + n) / (f - n);
  3781. var i0 = (left + right) / (left - right);
  3782. var i1 = (top + bottom) / (bottom - top);
  3783. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3784. };
  3785. /**
  3786. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3787. */
  3788. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3789. var matrix = Matrix.Zero();
  3790. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3791. return matrix;
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3795. */
  3796. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3797. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3798. result.m[10] *= -1.0;
  3799. };
  3800. /**
  3801. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3802. */
  3803. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3804. var matrix = Matrix.Zero();
  3805. var n = znear;
  3806. var f = zfar;
  3807. var a = 2.0 * n / width;
  3808. var b = 2.0 * n / height;
  3809. var c = (f + n) / (f - n);
  3810. var d = -2.0 * f * n / (f - n);
  3811. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3812. return matrix;
  3813. };
  3814. /**
  3815. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3816. */
  3817. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3818. var matrix = Matrix.Zero();
  3819. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3820. return matrix;
  3821. };
  3822. /**
  3823. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3824. */
  3825. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3826. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3827. var n = znear;
  3828. var f = zfar;
  3829. var t = 1.0 / (Math.tan(fov * 0.5));
  3830. var a = isVerticalFovFixed ? (t / aspect) : t;
  3831. var b = isVerticalFovFixed ? t : (t * aspect);
  3832. var c = (f + n) / (f - n);
  3833. var d = -2.0 * f * n / (f - n);
  3834. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3835. };
  3836. /**
  3837. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3838. */
  3839. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3840. var matrix = Matrix.Zero();
  3841. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3842. return matrix;
  3843. };
  3844. /**
  3845. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3846. */
  3847. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3848. //alternatively this could be expressed as:
  3849. // m = PerspectiveFovLHToRef
  3850. // m[10] *= -1.0;
  3851. // m[11] *= -1.0;
  3852. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3853. var n = znear;
  3854. var f = zfar;
  3855. var t = 1.0 / (Math.tan(fov * 0.5));
  3856. var a = isVerticalFovFixed ? (t / aspect) : t;
  3857. var b = isVerticalFovFixed ? t : (t * aspect);
  3858. var c = -(f + n) / (f - n);
  3859. var d = -2 * f * n / (f - n);
  3860. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3861. };
  3862. /**
  3863. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3864. */
  3865. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3866. if (rightHanded === void 0) { rightHanded = false; }
  3867. var rightHandedFactor = rightHanded ? -1 : 1;
  3868. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3869. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3870. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3871. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3872. var xScale = 2.0 / (leftTan + rightTan);
  3873. var yScale = 2.0 / (upTan + downTan);
  3874. result.m[0] = xScale;
  3875. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3876. result.m[5] = yScale;
  3877. result.m[6] = result.m[7] = 0.0;
  3878. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3879. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3880. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3881. result.m[10] = -zfar / (znear - zfar);
  3882. result.m[11] = 1.0 * rightHandedFactor;
  3883. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3884. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3885. // result.m[14] = (znear * zfar) / (znear - zfar);
  3886. result._markAsUpdated();
  3887. };
  3888. /**
  3889. * Returns the final transformation matrix : world * view * projection * viewport
  3890. */
  3891. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3892. var cw = viewport.width;
  3893. var ch = viewport.height;
  3894. var cx = viewport.x;
  3895. var cy = viewport.y;
  3896. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3897. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3898. };
  3899. /**
  3900. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3901. */
  3902. Matrix.GetAsMatrix2x2 = function (matrix) {
  3903. return new Float32Array([
  3904. matrix.m[0], matrix.m[1],
  3905. matrix.m[4], matrix.m[5]
  3906. ]);
  3907. };
  3908. /**
  3909. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3910. */
  3911. Matrix.GetAsMatrix3x3 = function (matrix) {
  3912. return new Float32Array([
  3913. matrix.m[0], matrix.m[1], matrix.m[2],
  3914. matrix.m[4], matrix.m[5], matrix.m[6],
  3915. matrix.m[8], matrix.m[9], matrix.m[10]
  3916. ]);
  3917. };
  3918. /**
  3919. * Compute the transpose of the passed Matrix.
  3920. * Returns a new Matrix.
  3921. */
  3922. Matrix.Transpose = function (matrix) {
  3923. var result = new Matrix();
  3924. Matrix.TransposeToRef(matrix, result);
  3925. return result;
  3926. };
  3927. /**
  3928. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3929. */
  3930. Matrix.TransposeToRef = function (matrix, result) {
  3931. result.m[0] = matrix.m[0];
  3932. result.m[1] = matrix.m[4];
  3933. result.m[2] = matrix.m[8];
  3934. result.m[3] = matrix.m[12];
  3935. result.m[4] = matrix.m[1];
  3936. result.m[5] = matrix.m[5];
  3937. result.m[6] = matrix.m[9];
  3938. result.m[7] = matrix.m[13];
  3939. result.m[8] = matrix.m[2];
  3940. result.m[9] = matrix.m[6];
  3941. result.m[10] = matrix.m[10];
  3942. result.m[11] = matrix.m[14];
  3943. result.m[12] = matrix.m[3];
  3944. result.m[13] = matrix.m[7];
  3945. result.m[14] = matrix.m[11];
  3946. result.m[15] = matrix.m[15];
  3947. };
  3948. /**
  3949. * Returns a new Matrix as the reflection matrix across the passed plane.
  3950. */
  3951. Matrix.Reflection = function (plane) {
  3952. var matrix = new Matrix();
  3953. Matrix.ReflectionToRef(plane, matrix);
  3954. return matrix;
  3955. };
  3956. /**
  3957. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3958. */
  3959. Matrix.ReflectionToRef = function (plane, result) {
  3960. plane.normalize();
  3961. var x = plane.normal.x;
  3962. var y = plane.normal.y;
  3963. var z = plane.normal.z;
  3964. var temp = -2 * x;
  3965. var temp2 = -2 * y;
  3966. var temp3 = -2 * z;
  3967. result.m[0] = (temp * x) + 1;
  3968. result.m[1] = temp2 * x;
  3969. result.m[2] = temp3 * x;
  3970. result.m[3] = 0.0;
  3971. result.m[4] = temp * y;
  3972. result.m[5] = (temp2 * y) + 1;
  3973. result.m[6] = temp3 * y;
  3974. result.m[7] = 0.0;
  3975. result.m[8] = temp * z;
  3976. result.m[9] = temp2 * z;
  3977. result.m[10] = (temp3 * z) + 1;
  3978. result.m[11] = 0.0;
  3979. result.m[12] = temp * plane.d;
  3980. result.m[13] = temp2 * plane.d;
  3981. result.m[14] = temp3 * plane.d;
  3982. result.m[15] = 1.0;
  3983. result._markAsUpdated();
  3984. };
  3985. /**
  3986. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3987. */
  3988. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3989. result.m[0] = xaxis.x;
  3990. result.m[1] = xaxis.y;
  3991. result.m[2] = xaxis.z;
  3992. result.m[3] = 0.0;
  3993. result.m[4] = yaxis.x;
  3994. result.m[5] = yaxis.y;
  3995. result.m[6] = yaxis.z;
  3996. result.m[7] = 0.0;
  3997. result.m[8] = zaxis.x;
  3998. result.m[9] = zaxis.y;
  3999. result.m[10] = zaxis.z;
  4000. result.m[11] = 0.0;
  4001. result.m[12] = 0.0;
  4002. result.m[13] = 0.0;
  4003. result.m[14] = 0.0;
  4004. result.m[15] = 1.0;
  4005. result._markAsUpdated();
  4006. };
  4007. /**
  4008. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4009. */
  4010. Matrix.FromQuaternionToRef = function (quat, result) {
  4011. var xx = quat.x * quat.x;
  4012. var yy = quat.y * quat.y;
  4013. var zz = quat.z * quat.z;
  4014. var xy = quat.x * quat.y;
  4015. var zw = quat.z * quat.w;
  4016. var zx = quat.z * quat.x;
  4017. var yw = quat.y * quat.w;
  4018. var yz = quat.y * quat.z;
  4019. var xw = quat.x * quat.w;
  4020. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4021. result.m[1] = 2.0 * (xy + zw);
  4022. result.m[2] = 2.0 * (zx - yw);
  4023. result.m[3] = 0.0;
  4024. result.m[4] = 2.0 * (xy - zw);
  4025. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4026. result.m[6] = 2.0 * (yz + xw);
  4027. result.m[7] = 0.0;
  4028. result.m[8] = 2.0 * (zx + yw);
  4029. result.m[9] = 2.0 * (yz - xw);
  4030. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4031. result.m[11] = 0.0;
  4032. result.m[12] = 0.0;
  4033. result.m[13] = 0.0;
  4034. result.m[14] = 0.0;
  4035. result.m[15] = 1.0;
  4036. result._markAsUpdated();
  4037. };
  4038. Matrix._tempQuaternion = new Quaternion();
  4039. Matrix._xAxis = Vector3.Zero();
  4040. Matrix._yAxis = Vector3.Zero();
  4041. Matrix._zAxis = Vector3.Zero();
  4042. Matrix._updateFlagSeed = 0;
  4043. Matrix._identityReadOnly = Matrix.Identity();
  4044. return Matrix;
  4045. }());
  4046. BABYLON.Matrix = Matrix;
  4047. var Plane = /** @class */ (function () {
  4048. /**
  4049. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4050. */
  4051. function Plane(a, b, c, d) {
  4052. this.normal = new Vector3(a, b, c);
  4053. this.d = d;
  4054. }
  4055. /**
  4056. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4057. */
  4058. Plane.prototype.asArray = function () {
  4059. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4060. };
  4061. // Methods
  4062. /**
  4063. * Returns a new plane copied from the current Plane.
  4064. */
  4065. Plane.prototype.clone = function () {
  4066. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4067. };
  4068. /**
  4069. * Returns the string "Plane".
  4070. */
  4071. Plane.prototype.getClassName = function () {
  4072. return "Plane";
  4073. };
  4074. /**
  4075. * Returns the Plane hash code.
  4076. */
  4077. Plane.prototype.getHashCode = function () {
  4078. var hash = this.normal.getHashCode();
  4079. hash = (hash * 397) ^ (this.d || 0);
  4080. return hash;
  4081. };
  4082. /**
  4083. * Normalize the current Plane in place.
  4084. * Returns the updated Plane.
  4085. */
  4086. Plane.prototype.normalize = function () {
  4087. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4088. var magnitude = 0.0;
  4089. if (norm !== 0) {
  4090. magnitude = 1.0 / norm;
  4091. }
  4092. this.normal.x *= magnitude;
  4093. this.normal.y *= magnitude;
  4094. this.normal.z *= magnitude;
  4095. this.d *= magnitude;
  4096. return this;
  4097. };
  4098. /**
  4099. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4100. */
  4101. Plane.prototype.transform = function (transformation) {
  4102. var transposedMatrix = Matrix.Transpose(transformation);
  4103. var x = this.normal.x;
  4104. var y = this.normal.y;
  4105. var z = this.normal.z;
  4106. var d = this.d;
  4107. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4108. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4109. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4110. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4111. return new Plane(normalX, normalY, normalZ, finalD);
  4112. };
  4113. /**
  4114. * Returns the dot product (float) of the point coordinates and the plane normal.
  4115. */
  4116. Plane.prototype.dotCoordinate = function (point) {
  4117. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4118. };
  4119. /**
  4120. * Updates the current Plane from the plane defined by the three passed points.
  4121. * Returns the updated Plane.
  4122. */
  4123. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4124. var x1 = point2.x - point1.x;
  4125. var y1 = point2.y - point1.y;
  4126. var z1 = point2.z - point1.z;
  4127. var x2 = point3.x - point1.x;
  4128. var y2 = point3.y - point1.y;
  4129. var z2 = point3.z - point1.z;
  4130. var yz = (y1 * z2) - (z1 * y2);
  4131. var xz = (z1 * x2) - (x1 * z2);
  4132. var xy = (x1 * y2) - (y1 * x2);
  4133. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4134. var invPyth;
  4135. if (pyth !== 0) {
  4136. invPyth = 1.0 / pyth;
  4137. }
  4138. else {
  4139. invPyth = 0.0;
  4140. }
  4141. this.normal.x = yz * invPyth;
  4142. this.normal.y = xz * invPyth;
  4143. this.normal.z = xy * invPyth;
  4144. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4145. return this;
  4146. };
  4147. /**
  4148. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4149. */
  4150. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4151. var dot = Vector3.Dot(this.normal, direction);
  4152. return (dot <= epsilon);
  4153. };
  4154. /**
  4155. * Returns the signed distance (float) from the passed point to the Plane.
  4156. */
  4157. Plane.prototype.signedDistanceTo = function (point) {
  4158. return Vector3.Dot(point, this.normal) + this.d;
  4159. };
  4160. // Statics
  4161. /**
  4162. * Returns a new Plane from the passed array.
  4163. */
  4164. Plane.FromArray = function (array) {
  4165. return new Plane(array[0], array[1], array[2], array[3]);
  4166. };
  4167. /**
  4168. * Returns a new Plane defined by the three passed points.
  4169. */
  4170. Plane.FromPoints = function (point1, point2, point3) {
  4171. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4172. result.copyFromPoints(point1, point2, point3);
  4173. return result;
  4174. };
  4175. /**
  4176. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4177. * Note : the vector "normal" is updated because normalized.
  4178. */
  4179. Plane.FromPositionAndNormal = function (origin, normal) {
  4180. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4181. normal.normalize();
  4182. result.normal = normal;
  4183. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4184. return result;
  4185. };
  4186. /**
  4187. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4188. */
  4189. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4190. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4191. return Vector3.Dot(point, normal) + d;
  4192. };
  4193. return Plane;
  4194. }());
  4195. BABYLON.Plane = Plane;
  4196. var Viewport = /** @class */ (function () {
  4197. /**
  4198. * Creates a Viewport object located at (x, y) and sized (width, height).
  4199. */
  4200. function Viewport(x, y, width, height) {
  4201. this.x = x;
  4202. this.y = y;
  4203. this.width = width;
  4204. this.height = height;
  4205. }
  4206. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4207. if (renderWidthOrEngine.getRenderWidth) {
  4208. var engine = renderWidthOrEngine;
  4209. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4210. }
  4211. var renderWidth = renderWidthOrEngine;
  4212. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4213. };
  4214. /**
  4215. * Returns a new Viewport copied from the current one.
  4216. */
  4217. Viewport.prototype.clone = function () {
  4218. return new Viewport(this.x, this.y, this.width, this.height);
  4219. };
  4220. return Viewport;
  4221. }());
  4222. BABYLON.Viewport = Viewport;
  4223. var Frustum = /** @class */ (function () {
  4224. function Frustum() {
  4225. }
  4226. /**
  4227. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4228. */
  4229. Frustum.GetPlanes = function (transform) {
  4230. var frustumPlanes = [];
  4231. for (var index = 0; index < 6; index++) {
  4232. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4233. }
  4234. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4235. return frustumPlanes;
  4236. };
  4237. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4238. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4239. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4240. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4241. frustumPlane.d = transform.m[15] + transform.m[14];
  4242. frustumPlane.normalize();
  4243. };
  4244. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4245. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4246. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4247. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4248. frustumPlane.d = transform.m[15] - transform.m[14];
  4249. frustumPlane.normalize();
  4250. };
  4251. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4252. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4253. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4254. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4255. frustumPlane.d = transform.m[15] + transform.m[12];
  4256. frustumPlane.normalize();
  4257. };
  4258. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4259. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4260. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4261. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4262. frustumPlane.d = transform.m[15] - transform.m[12];
  4263. frustumPlane.normalize();
  4264. };
  4265. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4266. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4267. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4268. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4269. frustumPlane.d = transform.m[15] - transform.m[13];
  4270. frustumPlane.normalize();
  4271. };
  4272. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4273. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4274. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4275. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4276. frustumPlane.d = transform.m[15] + transform.m[13];
  4277. frustumPlane.normalize();
  4278. };
  4279. /**
  4280. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4281. */
  4282. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4283. // Near
  4284. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4285. // Far
  4286. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4287. // Left
  4288. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4289. // Right
  4290. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4291. // Top
  4292. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4293. // Bottom
  4294. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4295. };
  4296. return Frustum;
  4297. }());
  4298. BABYLON.Frustum = Frustum;
  4299. var Space;
  4300. (function (Space) {
  4301. Space[Space["LOCAL"] = 0] = "LOCAL";
  4302. Space[Space["WORLD"] = 1] = "WORLD";
  4303. Space[Space["BONE"] = 2] = "BONE";
  4304. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4305. var Axis = /** @class */ (function () {
  4306. function Axis() {
  4307. }
  4308. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4309. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4310. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4311. return Axis;
  4312. }());
  4313. BABYLON.Axis = Axis;
  4314. ;
  4315. var BezierCurve = /** @class */ (function () {
  4316. function BezierCurve() {
  4317. }
  4318. /**
  4319. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4320. */
  4321. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4322. // Extract X (which is equal to time here)
  4323. var f0 = 1 - 3 * x2 + 3 * x1;
  4324. var f1 = 3 * x2 - 6 * x1;
  4325. var f2 = 3 * x1;
  4326. var refinedT = t;
  4327. for (var i = 0; i < 5; i++) {
  4328. var refinedT2 = refinedT * refinedT;
  4329. var refinedT3 = refinedT2 * refinedT;
  4330. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4331. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4332. refinedT -= (x - t) * slope;
  4333. refinedT = Math.min(1, Math.max(0, refinedT));
  4334. }
  4335. // Resolve cubic bezier for the given x
  4336. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4337. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4338. Math.pow(refinedT, 3);
  4339. };
  4340. return BezierCurve;
  4341. }());
  4342. BABYLON.BezierCurve = BezierCurve;
  4343. var Orientation;
  4344. (function (Orientation) {
  4345. Orientation[Orientation["CW"] = 0] = "CW";
  4346. Orientation[Orientation["CCW"] = 1] = "CCW";
  4347. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4348. var Angle = /** @class */ (function () {
  4349. /**
  4350. * Creates an Angle object of "radians" radians (float).
  4351. */
  4352. function Angle(radians) {
  4353. var _this = this;
  4354. /**
  4355. * Returns the Angle value in degrees (float).
  4356. */
  4357. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4358. /**
  4359. * Returns the Angle value in radians (float).
  4360. */
  4361. this.radians = function () { return _this._radians; };
  4362. this._radians = radians;
  4363. if (this._radians < 0.0)
  4364. this._radians += (2.0 * Math.PI);
  4365. }
  4366. /**
  4367. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4368. */
  4369. Angle.BetweenTwoPoints = function (a, b) {
  4370. var delta = b.subtract(a);
  4371. var theta = Math.atan2(delta.y, delta.x);
  4372. return new Angle(theta);
  4373. };
  4374. /**
  4375. * Returns a new Angle object from the passed float in radians.
  4376. */
  4377. Angle.FromRadians = function (radians) {
  4378. return new Angle(radians);
  4379. };
  4380. /**
  4381. * Returns a new Angle object from the passed float in degrees.
  4382. */
  4383. Angle.FromDegrees = function (degrees) {
  4384. return new Angle(degrees * Math.PI / 180.0);
  4385. };
  4386. return Angle;
  4387. }());
  4388. BABYLON.Angle = Angle;
  4389. var Arc2 = /** @class */ (function () {
  4390. /**
  4391. * Creates an Arc object from the three passed points : start, middle and end.
  4392. */
  4393. function Arc2(startPoint, midPoint, endPoint) {
  4394. this.startPoint = startPoint;
  4395. this.midPoint = midPoint;
  4396. this.endPoint = endPoint;
  4397. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4398. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4399. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4400. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4401. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4402. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4403. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4404. var a1 = this.startAngle.degrees();
  4405. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4406. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4407. // angles correction
  4408. if (a2 - a1 > +180.0)
  4409. a2 -= 360.0;
  4410. if (a2 - a1 < -180.0)
  4411. a2 += 360.0;
  4412. if (a3 - a2 > +180.0)
  4413. a3 -= 360.0;
  4414. if (a3 - a2 < -180.0)
  4415. a3 += 360.0;
  4416. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4417. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4418. }
  4419. return Arc2;
  4420. }());
  4421. BABYLON.Arc2 = Arc2;
  4422. var Path2 = /** @class */ (function () {
  4423. /**
  4424. * Creates a Path2 object from the starting 2D coordinates x and y.
  4425. */
  4426. function Path2(x, y) {
  4427. this._points = new Array();
  4428. this._length = 0.0;
  4429. this.closed = false;
  4430. this._points.push(new Vector2(x, y));
  4431. }
  4432. /**
  4433. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4434. * Returns the updated Path2.
  4435. */
  4436. Path2.prototype.addLineTo = function (x, y) {
  4437. if (closed) {
  4438. //Tools.Error("cannot add lines to closed paths");
  4439. return this;
  4440. }
  4441. var newPoint = new Vector2(x, y);
  4442. var previousPoint = this._points[this._points.length - 1];
  4443. this._points.push(newPoint);
  4444. this._length += newPoint.subtract(previousPoint).length();
  4445. return this;
  4446. };
  4447. /**
  4448. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4449. * Returns the updated Path2.
  4450. */
  4451. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4452. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4453. if (closed) {
  4454. //Tools.Error("cannot add arcs to closed paths");
  4455. return this;
  4456. }
  4457. var startPoint = this._points[this._points.length - 1];
  4458. var midPoint = new Vector2(midX, midY);
  4459. var endPoint = new Vector2(endX, endY);
  4460. var arc = new Arc2(startPoint, midPoint, endPoint);
  4461. var increment = arc.angle.radians() / numberOfSegments;
  4462. if (arc.orientation === Orientation.CW)
  4463. increment *= -1;
  4464. var currentAngle = arc.startAngle.radians() + increment;
  4465. for (var i = 0; i < numberOfSegments; i++) {
  4466. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4467. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4468. this.addLineTo(x, y);
  4469. currentAngle += increment;
  4470. }
  4471. return this;
  4472. };
  4473. /**
  4474. * Closes the Path2.
  4475. * Returns the Path2.
  4476. */
  4477. Path2.prototype.close = function () {
  4478. this.closed = true;
  4479. return this;
  4480. };
  4481. /**
  4482. * Returns the Path2 total length (float).
  4483. */
  4484. Path2.prototype.length = function () {
  4485. var result = this._length;
  4486. if (!this.closed) {
  4487. var lastPoint = this._points[this._points.length - 1];
  4488. var firstPoint = this._points[0];
  4489. result += (firstPoint.subtract(lastPoint).length());
  4490. }
  4491. return result;
  4492. };
  4493. /**
  4494. * Returns the Path2 internal array of points.
  4495. */
  4496. Path2.prototype.getPoints = function () {
  4497. return this._points;
  4498. };
  4499. /**
  4500. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4501. */
  4502. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4503. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4504. //Tools.Error("normalized length position should be between 0 and 1.");
  4505. return Vector2.Zero();
  4506. }
  4507. var lengthPosition = normalizedLengthPosition * this.length();
  4508. var previousOffset = 0;
  4509. for (var i = 0; i < this._points.length; i++) {
  4510. var j = (i + 1) % this._points.length;
  4511. var a = this._points[i];
  4512. var b = this._points[j];
  4513. var bToA = b.subtract(a);
  4514. var nextOffset = (bToA.length() + previousOffset);
  4515. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4516. var dir = bToA.normalize();
  4517. var localOffset = lengthPosition - previousOffset;
  4518. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4519. }
  4520. previousOffset = nextOffset;
  4521. }
  4522. //Tools.Error("internal error");
  4523. return Vector2.Zero();
  4524. };
  4525. /**
  4526. * Returns a new Path2 starting at the coordinates (x, y).
  4527. */
  4528. Path2.StartingAt = function (x, y) {
  4529. return new Path2(x, y);
  4530. };
  4531. return Path2;
  4532. }());
  4533. BABYLON.Path2 = Path2;
  4534. var Path3D = /** @class */ (function () {
  4535. /**
  4536. * new Path3D(path, normal, raw)
  4537. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4538. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4539. * path : an array of Vector3, the curve axis of the Path3D
  4540. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4541. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4542. */
  4543. function Path3D(path, firstNormal, raw) {
  4544. if (firstNormal === void 0) { firstNormal = null; }
  4545. this.path = path;
  4546. this._curve = new Array();
  4547. this._distances = new Array();
  4548. this._tangents = new Array();
  4549. this._normals = new Array();
  4550. this._binormals = new Array();
  4551. for (var p = 0; p < path.length; p++) {
  4552. this._curve[p] = path[p].clone(); // hard copy
  4553. }
  4554. this._raw = raw || false;
  4555. this._compute(firstNormal);
  4556. }
  4557. /**
  4558. * Returns the Path3D array of successive Vector3 designing its curve.
  4559. */
  4560. Path3D.prototype.getCurve = function () {
  4561. return this._curve;
  4562. };
  4563. /**
  4564. * Returns an array populated with tangent vectors on each Path3D curve point.
  4565. */
  4566. Path3D.prototype.getTangents = function () {
  4567. return this._tangents;
  4568. };
  4569. /**
  4570. * Returns an array populated with normal vectors on each Path3D curve point.
  4571. */
  4572. Path3D.prototype.getNormals = function () {
  4573. return this._normals;
  4574. };
  4575. /**
  4576. * Returns an array populated with binormal vectors on each Path3D curve point.
  4577. */
  4578. Path3D.prototype.getBinormals = function () {
  4579. return this._binormals;
  4580. };
  4581. /**
  4582. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4583. */
  4584. Path3D.prototype.getDistances = function () {
  4585. return this._distances;
  4586. };
  4587. /**
  4588. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4589. * Returns the same object updated.
  4590. */
  4591. Path3D.prototype.update = function (path, firstNormal) {
  4592. if (firstNormal === void 0) { firstNormal = null; }
  4593. for (var p = 0; p < path.length; p++) {
  4594. this._curve[p].x = path[p].x;
  4595. this._curve[p].y = path[p].y;
  4596. this._curve[p].z = path[p].z;
  4597. }
  4598. this._compute(firstNormal);
  4599. return this;
  4600. };
  4601. // private function compute() : computes tangents, normals and binormals
  4602. Path3D.prototype._compute = function (firstNormal) {
  4603. var l = this._curve.length;
  4604. // first and last tangents
  4605. this._tangents[0] = this._getFirstNonNullVector(0);
  4606. if (!this._raw) {
  4607. this._tangents[0].normalize();
  4608. }
  4609. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4610. if (!this._raw) {
  4611. this._tangents[l - 1].normalize();
  4612. }
  4613. // normals and binormals at first point : arbitrary vector with _normalVector()
  4614. var tg0 = this._tangents[0];
  4615. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4616. this._normals[0] = pp0;
  4617. if (!this._raw) {
  4618. this._normals[0].normalize();
  4619. }
  4620. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4621. if (!this._raw) {
  4622. this._binormals[0].normalize();
  4623. }
  4624. this._distances[0] = 0.0;
  4625. // normals and binormals : next points
  4626. var prev; // previous vector (segment)
  4627. var cur; // current vector (segment)
  4628. var curTang; // current tangent
  4629. // previous normal
  4630. var prevBinor; // previous binormal
  4631. for (var i = 1; i < l; i++) {
  4632. // tangents
  4633. prev = this._getLastNonNullVector(i);
  4634. if (i < l - 1) {
  4635. cur = this._getFirstNonNullVector(i);
  4636. this._tangents[i] = prev.add(cur);
  4637. this._tangents[i].normalize();
  4638. }
  4639. this._distances[i] = this._distances[i - 1] + prev.length();
  4640. // normals and binormals
  4641. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4642. curTang = this._tangents[i];
  4643. prevBinor = this._binormals[i - 1];
  4644. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4645. if (!this._raw) {
  4646. this._normals[i].normalize();
  4647. }
  4648. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4649. if (!this._raw) {
  4650. this._binormals[i].normalize();
  4651. }
  4652. }
  4653. };
  4654. // private function getFirstNonNullVector(index)
  4655. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4656. Path3D.prototype._getFirstNonNullVector = function (index) {
  4657. var i = 1;
  4658. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4659. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4660. i++;
  4661. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4662. }
  4663. return nNVector;
  4664. };
  4665. // private function getLastNonNullVector(index)
  4666. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4667. Path3D.prototype._getLastNonNullVector = function (index) {
  4668. var i = 1;
  4669. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4670. while (nLVector.length() === 0 && index > i + 1) {
  4671. i++;
  4672. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4673. }
  4674. return nLVector;
  4675. };
  4676. // private function normalVector(v0, vt, va) :
  4677. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4678. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4679. Path3D.prototype._normalVector = function (v0, vt, va) {
  4680. var normal0;
  4681. var tgl = vt.length();
  4682. if (tgl === 0.0) {
  4683. tgl = 1.0;
  4684. }
  4685. if (va === undefined || va === null) {
  4686. var point;
  4687. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4688. point = new Vector3(0.0, -1.0, 0.0);
  4689. }
  4690. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4691. point = new Vector3(1.0, 0.0, 0.0);
  4692. }
  4693. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4694. point = new Vector3(0.0, 0.0, 1.0);
  4695. }
  4696. else {
  4697. point = Vector3.Zero();
  4698. }
  4699. normal0 = Vector3.Cross(vt, point);
  4700. }
  4701. else {
  4702. normal0 = Vector3.Cross(vt, va);
  4703. Vector3.CrossToRef(normal0, vt, normal0);
  4704. }
  4705. normal0.normalize();
  4706. return normal0;
  4707. };
  4708. return Path3D;
  4709. }());
  4710. BABYLON.Path3D = Path3D;
  4711. var Curve3 = /** @class */ (function () {
  4712. /**
  4713. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4714. * A Curve3 is designed from a series of successive Vector3.
  4715. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4716. */
  4717. function Curve3(points) {
  4718. this._length = 0.0;
  4719. this._points = points;
  4720. this._length = this._computeLength(points);
  4721. }
  4722. /**
  4723. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4724. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4725. * @param v1 (Vector3) the control point
  4726. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4727. * @param nbPoints (integer) the wanted number of points in the curve
  4728. */
  4729. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4730. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4731. var bez = new Array();
  4732. var equation = function (t, val0, val1, val2) {
  4733. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4734. return res;
  4735. };
  4736. for (var i = 0; i <= nbPoints; i++) {
  4737. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4738. }
  4739. return new Curve3(bez);
  4740. };
  4741. /**
  4742. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4743. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4744. * @param v1 (Vector3) the first control point
  4745. * @param v2 (Vector3) the second control point
  4746. * @param v3 (Vector3) the end point of the Cubic Bezier
  4747. * @param nbPoints (integer) the wanted number of points in the curve
  4748. */
  4749. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4750. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4751. var bez = new Array();
  4752. var equation = function (t, val0, val1, val2, val3) {
  4753. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4754. return res;
  4755. };
  4756. for (var i = 0; i <= nbPoints; i++) {
  4757. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4758. }
  4759. return new Curve3(bez);
  4760. };
  4761. /**
  4762. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4763. * @param p1 (Vector3) the origin point of the Hermite Spline
  4764. * @param t1 (Vector3) the tangent vector at the origin point
  4765. * @param p2 (Vector3) the end point of the Hermite Spline
  4766. * @param t2 (Vector3) the tangent vector at the end point
  4767. * @param nbPoints (integer) the wanted number of points in the curve
  4768. */
  4769. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4770. var hermite = new Array();
  4771. var step = 1.0 / nbPoints;
  4772. for (var i = 0; i <= nbPoints; i++) {
  4773. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4774. }
  4775. return new Curve3(hermite);
  4776. };
  4777. /**
  4778. * Returns a Curve3 object along a CatmullRom Spline curve :
  4779. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4780. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4781. */
  4782. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4783. var totalPoints = new Array();
  4784. totalPoints.push(points[0].clone());
  4785. Array.prototype.push.apply(totalPoints, points);
  4786. totalPoints.push(points[points.length - 1].clone());
  4787. var catmullRom = new Array();
  4788. var step = 1.0 / nbPoints;
  4789. var amount = 0.0;
  4790. for (var i = 0; i < totalPoints.length - 3; i++) {
  4791. amount = 0;
  4792. for (var c = 0; c < nbPoints; c++) {
  4793. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4794. amount += step;
  4795. }
  4796. }
  4797. i--;
  4798. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4799. return new Curve3(catmullRom);
  4800. };
  4801. /**
  4802. * Returns the Curve3 stored array of successive Vector3
  4803. */
  4804. Curve3.prototype.getPoints = function () {
  4805. return this._points;
  4806. };
  4807. /**
  4808. * Returns the computed length (float) of the curve.
  4809. */
  4810. Curve3.prototype.length = function () {
  4811. return this._length;
  4812. };
  4813. /**
  4814. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4815. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4816. * curveA and curveB keep unchanged.
  4817. */
  4818. Curve3.prototype.continue = function (curve) {
  4819. var lastPoint = this._points[this._points.length - 1];
  4820. var continuedPoints = this._points.slice();
  4821. var curvePoints = curve.getPoints();
  4822. for (var i = 1; i < curvePoints.length; i++) {
  4823. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4824. }
  4825. var continuedCurve = new Curve3(continuedPoints);
  4826. return continuedCurve;
  4827. };
  4828. Curve3.prototype._computeLength = function (path) {
  4829. var l = 0;
  4830. for (var i = 1; i < path.length; i++) {
  4831. l += (path[i].subtract(path[i - 1])).length();
  4832. }
  4833. return l;
  4834. };
  4835. return Curve3;
  4836. }());
  4837. BABYLON.Curve3 = Curve3;
  4838. // Vertex formats
  4839. var PositionNormalVertex = /** @class */ (function () {
  4840. function PositionNormalVertex(position, normal) {
  4841. if (position === void 0) { position = Vector3.Zero(); }
  4842. if (normal === void 0) { normal = Vector3.Up(); }
  4843. this.position = position;
  4844. this.normal = normal;
  4845. }
  4846. PositionNormalVertex.prototype.clone = function () {
  4847. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4848. };
  4849. return PositionNormalVertex;
  4850. }());
  4851. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4852. var PositionNormalTextureVertex = /** @class */ (function () {
  4853. function PositionNormalTextureVertex(position, normal, uv) {
  4854. if (position === void 0) { position = Vector3.Zero(); }
  4855. if (normal === void 0) { normal = Vector3.Up(); }
  4856. if (uv === void 0) { uv = Vector2.Zero(); }
  4857. this.position = position;
  4858. this.normal = normal;
  4859. this.uv = uv;
  4860. }
  4861. PositionNormalTextureVertex.prototype.clone = function () {
  4862. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4863. };
  4864. return PositionNormalTextureVertex;
  4865. }());
  4866. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4867. // Temporary pre-allocated objects for engine internal use
  4868. // usage in any internal function :
  4869. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4870. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4871. var Tmp = /** @class */ (function () {
  4872. function Tmp() {
  4873. }
  4874. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4875. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4876. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4877. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4878. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4879. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4880. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4881. Matrix.Zero(), Matrix.Zero(),
  4882. Matrix.Zero(), Matrix.Zero(),
  4883. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4884. return Tmp;
  4885. }());
  4886. BABYLON.Tmp = Tmp;
  4887. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4888. var MathTmp = /** @class */ (function () {
  4889. function MathTmp() {
  4890. }
  4891. MathTmp.Vector3 = [Vector3.Zero()];
  4892. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4893. MathTmp.Quaternion = [Quaternion.Zero()];
  4894. return MathTmp;
  4895. }());
  4896. })(BABYLON || (BABYLON = {}));
  4897. //# sourceMappingURL=babylon.math.js.map
  4898. var BABYLON;
  4899. (function (BABYLON) {
  4900. var Scalar = /** @class */ (function () {
  4901. function Scalar() {
  4902. }
  4903. /**
  4904. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4905. */
  4906. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4907. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4908. var num = a - b;
  4909. return -epsilon <= num && num <= epsilon;
  4910. };
  4911. /**
  4912. * Returns a string : the upper case translation of the number i to hexadecimal.
  4913. */
  4914. Scalar.ToHex = function (i) {
  4915. var str = i.toString(16);
  4916. if (i <= 15) {
  4917. return ("0" + str).toUpperCase();
  4918. }
  4919. return str.toUpperCase();
  4920. };
  4921. /**
  4922. * Returns -1 if value is negative and +1 is value is positive.
  4923. * Returns the value itself if it's equal to zero.
  4924. */
  4925. Scalar.Sign = function (value) {
  4926. value = +value; // convert to a number
  4927. if (value === 0 || isNaN(value))
  4928. return value;
  4929. return value > 0 ? 1 : -1;
  4930. };
  4931. /**
  4932. * Returns the value itself if it's between min and max.
  4933. * Returns min if the value is lower than min.
  4934. * Returns max if the value is greater than max.
  4935. */
  4936. Scalar.Clamp = function (value, min, max) {
  4937. if (min === void 0) { min = 0; }
  4938. if (max === void 0) { max = 1; }
  4939. return Math.min(max, Math.max(min, value));
  4940. };
  4941. /**
  4942. * Returns the log2 of value.
  4943. */
  4944. Scalar.Log2 = function (value) {
  4945. return Math.log(value) * Math.LOG2E;
  4946. };
  4947. /**
  4948. * Loops the value, so that it is never larger than length and never smaller than 0.
  4949. *
  4950. * This is similar to the modulo operator but it works with floating point numbers.
  4951. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4952. * With t = 5 and length = 2.5, the result would be 0.0.
  4953. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4954. */
  4955. Scalar.Repeat = function (value, length) {
  4956. return value - Math.floor(value / length) * length;
  4957. };
  4958. /**
  4959. * Normalize the value between 0.0 and 1.0 using min and max values
  4960. */
  4961. Scalar.Normalize = function (value, min, max) {
  4962. return (value - min) / (max - min);
  4963. };
  4964. /**
  4965. * Denormalize the value from 0.0 and 1.0 using min and max values
  4966. */
  4967. Scalar.Denormalize = function (normalized, min, max) {
  4968. return (normalized * (max - min) + min);
  4969. };
  4970. /**
  4971. * Calculates the shortest difference between two given angles given in degrees.
  4972. */
  4973. Scalar.DeltaAngle = function (current, target) {
  4974. var num = Scalar.Repeat(target - current, 360.0);
  4975. if (num > 180.0) {
  4976. num -= 360.0;
  4977. }
  4978. return num;
  4979. };
  4980. /**
  4981. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4982. *
  4983. * The returned value will move back and forth between 0 and length
  4984. */
  4985. Scalar.PingPong = function (tx, length) {
  4986. var t = Scalar.Repeat(tx, length * 2.0);
  4987. return length - Math.abs(t - length);
  4988. };
  4989. /**
  4990. * Interpolates between min and max with smoothing at the limits.
  4991. *
  4992. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4993. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4994. */
  4995. Scalar.SmoothStep = function (from, to, tx) {
  4996. var t = Scalar.Clamp(tx);
  4997. t = -2.0 * t * t * t + 3.0 * t * t;
  4998. return to * t + from * (1.0 - t);
  4999. };
  5000. /**
  5001. * Moves a value current towards target.
  5002. *
  5003. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5004. * Negative values of maxDelta pushes the value away from target.
  5005. */
  5006. Scalar.MoveTowards = function (current, target, maxDelta) {
  5007. var result = 0;
  5008. if (Math.abs(target - current) <= maxDelta) {
  5009. result = target;
  5010. }
  5011. else {
  5012. result = current + Scalar.Sign(target - current) * maxDelta;
  5013. }
  5014. return result;
  5015. };
  5016. /**
  5017. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5018. *
  5019. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5020. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5021. */
  5022. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5023. var num = Scalar.DeltaAngle(current, target);
  5024. var result = 0;
  5025. if (-maxDelta < num && num < maxDelta) {
  5026. result = target;
  5027. }
  5028. else {
  5029. target = current + num;
  5030. result = Scalar.MoveTowards(current, target, maxDelta);
  5031. }
  5032. return result;
  5033. };
  5034. /**
  5035. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5036. */
  5037. Scalar.Lerp = function (start, end, amount) {
  5038. return start + ((end - start) * amount);
  5039. };
  5040. /**
  5041. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5042. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5043. */
  5044. Scalar.LerpAngle = function (start, end, amount) {
  5045. var num = Scalar.Repeat(end - start, 360.0);
  5046. if (num > 180.0) {
  5047. num -= 360.0;
  5048. }
  5049. return start + num * Scalar.Clamp(amount);
  5050. };
  5051. /**
  5052. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5053. */
  5054. Scalar.InverseLerp = function (a, b, value) {
  5055. var result = 0;
  5056. if (a != b) {
  5057. result = Scalar.Clamp((value - a) / (b - a));
  5058. }
  5059. else {
  5060. result = 0.0;
  5061. }
  5062. return result;
  5063. };
  5064. /**
  5065. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5066. */
  5067. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5068. var squared = amount * amount;
  5069. var cubed = amount * squared;
  5070. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5071. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5072. var part3 = (cubed - (2.0 * squared)) + amount;
  5073. var part4 = cubed - squared;
  5074. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5075. };
  5076. /**
  5077. * Returns a random float number between and min and max values
  5078. */
  5079. Scalar.RandomRange = function (min, max) {
  5080. if (min === max)
  5081. return min;
  5082. return ((Math.random() * (max - min)) + min);
  5083. };
  5084. /**
  5085. * This function returns percentage of a number in a given range.
  5086. *
  5087. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5088. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5089. */
  5090. Scalar.RangeToPercent = function (number, min, max) {
  5091. return ((number - min) / (max - min));
  5092. };
  5093. /**
  5094. * This function returns number that corresponds to the percentage in a given range.
  5095. *
  5096. * PercentToRange(0.34,0,100) will return 34.
  5097. */
  5098. Scalar.PercentToRange = function (percent, min, max) {
  5099. return ((max - min) * percent + min);
  5100. };
  5101. return Scalar;
  5102. }());
  5103. BABYLON.Scalar = Scalar;
  5104. })(BABYLON || (BABYLON = {}));
  5105. //# sourceMappingURL=babylon.math.scalar.js.map
  5106. //# sourceMappingURL=babylon.mixins.js.map
  5107. var BABYLON;
  5108. (function (BABYLON) {
  5109. var __decoratorInitialStore = {};
  5110. var __mergedStore = {};
  5111. var _copySource = function (creationFunction, source, instanciate) {
  5112. var destination = creationFunction();
  5113. // Tags
  5114. if (BABYLON.Tags) {
  5115. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5116. }
  5117. var classStore = getMergedStore(destination);
  5118. // Properties
  5119. for (var property in classStore) {
  5120. var propertyDescriptor = classStore[property];
  5121. var sourceProperty = source[property];
  5122. var propertyType = propertyDescriptor.type;
  5123. if (sourceProperty !== undefined && sourceProperty !== null) {
  5124. switch (propertyType) {
  5125. case 0: // Value
  5126. case 6:// Mesh reference
  5127. destination[property] = sourceProperty;
  5128. break;
  5129. case 1:// Texture
  5130. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5131. break;
  5132. case 2: // Color3
  5133. case 3: // FresnelParameters
  5134. case 4: // Vector2
  5135. case 5: // Vector3
  5136. case 7:// Color Curves
  5137. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5138. break;
  5139. }
  5140. }
  5141. }
  5142. return destination;
  5143. };
  5144. function getDirectStore(target) {
  5145. var classKey = target.getClassName();
  5146. if (!__decoratorInitialStore[classKey]) {
  5147. __decoratorInitialStore[classKey] = {};
  5148. }
  5149. return __decoratorInitialStore[classKey];
  5150. }
  5151. /**
  5152. * Return the list of properties flagged as serializable
  5153. * @param target: host object
  5154. */
  5155. function getMergedStore(target) {
  5156. var classKey = target.getClassName();
  5157. if (__mergedStore[classKey]) {
  5158. return __mergedStore[classKey];
  5159. }
  5160. __mergedStore[classKey] = {};
  5161. var store = __mergedStore[classKey];
  5162. var currentTarget = target;
  5163. var currentKey = classKey;
  5164. while (currentKey) {
  5165. var initialStore = __decoratorInitialStore[currentKey];
  5166. for (var property in initialStore) {
  5167. store[property] = initialStore[property];
  5168. }
  5169. var parent_1 = void 0;
  5170. var done = false;
  5171. do {
  5172. parent_1 = Object.getPrototypeOf(currentTarget);
  5173. if (!parent_1.getClassName) {
  5174. done = true;
  5175. break;
  5176. }
  5177. if (parent_1.getClassName() !== currentKey) {
  5178. break;
  5179. }
  5180. currentTarget = parent_1;
  5181. } while (parent_1);
  5182. if (done) {
  5183. break;
  5184. }
  5185. currentKey = parent_1.getClassName();
  5186. currentTarget = parent_1;
  5187. }
  5188. return store;
  5189. }
  5190. function generateSerializableMember(type, sourceName) {
  5191. return function (target, propertyKey) {
  5192. var classStore = getDirectStore(target);
  5193. if (!classStore[propertyKey]) {
  5194. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5195. }
  5196. };
  5197. }
  5198. function generateExpandMember(setCallback, targetKey) {
  5199. if (targetKey === void 0) { targetKey = null; }
  5200. return function (target, propertyKey) {
  5201. var key = targetKey || ("_" + propertyKey);
  5202. Object.defineProperty(target, propertyKey, {
  5203. get: function () {
  5204. return this[key];
  5205. },
  5206. set: function (value) {
  5207. if (this[key] === value) {
  5208. return;
  5209. }
  5210. this[key] = value;
  5211. target[setCallback].apply(this);
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. };
  5217. }
  5218. function expandToProperty(callback, targetKey) {
  5219. if (targetKey === void 0) { targetKey = null; }
  5220. return generateExpandMember(callback, targetKey);
  5221. }
  5222. BABYLON.expandToProperty = expandToProperty;
  5223. function serialize(sourceName) {
  5224. return generateSerializableMember(0, sourceName); // value member
  5225. }
  5226. BABYLON.serialize = serialize;
  5227. function serializeAsTexture(sourceName) {
  5228. return generateSerializableMember(1, sourceName); // texture member
  5229. }
  5230. BABYLON.serializeAsTexture = serializeAsTexture;
  5231. function serializeAsColor3(sourceName) {
  5232. return generateSerializableMember(2, sourceName); // color3 member
  5233. }
  5234. BABYLON.serializeAsColor3 = serializeAsColor3;
  5235. function serializeAsFresnelParameters(sourceName) {
  5236. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5237. }
  5238. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5239. function serializeAsVector2(sourceName) {
  5240. return generateSerializableMember(4, sourceName); // vector2 member
  5241. }
  5242. BABYLON.serializeAsVector2 = serializeAsVector2;
  5243. function serializeAsVector3(sourceName) {
  5244. return generateSerializableMember(5, sourceName); // vector3 member
  5245. }
  5246. BABYLON.serializeAsVector3 = serializeAsVector3;
  5247. function serializeAsMeshReference(sourceName) {
  5248. return generateSerializableMember(6, sourceName); // mesh reference member
  5249. }
  5250. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5251. function serializeAsColorCurves(sourceName) {
  5252. return generateSerializableMember(7, sourceName); // color curves
  5253. }
  5254. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5255. function serializeAsColor4(sourceName) {
  5256. return generateSerializableMember(8, sourceName); // color 4
  5257. }
  5258. BABYLON.serializeAsColor4 = serializeAsColor4;
  5259. function serializeAsImageProcessingConfiguration(sourceName) {
  5260. return generateSerializableMember(9, sourceName); // image processing
  5261. }
  5262. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5263. var SerializationHelper = /** @class */ (function () {
  5264. function SerializationHelper() {
  5265. }
  5266. SerializationHelper.Serialize = function (entity, serializationObject) {
  5267. if (!serializationObject) {
  5268. serializationObject = {};
  5269. }
  5270. // Tags
  5271. if (BABYLON.Tags) {
  5272. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5273. }
  5274. var serializedProperties = getMergedStore(entity);
  5275. // Properties
  5276. for (var property in serializedProperties) {
  5277. var propertyDescriptor = serializedProperties[property];
  5278. var targetPropertyName = propertyDescriptor.sourceName || property;
  5279. var propertyType = propertyDescriptor.type;
  5280. var sourceProperty = entity[property];
  5281. if (sourceProperty !== undefined && sourceProperty !== null) {
  5282. switch (propertyType) {
  5283. case 0:// Value
  5284. serializationObject[targetPropertyName] = sourceProperty;
  5285. break;
  5286. case 1:// Texture
  5287. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5288. break;
  5289. case 2:// Color3
  5290. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5291. break;
  5292. case 3:// FresnelParameters
  5293. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5294. break;
  5295. case 4:// Vector2
  5296. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5297. break;
  5298. case 5:// Vector3
  5299. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5300. break;
  5301. case 6:// Mesh reference
  5302. serializationObject[targetPropertyName] = sourceProperty.id;
  5303. break;
  5304. case 7:// Color Curves
  5305. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5306. break;
  5307. case 8:// Color 4
  5308. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5309. break;
  5310. case 9:// Image Processing
  5311. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5312. break;
  5313. }
  5314. }
  5315. }
  5316. return serializationObject;
  5317. };
  5318. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5319. if (rootUrl === void 0) { rootUrl = null; }
  5320. var destination = creationFunction();
  5321. if (!rootUrl) {
  5322. rootUrl = "";
  5323. }
  5324. // Tags
  5325. if (BABYLON.Tags) {
  5326. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5327. }
  5328. var classStore = getMergedStore(destination);
  5329. // Properties
  5330. for (var property in classStore) {
  5331. var propertyDescriptor = classStore[property];
  5332. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5333. var propertyType = propertyDescriptor.type;
  5334. if (sourceProperty !== undefined && sourceProperty !== null) {
  5335. var dest = destination;
  5336. switch (propertyType) {
  5337. case 0:// Value
  5338. dest[property] = sourceProperty;
  5339. break;
  5340. case 1:// Texture
  5341. if (scene) {
  5342. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5343. }
  5344. break;
  5345. case 2:// Color3
  5346. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5347. break;
  5348. case 3:// FresnelParameters
  5349. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5350. break;
  5351. case 4:// Vector2
  5352. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5353. break;
  5354. case 5:// Vector3
  5355. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5356. break;
  5357. case 6:// Mesh reference
  5358. if (scene) {
  5359. dest[property] = scene.getLastMeshByID(sourceProperty);
  5360. }
  5361. break;
  5362. case 7:// Color Curves
  5363. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5364. break;
  5365. case 8:// Color 4
  5366. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5367. break;
  5368. case 9:// Image Processing
  5369. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. return destination;
  5375. };
  5376. SerializationHelper.Clone = function (creationFunction, source) {
  5377. return _copySource(creationFunction, source, false);
  5378. };
  5379. SerializationHelper.Instanciate = function (creationFunction, source) {
  5380. return _copySource(creationFunction, source, true);
  5381. };
  5382. return SerializationHelper;
  5383. }());
  5384. BABYLON.SerializationHelper = SerializationHelper;
  5385. })(BABYLON || (BABYLON = {}));
  5386. //# sourceMappingURL=babylon.decorators.js.map
  5387. var BABYLON;
  5388. (function (BABYLON) {
  5389. /**
  5390. * A class serves as a medium between the observable and its observers
  5391. */
  5392. var EventState = /** @class */ (function () {
  5393. /**
  5394. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5395. */
  5396. function EventState(mask, skipNextObservers, target, currentTarget) {
  5397. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5398. this.initalize(mask, skipNextObservers, target, currentTarget);
  5399. }
  5400. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5401. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5402. this.mask = mask;
  5403. this.skipNextObservers = skipNextObservers;
  5404. this.target = target;
  5405. this.currentTarget = currentTarget;
  5406. return this;
  5407. };
  5408. return EventState;
  5409. }());
  5410. BABYLON.EventState = EventState;
  5411. /**
  5412. * Represent an Observer registered to a given Observable object.
  5413. */
  5414. var Observer = /** @class */ (function () {
  5415. function Observer(callback, mask, scope) {
  5416. if (scope === void 0) { scope = null; }
  5417. this.callback = callback;
  5418. this.mask = mask;
  5419. this.scope = scope;
  5420. }
  5421. return Observer;
  5422. }());
  5423. BABYLON.Observer = Observer;
  5424. /**
  5425. * Represent a list of observers registered to multiple Observables object.
  5426. */
  5427. var MultiObserver = /** @class */ (function () {
  5428. function MultiObserver() {
  5429. }
  5430. MultiObserver.prototype.dispose = function () {
  5431. if (this._observers && this._observables) {
  5432. for (var index = 0; index < this._observers.length; index++) {
  5433. this._observables[index].remove(this._observers[index]);
  5434. }
  5435. }
  5436. this._observers = null;
  5437. this._observables = null;
  5438. };
  5439. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5440. if (mask === void 0) { mask = -1; }
  5441. if (scope === void 0) { scope = null; }
  5442. var result = new MultiObserver();
  5443. result._observers = new Array();
  5444. result._observables = observables;
  5445. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5446. var observable = observables_1[_i];
  5447. var observer = observable.add(callback, mask, false, scope);
  5448. if (observer) {
  5449. result._observers.push(observer);
  5450. }
  5451. }
  5452. return result;
  5453. };
  5454. return MultiObserver;
  5455. }());
  5456. BABYLON.MultiObserver = MultiObserver;
  5457. /**
  5458. * The Observable class is a simple implementation of the Observable pattern.
  5459. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5460. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5461. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5462. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5463. */
  5464. var Observable = /** @class */ (function () {
  5465. function Observable(onObserverAdded) {
  5466. this._observers = new Array();
  5467. this._eventState = new EventState(0);
  5468. if (onObserverAdded) {
  5469. this._onObserverAdded = onObserverAdded;
  5470. }
  5471. }
  5472. /**
  5473. * Create a new Observer with the specified callback
  5474. * @param callback the callback that will be executed for that Observer
  5475. * @param mask the mask used to filter observers
  5476. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5477. * @param scope optional scope for the callback to be called from
  5478. */
  5479. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5480. if (mask === void 0) { mask = -1; }
  5481. if (insertFirst === void 0) { insertFirst = false; }
  5482. if (scope === void 0) { scope = null; }
  5483. if (!callback) {
  5484. return null;
  5485. }
  5486. var observer = new Observer(callback, mask, scope);
  5487. if (insertFirst) {
  5488. this._observers.unshift(observer);
  5489. }
  5490. else {
  5491. this._observers.push(observer);
  5492. }
  5493. if (this._onObserverAdded) {
  5494. this._onObserverAdded(observer);
  5495. }
  5496. return observer;
  5497. };
  5498. /**
  5499. * Remove an Observer from the Observable object
  5500. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5501. */
  5502. Observable.prototype.remove = function (observer) {
  5503. if (!observer) {
  5504. return false;
  5505. }
  5506. var index = this._observers.indexOf(observer);
  5507. if (index !== -1) {
  5508. this._observers.splice(index, 1);
  5509. return true;
  5510. }
  5511. return false;
  5512. };
  5513. /**
  5514. * Remove a callback from the Observable object
  5515. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5516. */
  5517. Observable.prototype.removeCallback = function (callback) {
  5518. for (var index = 0; index < this._observers.length; index++) {
  5519. if (this._observers[index].callback === callback) {
  5520. this._observers.splice(index, 1);
  5521. return true;
  5522. }
  5523. }
  5524. return false;
  5525. };
  5526. /**
  5527. * Notify all Observers by calling their respective callback with the given data
  5528. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5529. * @param eventData
  5530. * @param mask
  5531. */
  5532. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5533. if (mask === void 0) { mask = -1; }
  5534. if (!this._observers.length) {
  5535. return true;
  5536. }
  5537. var state = this._eventState;
  5538. state.mask = mask;
  5539. state.target = target;
  5540. state.currentTarget = currentTarget;
  5541. state.skipNextObservers = false;
  5542. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5543. var obs = _a[_i];
  5544. if (obs.mask & mask) {
  5545. if (obs.scope) {
  5546. obs.callback.apply(obs.scope, [eventData, state]);
  5547. }
  5548. else {
  5549. obs.callback(eventData, state);
  5550. }
  5551. }
  5552. if (state.skipNextObservers) {
  5553. return false;
  5554. }
  5555. }
  5556. return true;
  5557. };
  5558. /**
  5559. * Notify a specific observer
  5560. * @param eventData
  5561. * @param mask
  5562. */
  5563. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5564. if (mask === void 0) { mask = -1; }
  5565. var state = this._eventState;
  5566. state.mask = mask;
  5567. state.skipNextObservers = false;
  5568. observer.callback(eventData, state);
  5569. };
  5570. /**
  5571. * return true is the Observable has at least one Observer registered
  5572. */
  5573. Observable.prototype.hasObservers = function () {
  5574. return this._observers.length > 0;
  5575. };
  5576. /**
  5577. * Clear the list of observers
  5578. */
  5579. Observable.prototype.clear = function () {
  5580. this._observers = new Array();
  5581. this._onObserverAdded = null;
  5582. };
  5583. /**
  5584. * Clone the current observable
  5585. */
  5586. Observable.prototype.clone = function () {
  5587. var result = new Observable();
  5588. result._observers = this._observers.slice(0);
  5589. return result;
  5590. };
  5591. /**
  5592. * Does this observable handles observer registered with a given mask
  5593. * @param {number} trigger - the mask to be tested
  5594. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5595. **/
  5596. Observable.prototype.hasSpecificMask = function (mask) {
  5597. if (mask === void 0) { mask = -1; }
  5598. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5599. var obs = _a[_i];
  5600. if (obs.mask & mask || obs.mask === mask) {
  5601. return true;
  5602. }
  5603. }
  5604. return false;
  5605. };
  5606. return Observable;
  5607. }());
  5608. BABYLON.Observable = Observable;
  5609. })(BABYLON || (BABYLON = {}));
  5610. //# sourceMappingURL=babylon.observable.js.map
  5611. var BABYLON;
  5612. (function (BABYLON) {
  5613. var SmartArray = /** @class */ (function () {
  5614. function SmartArray(capacity) {
  5615. this.length = 0;
  5616. this.data = new Array(capacity);
  5617. this._id = SmartArray._GlobalId++;
  5618. }
  5619. SmartArray.prototype.push = function (value) {
  5620. this.data[this.length++] = value;
  5621. if (this.length > this.data.length) {
  5622. this.data.length *= 2;
  5623. }
  5624. };
  5625. SmartArray.prototype.forEach = function (func) {
  5626. for (var index = 0; index < this.length; index++) {
  5627. func(this.data[index]);
  5628. }
  5629. };
  5630. SmartArray.prototype.sort = function (compareFn) {
  5631. this.data.sort(compareFn);
  5632. };
  5633. SmartArray.prototype.reset = function () {
  5634. this.length = 0;
  5635. };
  5636. SmartArray.prototype.dispose = function () {
  5637. this.reset();
  5638. if (this.data) {
  5639. this.data.length = 0;
  5640. this.data = [];
  5641. }
  5642. };
  5643. SmartArray.prototype.concat = function (array) {
  5644. if (array.length === 0) {
  5645. return;
  5646. }
  5647. if (this.length + array.length > this.data.length) {
  5648. this.data.length = (this.length + array.length) * 2;
  5649. }
  5650. for (var index = 0; index < array.length; index++) {
  5651. this.data[this.length++] = (array.data || array)[index];
  5652. }
  5653. };
  5654. SmartArray.prototype.indexOf = function (value) {
  5655. var position = this.data.indexOf(value);
  5656. if (position >= this.length) {
  5657. return -1;
  5658. }
  5659. return position;
  5660. };
  5661. SmartArray.prototype.contains = function (value) {
  5662. return this.data.indexOf(value) !== -1;
  5663. };
  5664. // Statics
  5665. SmartArray._GlobalId = 0;
  5666. return SmartArray;
  5667. }());
  5668. BABYLON.SmartArray = SmartArray;
  5669. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5670. __extends(SmartArrayNoDuplicate, _super);
  5671. function SmartArrayNoDuplicate() {
  5672. var _this = _super !== null && _super.apply(this, arguments) || this;
  5673. _this._duplicateId = 0;
  5674. return _this;
  5675. }
  5676. SmartArrayNoDuplicate.prototype.push = function (value) {
  5677. _super.prototype.push.call(this, value);
  5678. if (!value.__smartArrayFlags) {
  5679. value.__smartArrayFlags = {};
  5680. }
  5681. value.__smartArrayFlags[this._id] = this._duplicateId;
  5682. };
  5683. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5684. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5685. return false;
  5686. }
  5687. this.push(value);
  5688. return true;
  5689. };
  5690. SmartArrayNoDuplicate.prototype.reset = function () {
  5691. _super.prototype.reset.call(this);
  5692. this._duplicateId++;
  5693. };
  5694. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5695. if (array.length === 0) {
  5696. return;
  5697. }
  5698. if (this.length + array.length > this.data.length) {
  5699. this.data.length = (this.length + array.length) * 2;
  5700. }
  5701. for (var index = 0; index < array.length; index++) {
  5702. var item = (array.data || array)[index];
  5703. this.pushNoDuplicate(item);
  5704. }
  5705. };
  5706. return SmartArrayNoDuplicate;
  5707. }(SmartArray));
  5708. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5709. })(BABYLON || (BABYLON = {}));
  5710. //# sourceMappingURL=babylon.smartArray.js.map
  5711. var BABYLON;
  5712. (function (BABYLON) {
  5713. // Screenshots
  5714. var screenshotCanvas;
  5715. var cloneValue = function (source, destinationObject) {
  5716. if (!source)
  5717. return null;
  5718. if (source instanceof BABYLON.Mesh) {
  5719. return null;
  5720. }
  5721. if (source instanceof BABYLON.SubMesh) {
  5722. return source.clone(destinationObject);
  5723. }
  5724. else if (source.clone) {
  5725. return source.clone();
  5726. }
  5727. return null;
  5728. };
  5729. var Tools = /** @class */ (function () {
  5730. function Tools() {
  5731. }
  5732. ;
  5733. /**
  5734. * Interpolates between a and b via alpha
  5735. * @param a The lower value (returned when alpha = 0)
  5736. * @param b The upper value (returned when alpha = 1)
  5737. * @param alpha The interpolation-factor
  5738. * @return The mixed value
  5739. */
  5740. Tools.Mix = function (a, b, alpha) {
  5741. return a * (1 - alpha) + b * alpha;
  5742. };
  5743. Tools.Instantiate = function (className) {
  5744. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5745. return Tools.RegisteredExternalClasses[className];
  5746. }
  5747. var arr = className.split(".");
  5748. var fn = (window || this);
  5749. for (var i = 0, len = arr.length; i < len; i++) {
  5750. fn = fn[arr[i]];
  5751. }
  5752. if (typeof fn !== "function") {
  5753. return null;
  5754. }
  5755. return fn;
  5756. };
  5757. Tools.SetImmediate = function (action) {
  5758. if (window.setImmediate) {
  5759. window.setImmediate(action);
  5760. }
  5761. else {
  5762. setTimeout(action, 1);
  5763. }
  5764. };
  5765. Tools.IsExponentOfTwo = function (value) {
  5766. var count = 1;
  5767. do {
  5768. count *= 2;
  5769. } while (count < value);
  5770. return count === value;
  5771. };
  5772. /**
  5773. * Find the next highest power of two.
  5774. * @param x Number to start search from.
  5775. * @return Next highest power of two.
  5776. */
  5777. Tools.CeilingPOT = function (x) {
  5778. x--;
  5779. x |= x >> 1;
  5780. x |= x >> 2;
  5781. x |= x >> 4;
  5782. x |= x >> 8;
  5783. x |= x >> 16;
  5784. x++;
  5785. return x;
  5786. };
  5787. /**
  5788. * Find the next lowest power of two.
  5789. * @param x Number to start search from.
  5790. * @return Next lowest power of two.
  5791. */
  5792. Tools.FloorPOT = function (x) {
  5793. x = x | (x >> 1);
  5794. x = x | (x >> 2);
  5795. x = x | (x >> 4);
  5796. x = x | (x >> 8);
  5797. x = x | (x >> 16);
  5798. return x - (x >> 1);
  5799. };
  5800. /**
  5801. * Find the nearest power of two.
  5802. * @param x Number to start search from.
  5803. * @return Next nearest power of two.
  5804. */
  5805. Tools.NearestPOT = function (x) {
  5806. var c = Tools.CeilingPOT(x);
  5807. var f = Tools.FloorPOT(x);
  5808. return (c - x) > (x - f) ? f : c;
  5809. };
  5810. Tools.GetExponentOfTwo = function (value, max, mode) {
  5811. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5812. var pot;
  5813. switch (mode) {
  5814. case BABYLON.Engine.SCALEMODE_FLOOR:
  5815. pot = Tools.FloorPOT(value);
  5816. break;
  5817. case BABYLON.Engine.SCALEMODE_NEAREST:
  5818. pot = Tools.NearestPOT(value);
  5819. break;
  5820. case BABYLON.Engine.SCALEMODE_CEILING:
  5821. default:
  5822. pot = Tools.CeilingPOT(value);
  5823. break;
  5824. }
  5825. return Math.min(pot, max);
  5826. };
  5827. Tools.GetFilename = function (path) {
  5828. var index = path.lastIndexOf("/");
  5829. if (index < 0)
  5830. return path;
  5831. return path.substring(index + 1);
  5832. };
  5833. Tools.GetDOMTextContent = function (element) {
  5834. var result = "";
  5835. var child = element.firstChild;
  5836. while (child) {
  5837. if (child.nodeType === 3) {
  5838. result += child.textContent;
  5839. }
  5840. child = child.nextSibling;
  5841. }
  5842. return result;
  5843. };
  5844. Tools.ToDegrees = function (angle) {
  5845. return angle * 180 / Math.PI;
  5846. };
  5847. Tools.ToRadians = function (angle) {
  5848. return angle * Math.PI / 180;
  5849. };
  5850. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5851. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5852. var output = "";
  5853. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5854. var i = 0;
  5855. var bytes = new Uint8Array(buffer);
  5856. while (i < bytes.length) {
  5857. chr1 = bytes[i++];
  5858. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5859. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5860. enc1 = chr1 >> 2;
  5861. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5862. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5863. enc4 = chr3 & 63;
  5864. if (isNaN(chr2)) {
  5865. enc3 = enc4 = 64;
  5866. }
  5867. else if (isNaN(chr3)) {
  5868. enc4 = 64;
  5869. }
  5870. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5871. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5872. }
  5873. return "data:image/png;base64," + output;
  5874. };
  5875. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5876. if (bias === void 0) { bias = null; }
  5877. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5878. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5879. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5880. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5881. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5882. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5883. }
  5884. if (bias) {
  5885. minimum.x -= minimum.x * bias.x + bias.y;
  5886. minimum.y -= minimum.y * bias.x + bias.y;
  5887. minimum.z -= minimum.z * bias.x + bias.y;
  5888. maximum.x += maximum.x * bias.x + bias.y;
  5889. maximum.y += maximum.y * bias.x + bias.y;
  5890. maximum.z += maximum.z * bias.x + bias.y;
  5891. }
  5892. return {
  5893. minimum: minimum,
  5894. maximum: maximum
  5895. };
  5896. };
  5897. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5898. if (bias === void 0) { bias = null; }
  5899. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5900. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5901. if (!stride) {
  5902. stride = 3;
  5903. }
  5904. for (var index = start; index < start + count; index++) {
  5905. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5906. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5907. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5908. }
  5909. if (bias) {
  5910. minimum.x -= minimum.x * bias.x + bias.y;
  5911. minimum.y -= minimum.y * bias.x + bias.y;
  5912. minimum.z -= minimum.z * bias.x + bias.y;
  5913. maximum.x += maximum.x * bias.x + bias.y;
  5914. maximum.y += maximum.y * bias.x + bias.y;
  5915. maximum.z += maximum.z * bias.x + bias.y;
  5916. }
  5917. return {
  5918. minimum: minimum,
  5919. maximum: maximum
  5920. };
  5921. };
  5922. Tools.Vector2ArrayFeeder = function (array) {
  5923. return function (index) {
  5924. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5925. var length = isFloatArray ? array.length / 2 : array.length;
  5926. if (index >= length) {
  5927. return null;
  5928. }
  5929. if (isFloatArray) {
  5930. var fa = array;
  5931. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5932. }
  5933. var a = array;
  5934. return a[index];
  5935. };
  5936. };
  5937. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5938. if (bias === void 0) { bias = null; }
  5939. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5940. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5941. var i = 0;
  5942. var cur = feeder(i++);
  5943. while (cur) {
  5944. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5945. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5946. cur = feeder(i++);
  5947. }
  5948. if (bias) {
  5949. minimum.x -= minimum.x * bias.x + bias.y;
  5950. minimum.y -= minimum.y * bias.x + bias.y;
  5951. maximum.x += maximum.x * bias.x + bias.y;
  5952. maximum.y += maximum.y * bias.x + bias.y;
  5953. }
  5954. return {
  5955. minimum: minimum,
  5956. maximum: maximum
  5957. };
  5958. };
  5959. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5960. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5961. return null;
  5962. return Array.isArray(obj) ? obj : [obj];
  5963. };
  5964. // Misc.
  5965. Tools.GetPointerPrefix = function () {
  5966. var eventPrefix = "pointer";
  5967. // Check if pointer events are supported
  5968. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5969. eventPrefix = "mouse";
  5970. }
  5971. return eventPrefix;
  5972. };
  5973. /**
  5974. * @param func - the function to be called
  5975. * @param requester - the object that will request the next frame. Falls back to window.
  5976. */
  5977. Tools.QueueNewFrame = function (func, requester) {
  5978. if (!Tools.IsWindowObjectExist()) {
  5979. return setTimeout(func, 16);
  5980. }
  5981. if (!requester) {
  5982. requester = window;
  5983. }
  5984. if (requester.requestAnimationFrame) {
  5985. return requester.requestAnimationFrame(func);
  5986. }
  5987. else if (requester.msRequestAnimationFrame) {
  5988. return requester.msRequestAnimationFrame(func);
  5989. }
  5990. else if (requester.webkitRequestAnimationFrame) {
  5991. return requester.webkitRequestAnimationFrame(func);
  5992. }
  5993. else if (requester.mozRequestAnimationFrame) {
  5994. return requester.mozRequestAnimationFrame(func);
  5995. }
  5996. else if (requester.oRequestAnimationFrame) {
  5997. return requester.oRequestAnimationFrame(func);
  5998. }
  5999. else {
  6000. return window.setTimeout(func, 16);
  6001. }
  6002. };
  6003. Tools.RequestFullscreen = function (element) {
  6004. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6005. if (!requestFunction)
  6006. return;
  6007. requestFunction.call(element);
  6008. };
  6009. Tools.ExitFullscreen = function () {
  6010. if (document.exitFullscreen) {
  6011. document.exitFullscreen();
  6012. }
  6013. else if (document.mozCancelFullScreen) {
  6014. document.mozCancelFullScreen();
  6015. }
  6016. else if (document.webkitCancelFullScreen) {
  6017. document.webkitCancelFullScreen();
  6018. }
  6019. else if (document.msCancelFullScreen) {
  6020. document.msCancelFullScreen();
  6021. }
  6022. };
  6023. Tools.SetCorsBehavior = function (url, img) {
  6024. if (Tools.CorsBehavior) {
  6025. switch (typeof (Tools.CorsBehavior)) {
  6026. case "function":
  6027. var result = Tools.CorsBehavior(url);
  6028. if (result) {
  6029. img.crossOrigin = result;
  6030. }
  6031. break;
  6032. case "string":
  6033. default:
  6034. img.crossOrigin = Tools.CorsBehavior;
  6035. break;
  6036. }
  6037. }
  6038. };
  6039. // External files
  6040. Tools.CleanUrl = function (url) {
  6041. url = url.replace(/#/mg, "%23");
  6042. return url;
  6043. };
  6044. Tools.LoadImage = function (url, onLoad, onError, database) {
  6045. if (url instanceof ArrayBuffer) {
  6046. url = Tools.EncodeArrayBufferTobase64(url);
  6047. }
  6048. url = Tools.CleanUrl(url);
  6049. url = Tools.PreprocessUrl(url);
  6050. var img = new Image();
  6051. if (url.substr(0, 5) !== "data:") {
  6052. Tools.SetCorsBehavior(url, img);
  6053. }
  6054. img.onload = function () {
  6055. onLoad(img);
  6056. };
  6057. img.onerror = function (err) {
  6058. Tools.Error("Error while trying to load image: " + url);
  6059. if (Tools.UseFallbackTexture) {
  6060. img.src = Tools.fallbackTexture;
  6061. onLoad(img);
  6062. }
  6063. else {
  6064. onError("Error while trying to load image: " + url, err);
  6065. }
  6066. };
  6067. var noIndexedDB = function () {
  6068. img.src = url;
  6069. };
  6070. var loadFromIndexedDB = function () {
  6071. if (database) {
  6072. database.loadImageFromDB(url, img);
  6073. }
  6074. };
  6075. //ANY database to do!
  6076. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6077. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6078. }
  6079. else {
  6080. if (url.indexOf("file:") !== 0) {
  6081. noIndexedDB();
  6082. }
  6083. else {
  6084. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6085. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6086. try {
  6087. var blobURL;
  6088. try {
  6089. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6090. }
  6091. catch (ex) {
  6092. // Chrome doesn't support oneTimeOnly parameter
  6093. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6094. }
  6095. img.src = blobURL;
  6096. }
  6097. catch (e) {
  6098. img.src = "";
  6099. }
  6100. }
  6101. else {
  6102. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6103. img.src = Tools.fallbackTexture;
  6104. }
  6105. }
  6106. }
  6107. return img;
  6108. };
  6109. //ANY
  6110. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6111. url = Tools.CleanUrl(url);
  6112. url = Tools.PreprocessUrl(url);
  6113. var request = null;
  6114. var noIndexedDB = function () {
  6115. request = new XMLHttpRequest();
  6116. var loadUrl = Tools.BaseUrl + url;
  6117. request.open('GET', loadUrl, true);
  6118. if (useArrayBuffer) {
  6119. request.responseType = "arraybuffer";
  6120. }
  6121. if (progressCallBack) {
  6122. request.onprogress = progressCallBack;
  6123. }
  6124. request.onreadystatechange = function () {
  6125. var req = request;
  6126. // In case of undefined state in some browsers.
  6127. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6128. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6129. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6130. callback(!useArrayBuffer ? req.responseText : req.response);
  6131. }
  6132. else {
  6133. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6134. if (onError) {
  6135. onError(req, e);
  6136. }
  6137. else {
  6138. throw e;
  6139. }
  6140. }
  6141. }
  6142. };
  6143. request.send(null);
  6144. };
  6145. var loadFromIndexedDB = function () {
  6146. if (database) {
  6147. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6148. }
  6149. };
  6150. if (url.indexOf("file:") !== -1) {
  6151. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6152. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6153. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6154. }
  6155. else {
  6156. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6157. if (onError) {
  6158. var e = new Error(errorMessage);
  6159. onError(undefined, e);
  6160. }
  6161. else {
  6162. Tools.Error(errorMessage);
  6163. }
  6164. }
  6165. }
  6166. else {
  6167. // Caching all files
  6168. if (database && database.enableSceneOffline) {
  6169. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6170. }
  6171. else {
  6172. noIndexedDB();
  6173. }
  6174. }
  6175. return request;
  6176. };
  6177. /**
  6178. * Load a script (identified by an url). When the url returns, the
  6179. * content of this file is added into a new script element, attached to the DOM (body element)
  6180. */
  6181. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6182. var head = document.getElementsByTagName('head')[0];
  6183. var script = document.createElement('script');
  6184. script.type = 'text/javascript';
  6185. script.src = scriptUrl;
  6186. script.onload = function () {
  6187. if (onSuccess) {
  6188. onSuccess();
  6189. }
  6190. };
  6191. script.onerror = function (e) {
  6192. if (onError) {
  6193. onError("Unable to load script", e);
  6194. }
  6195. };
  6196. head.appendChild(script);
  6197. };
  6198. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6199. var reader = new FileReader();
  6200. reader.onload = function (e) {
  6201. //target doesn't have result from ts 1.3
  6202. callback(e.target['result']);
  6203. };
  6204. reader.onprogress = progressCallback;
  6205. reader.readAsDataURL(fileToLoad);
  6206. };
  6207. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6208. var reader = new FileReader();
  6209. reader.onerror = function (e) {
  6210. Tools.Log("Error while reading file: " + fileToLoad.name);
  6211. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6212. };
  6213. reader.onload = function (e) {
  6214. //target doesn't have result from ts 1.3
  6215. callback(e.target['result']);
  6216. };
  6217. if (progressCallBack) {
  6218. reader.onprogress = progressCallBack;
  6219. }
  6220. if (!useArrayBuffer) {
  6221. // Asynchronous read
  6222. reader.readAsText(fileToLoad);
  6223. }
  6224. else {
  6225. reader.readAsArrayBuffer(fileToLoad);
  6226. }
  6227. };
  6228. //returns a downloadable url to a file content.
  6229. Tools.FileAsURL = function (content) {
  6230. var fileBlob = new Blob([content]);
  6231. var url = window.URL || window.webkitURL;
  6232. var link = url.createObjectURL(fileBlob);
  6233. return link;
  6234. };
  6235. // Misc.
  6236. Tools.Format = function (value, decimals) {
  6237. if (decimals === void 0) { decimals = 2; }
  6238. return value.toFixed(decimals);
  6239. };
  6240. Tools.CheckExtends = function (v, min, max) {
  6241. if (v.x < min.x)
  6242. min.x = v.x;
  6243. if (v.y < min.y)
  6244. min.y = v.y;
  6245. if (v.z < min.z)
  6246. min.z = v.z;
  6247. if (v.x > max.x)
  6248. max.x = v.x;
  6249. if (v.y > max.y)
  6250. max.y = v.y;
  6251. if (v.z > max.z)
  6252. max.z = v.z;
  6253. };
  6254. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6255. for (var prop in source) {
  6256. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6257. continue;
  6258. }
  6259. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6260. continue;
  6261. }
  6262. var sourceValue = source[prop];
  6263. var typeOfSourceValue = typeof sourceValue;
  6264. if (typeOfSourceValue === "function") {
  6265. continue;
  6266. }
  6267. if (typeOfSourceValue === "object") {
  6268. if (sourceValue instanceof Array) {
  6269. destination[prop] = [];
  6270. if (sourceValue.length > 0) {
  6271. if (typeof sourceValue[0] == "object") {
  6272. for (var index = 0; index < sourceValue.length; index++) {
  6273. var clonedValue = cloneValue(sourceValue[index], destination);
  6274. if (destination[prop].indexOf(clonedValue) === -1) {
  6275. destination[prop].push(clonedValue);
  6276. }
  6277. }
  6278. }
  6279. else {
  6280. destination[prop] = sourceValue.slice(0);
  6281. }
  6282. }
  6283. }
  6284. else {
  6285. destination[prop] = cloneValue(sourceValue, destination);
  6286. }
  6287. }
  6288. else {
  6289. destination[prop] = sourceValue;
  6290. }
  6291. }
  6292. };
  6293. Tools.IsEmpty = function (obj) {
  6294. for (var i in obj) {
  6295. if (obj.hasOwnProperty(i)) {
  6296. return false;
  6297. }
  6298. }
  6299. return true;
  6300. };
  6301. Tools.RegisterTopRootEvents = function (events) {
  6302. for (var index = 0; index < events.length; index++) {
  6303. var event = events[index];
  6304. window.addEventListener(event.name, event.handler, false);
  6305. try {
  6306. if (window.parent) {
  6307. window.parent.addEventListener(event.name, event.handler, false);
  6308. }
  6309. }
  6310. catch (e) {
  6311. // Silently fails...
  6312. }
  6313. }
  6314. };
  6315. Tools.UnregisterTopRootEvents = function (events) {
  6316. for (var index = 0; index < events.length; index++) {
  6317. var event = events[index];
  6318. window.removeEventListener(event.name, event.handler);
  6319. try {
  6320. if (window.parent) {
  6321. window.parent.removeEventListener(event.name, event.handler);
  6322. }
  6323. }
  6324. catch (e) {
  6325. // Silently fails...
  6326. }
  6327. }
  6328. };
  6329. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6330. if (mimeType === void 0) { mimeType = "image/png"; }
  6331. // Read the contents of the framebuffer
  6332. var numberOfChannelsByLine = width * 4;
  6333. var halfHeight = height / 2;
  6334. //Reading datas from WebGL
  6335. var data = engine.readPixels(0, 0, width, height);
  6336. //To flip image on Y axis.
  6337. for (var i = 0; i < halfHeight; i++) {
  6338. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6339. var currentCell = j + i * numberOfChannelsByLine;
  6340. var targetLine = height - i - 1;
  6341. var targetCell = j + targetLine * numberOfChannelsByLine;
  6342. var temp = data[currentCell];
  6343. data[currentCell] = data[targetCell];
  6344. data[targetCell] = temp;
  6345. }
  6346. }
  6347. // Create a 2D canvas to store the result
  6348. if (!screenshotCanvas) {
  6349. screenshotCanvas = document.createElement('canvas');
  6350. }
  6351. screenshotCanvas.width = width;
  6352. screenshotCanvas.height = height;
  6353. var context = screenshotCanvas.getContext('2d');
  6354. if (context) {
  6355. // Copy the pixels to a 2D canvas
  6356. var imageData = context.createImageData(width, height);
  6357. var castData = (imageData.data);
  6358. castData.set(data);
  6359. context.putImageData(imageData, 0, 0);
  6360. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6361. }
  6362. };
  6363. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6364. if (mimeType === void 0) { mimeType = "image/png"; }
  6365. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6366. if (successCallback) {
  6367. successCallback(base64Image);
  6368. }
  6369. else {
  6370. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6371. if (("download" in document.createElement("a"))) {
  6372. var a = window.document.createElement("a");
  6373. a.href = base64Image;
  6374. var date = new Date();
  6375. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6376. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6377. window.document.body.appendChild(a);
  6378. a.addEventListener("click", function () {
  6379. if (a.parentElement) {
  6380. a.parentElement.removeChild(a);
  6381. }
  6382. });
  6383. a.click();
  6384. //Or opening a new tab with the image if it is not possible to automatically start download.
  6385. }
  6386. else {
  6387. var newWindow = window.open("");
  6388. var img = newWindow.document.createElement("img");
  6389. img.src = base64Image;
  6390. newWindow.document.body.appendChild(img);
  6391. }
  6392. }
  6393. };
  6394. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6395. if (mimeType === void 0) { mimeType = "image/png"; }
  6396. var width;
  6397. var height;
  6398. // If a precision value is specified
  6399. if (size.precision) {
  6400. width = Math.round(engine.getRenderWidth() * size.precision);
  6401. height = Math.round(width / engine.getAspectRatio(camera));
  6402. }
  6403. else if (size.width && size.height) {
  6404. width = size.width;
  6405. height = size.height;
  6406. }
  6407. else if (size.width && !size.height) {
  6408. width = size.width;
  6409. height = Math.round(width / engine.getAspectRatio(camera));
  6410. }
  6411. else if (size.height && !size.width) {
  6412. height = size.height;
  6413. width = Math.round(height * engine.getAspectRatio(camera));
  6414. }
  6415. else if (!isNaN(size)) {
  6416. height = size;
  6417. width = size;
  6418. }
  6419. else {
  6420. Tools.Error("Invalid 'size' parameter !");
  6421. return;
  6422. }
  6423. if (!screenshotCanvas) {
  6424. screenshotCanvas = document.createElement('canvas');
  6425. }
  6426. screenshotCanvas.width = width;
  6427. screenshotCanvas.height = height;
  6428. var renderContext = screenshotCanvas.getContext("2d");
  6429. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6430. var newWidth = width;
  6431. var newHeight = newWidth / ratio;
  6432. if (newHeight > height) {
  6433. newHeight = height;
  6434. newWidth = newHeight * ratio;
  6435. }
  6436. var offsetX = Math.max(0, width - newWidth) / 2;
  6437. var offsetY = Math.max(0, height - newHeight) / 2;
  6438. var renderingCanvas = engine.getRenderingCanvas();
  6439. if (renderContext && renderingCanvas) {
  6440. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6441. }
  6442. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6443. };
  6444. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6445. if (mimeType === void 0) { mimeType = "image/png"; }
  6446. if (samples === void 0) { samples = 1; }
  6447. var width;
  6448. var height;
  6449. //If a precision value is specified
  6450. if (size.precision) {
  6451. width = Math.round(engine.getRenderWidth() * size.precision);
  6452. height = Math.round(width / engine.getAspectRatio(camera));
  6453. size = { width: width, height: height };
  6454. }
  6455. else if (size.width && size.height) {
  6456. width = size.width;
  6457. height = size.height;
  6458. }
  6459. else if (size.width && !size.height) {
  6460. width = size.width;
  6461. height = Math.round(width / engine.getAspectRatio(camera));
  6462. size = { width: width, height: height };
  6463. }
  6464. else if (size.height && !size.width) {
  6465. height = size.height;
  6466. width = Math.round(height * engine.getAspectRatio(camera));
  6467. size = { width: width, height: height };
  6468. }
  6469. else if (!isNaN(size)) {
  6470. height = size;
  6471. width = size;
  6472. }
  6473. else {
  6474. Tools.Error("Invalid 'size' parameter !");
  6475. return;
  6476. }
  6477. var scene = camera.getScene();
  6478. var previousCamera = null;
  6479. if (scene.activeCamera !== camera) {
  6480. previousCamera = scene.activeCamera;
  6481. scene.activeCamera = camera;
  6482. }
  6483. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6484. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6485. texture.renderList = null;
  6486. texture.samples = samples;
  6487. texture.onAfterRenderObservable.add(function () {
  6488. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6489. });
  6490. scene.incrementRenderId();
  6491. scene.resetCachedMaterial();
  6492. texture.render(true);
  6493. texture.dispose();
  6494. if (previousCamera) {
  6495. scene.activeCamera = previousCamera;
  6496. }
  6497. camera.getProjectionMatrix(true); // Force cache refresh;
  6498. };
  6499. // XHR response validator for local file scenario
  6500. Tools.ValidateXHRData = function (xhr, dataType) {
  6501. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6502. if (dataType === void 0) { dataType = 7; }
  6503. try {
  6504. if (dataType & 1) {
  6505. if (xhr.responseText && xhr.responseText.length > 0) {
  6506. return true;
  6507. }
  6508. else if (dataType === 1) {
  6509. return false;
  6510. }
  6511. }
  6512. if (dataType & 2) {
  6513. // Check header width and height since there is no "TGA" magic number
  6514. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6515. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6516. return true;
  6517. }
  6518. else if (dataType === 2) {
  6519. return false;
  6520. }
  6521. }
  6522. if (dataType & 4) {
  6523. // Check for the "DDS" magic number
  6524. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6525. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6526. return true;
  6527. }
  6528. else {
  6529. return false;
  6530. }
  6531. }
  6532. }
  6533. catch (e) {
  6534. // Global protection
  6535. }
  6536. return false;
  6537. };
  6538. /**
  6539. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6540. * Be aware Math.random() could cause collisions, but:
  6541. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  6542. */
  6543. Tools.RandomId = function () {
  6544. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6545. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6546. return v.toString(16);
  6547. });
  6548. };
  6549. Object.defineProperty(Tools, "NoneLogLevel", {
  6550. get: function () {
  6551. return Tools._NoneLogLevel;
  6552. },
  6553. enumerable: true,
  6554. configurable: true
  6555. });
  6556. Object.defineProperty(Tools, "MessageLogLevel", {
  6557. get: function () {
  6558. return Tools._MessageLogLevel;
  6559. },
  6560. enumerable: true,
  6561. configurable: true
  6562. });
  6563. Object.defineProperty(Tools, "WarningLogLevel", {
  6564. get: function () {
  6565. return Tools._WarningLogLevel;
  6566. },
  6567. enumerable: true,
  6568. configurable: true
  6569. });
  6570. Object.defineProperty(Tools, "ErrorLogLevel", {
  6571. get: function () {
  6572. return Tools._ErrorLogLevel;
  6573. },
  6574. enumerable: true,
  6575. configurable: true
  6576. });
  6577. Object.defineProperty(Tools, "AllLogLevel", {
  6578. get: function () {
  6579. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6580. },
  6581. enumerable: true,
  6582. configurable: true
  6583. });
  6584. Tools._AddLogEntry = function (entry) {
  6585. Tools._LogCache = entry + Tools._LogCache;
  6586. if (Tools.OnNewCacheEntry) {
  6587. Tools.OnNewCacheEntry(entry);
  6588. }
  6589. };
  6590. Tools._FormatMessage = function (message) {
  6591. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6592. var date = new Date();
  6593. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6594. };
  6595. Tools._LogDisabled = function (message) {
  6596. // nothing to do
  6597. };
  6598. Tools._LogEnabled = function (message) {
  6599. var formattedMessage = Tools._FormatMessage(message);
  6600. console.log("BJS - " + formattedMessage);
  6601. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6602. Tools._AddLogEntry(entry);
  6603. };
  6604. Tools._WarnDisabled = function (message) {
  6605. // nothing to do
  6606. };
  6607. Tools._WarnEnabled = function (message) {
  6608. var formattedMessage = Tools._FormatMessage(message);
  6609. console.warn("BJS - " + formattedMessage);
  6610. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6611. Tools._AddLogEntry(entry);
  6612. };
  6613. Tools._ErrorDisabled = function (message) {
  6614. // nothing to do
  6615. };
  6616. Tools._ErrorEnabled = function (message) {
  6617. Tools.errorsCount++;
  6618. var formattedMessage = Tools._FormatMessage(message);
  6619. console.error("BJS - " + formattedMessage);
  6620. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6621. Tools._AddLogEntry(entry);
  6622. };
  6623. Object.defineProperty(Tools, "LogCache", {
  6624. get: function () {
  6625. return Tools._LogCache;
  6626. },
  6627. enumerable: true,
  6628. configurable: true
  6629. });
  6630. Tools.ClearLogCache = function () {
  6631. Tools._LogCache = "";
  6632. Tools.errorsCount = 0;
  6633. };
  6634. Object.defineProperty(Tools, "LogLevels", {
  6635. set: function (level) {
  6636. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6637. Tools.Log = Tools._LogEnabled;
  6638. }
  6639. else {
  6640. Tools.Log = Tools._LogDisabled;
  6641. }
  6642. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6643. Tools.Warn = Tools._WarnEnabled;
  6644. }
  6645. else {
  6646. Tools.Warn = Tools._WarnDisabled;
  6647. }
  6648. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6649. Tools.Error = Tools._ErrorEnabled;
  6650. }
  6651. else {
  6652. Tools.Error = Tools._ErrorDisabled;
  6653. }
  6654. },
  6655. enumerable: true,
  6656. configurable: true
  6657. });
  6658. Tools.IsWindowObjectExist = function () {
  6659. return (typeof window) !== "undefined";
  6660. };
  6661. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6662. get: function () {
  6663. return Tools._PerformanceNoneLogLevel;
  6664. },
  6665. enumerable: true,
  6666. configurable: true
  6667. });
  6668. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6669. get: function () {
  6670. return Tools._PerformanceUserMarkLogLevel;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6676. get: function () {
  6677. return Tools._PerformanceConsoleLogLevel;
  6678. },
  6679. enumerable: true,
  6680. configurable: true
  6681. });
  6682. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6683. set: function (level) {
  6684. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6685. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6686. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6687. return;
  6688. }
  6689. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6690. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6691. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6692. return;
  6693. }
  6694. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6695. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6696. },
  6697. enumerable: true,
  6698. configurable: true
  6699. });
  6700. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6701. };
  6702. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6703. };
  6704. Tools._StartUserMark = function (counterName, condition) {
  6705. if (condition === void 0) { condition = true; }
  6706. if (!Tools._performance) {
  6707. if (!Tools.IsWindowObjectExist()) {
  6708. return;
  6709. }
  6710. Tools._performance = window.performance;
  6711. }
  6712. if (!condition || !Tools._performance.mark) {
  6713. return;
  6714. }
  6715. Tools._performance.mark(counterName + "-Begin");
  6716. };
  6717. Tools._EndUserMark = function (counterName, condition) {
  6718. if (condition === void 0) { condition = true; }
  6719. if (!condition || !Tools._performance.mark) {
  6720. return;
  6721. }
  6722. Tools._performance.mark(counterName + "-End");
  6723. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6724. };
  6725. Tools._StartPerformanceConsole = function (counterName, condition) {
  6726. if (condition === void 0) { condition = true; }
  6727. if (!condition) {
  6728. return;
  6729. }
  6730. Tools._StartUserMark(counterName, condition);
  6731. if (console.time) {
  6732. console.time(counterName);
  6733. }
  6734. };
  6735. Tools._EndPerformanceConsole = function (counterName, condition) {
  6736. if (condition === void 0) { condition = true; }
  6737. if (!condition) {
  6738. return;
  6739. }
  6740. Tools._EndUserMark(counterName, condition);
  6741. if (console.time) {
  6742. console.timeEnd(counterName);
  6743. }
  6744. };
  6745. Object.defineProperty(Tools, "Now", {
  6746. get: function () {
  6747. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6748. return window.performance.now();
  6749. }
  6750. return new Date().getTime();
  6751. },
  6752. enumerable: true,
  6753. configurable: true
  6754. });
  6755. /**
  6756. * This method will return the name of the class used to create the instance of the given object.
  6757. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6758. * @param object the object to get the class name from
  6759. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6760. */
  6761. Tools.GetClassName = function (object, isType) {
  6762. if (isType === void 0) { isType = false; }
  6763. var name = null;
  6764. if (!isType && object.getClassName) {
  6765. name = object.getClassName();
  6766. }
  6767. else {
  6768. if (object instanceof Object) {
  6769. var classObj = isType ? object : Object.getPrototypeOf(object);
  6770. name = classObj.constructor["__bjsclassName__"];
  6771. }
  6772. if (!name) {
  6773. name = typeof object;
  6774. }
  6775. }
  6776. return name;
  6777. };
  6778. Tools.First = function (array, predicate) {
  6779. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6780. var el = array_1[_i];
  6781. if (predicate(el)) {
  6782. return el;
  6783. }
  6784. }
  6785. return null;
  6786. };
  6787. /**
  6788. * This method will return the name of the full name of the class, including its owning module (if any).
  6789. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6790. * @param object the object to get the class name from
  6791. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6792. */
  6793. Tools.getFullClassName = function (object, isType) {
  6794. if (isType === void 0) { isType = false; }
  6795. var className = null;
  6796. var moduleName = null;
  6797. if (!isType && object.getClassName) {
  6798. className = object.getClassName();
  6799. }
  6800. else {
  6801. if (object instanceof Object) {
  6802. var classObj = isType ? object : Object.getPrototypeOf(object);
  6803. className = classObj.constructor["__bjsclassName__"];
  6804. moduleName = classObj.constructor["__bjsmoduleName__"];
  6805. }
  6806. if (!className) {
  6807. className = typeof object;
  6808. }
  6809. }
  6810. if (!className) {
  6811. return null;
  6812. }
  6813. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6814. };
  6815. /**
  6816. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6817. * @param array
  6818. */
  6819. Tools.arrayOrStringFeeder = function (array) {
  6820. return function (index) {
  6821. if (index >= array.length) {
  6822. return null;
  6823. }
  6824. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6825. if (val && val.getHashCode) {
  6826. val = val.getHashCode();
  6827. }
  6828. if (typeof val === "string") {
  6829. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6830. }
  6831. return val;
  6832. };
  6833. };
  6834. /**
  6835. * Compute the hashCode of a stream of number
  6836. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6837. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6838. * @return the hash code computed
  6839. */
  6840. Tools.hashCodeFromStream = function (feeder) {
  6841. // Based from here: http://stackoverflow.com/a/7616484/802124
  6842. var hash = 0;
  6843. var index = 0;
  6844. var chr = feeder(index++);
  6845. while (chr != null) {
  6846. hash = ((hash << 5) - hash) + chr;
  6847. hash |= 0; // Convert to 32bit integer
  6848. chr = feeder(index++);
  6849. }
  6850. return hash;
  6851. };
  6852. Tools.BaseUrl = "";
  6853. Tools.CorsBehavior = "anonymous";
  6854. Tools.UseFallbackTexture = true;
  6855. /**
  6856. * Use this object to register external classes like custom textures or material
  6857. * to allow the laoders to instantiate them
  6858. */
  6859. Tools.RegisteredExternalClasses = {};
  6860. // Used in case of a texture loading problem
  6861. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  6862. Tools.PreprocessUrl = function (url) {
  6863. return url;
  6864. };
  6865. // Logs
  6866. Tools._NoneLogLevel = 0;
  6867. Tools._MessageLogLevel = 1;
  6868. Tools._WarningLogLevel = 2;
  6869. Tools._ErrorLogLevel = 4;
  6870. Tools._LogCache = "";
  6871. Tools.errorsCount = 0;
  6872. Tools.Log = Tools._LogEnabled;
  6873. Tools.Warn = Tools._WarnEnabled;
  6874. Tools.Error = Tools._ErrorEnabled;
  6875. // Performances
  6876. Tools._PerformanceNoneLogLevel = 0;
  6877. Tools._PerformanceUserMarkLogLevel = 1;
  6878. Tools._PerformanceConsoleLogLevel = 2;
  6879. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6880. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6881. return Tools;
  6882. }());
  6883. BABYLON.Tools = Tools;
  6884. /**
  6885. * This class is used to track a performance counter which is number based.
  6886. * The user has access to many properties which give statistics of different nature
  6887. *
  6888. * The implementer can track two kinds of Performance Counter: time and count
  6889. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6890. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6891. */
  6892. var PerfCounter = /** @class */ (function () {
  6893. function PerfCounter() {
  6894. this._startMonitoringTime = 0;
  6895. this._min = 0;
  6896. this._max = 0;
  6897. this._average = 0;
  6898. this._lastSecAverage = 0;
  6899. this._current = 0;
  6900. this._totalValueCount = 0;
  6901. this._totalAccumulated = 0;
  6902. this._lastSecAccumulated = 0;
  6903. this._lastSecTime = 0;
  6904. this._lastSecValueCount = 0;
  6905. }
  6906. Object.defineProperty(PerfCounter.prototype, "min", {
  6907. /**
  6908. * Returns the smallest value ever
  6909. */
  6910. get: function () {
  6911. return this._min;
  6912. },
  6913. enumerable: true,
  6914. configurable: true
  6915. });
  6916. Object.defineProperty(PerfCounter.prototype, "max", {
  6917. /**
  6918. * Returns the biggest value ever
  6919. */
  6920. get: function () {
  6921. return this._max;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(PerfCounter.prototype, "average", {
  6927. /**
  6928. * Returns the average value since the performance counter is running
  6929. */
  6930. get: function () {
  6931. return this._average;
  6932. },
  6933. enumerable: true,
  6934. configurable: true
  6935. });
  6936. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6937. /**
  6938. * Returns the average value of the last second the counter was monitored
  6939. */
  6940. get: function () {
  6941. return this._lastSecAverage;
  6942. },
  6943. enumerable: true,
  6944. configurable: true
  6945. });
  6946. Object.defineProperty(PerfCounter.prototype, "current", {
  6947. /**
  6948. * Returns the current value
  6949. */
  6950. get: function () {
  6951. return this._current;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(PerfCounter.prototype, "total", {
  6957. get: function () {
  6958. return this._totalAccumulated;
  6959. },
  6960. enumerable: true,
  6961. configurable: true
  6962. });
  6963. Object.defineProperty(PerfCounter.prototype, "count", {
  6964. get: function () {
  6965. return this._totalValueCount;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. /**
  6971. * Call this method to start monitoring a new frame.
  6972. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6973. */
  6974. PerfCounter.prototype.fetchNewFrame = function () {
  6975. this._totalValueCount++;
  6976. this._current = 0;
  6977. this._lastSecValueCount++;
  6978. };
  6979. /**
  6980. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6981. * @param newCount the count value to add to the monitored count
  6982. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6983. */
  6984. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6985. if (!PerfCounter.Enabled) {
  6986. return;
  6987. }
  6988. this._current += newCount;
  6989. if (fetchResult) {
  6990. this._fetchResult();
  6991. }
  6992. };
  6993. /**
  6994. * Start monitoring this performance counter
  6995. */
  6996. PerfCounter.prototype.beginMonitoring = function () {
  6997. if (!PerfCounter.Enabled) {
  6998. return;
  6999. }
  7000. this._startMonitoringTime = Tools.Now;
  7001. };
  7002. /**
  7003. * Compute the time lapsed since the previous beginMonitoring() call.
  7004. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  7005. */
  7006. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7007. if (newFrame === void 0) { newFrame = true; }
  7008. if (!PerfCounter.Enabled) {
  7009. return;
  7010. }
  7011. if (newFrame) {
  7012. this.fetchNewFrame();
  7013. }
  7014. var currentTime = Tools.Now;
  7015. this._current = currentTime - this._startMonitoringTime;
  7016. if (newFrame) {
  7017. this._fetchResult();
  7018. }
  7019. };
  7020. PerfCounter.prototype._fetchResult = function () {
  7021. this._totalAccumulated += this._current;
  7022. this._lastSecAccumulated += this._current;
  7023. // Min/Max update
  7024. this._min = Math.min(this._min, this._current);
  7025. this._max = Math.max(this._max, this._current);
  7026. this._average = this._totalAccumulated / this._totalValueCount;
  7027. // Reset last sec?
  7028. var now = Tools.Now;
  7029. if ((now - this._lastSecTime) > 1000) {
  7030. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7031. this._lastSecTime = now;
  7032. this._lastSecAccumulated = 0;
  7033. this._lastSecValueCount = 0;
  7034. }
  7035. };
  7036. PerfCounter.Enabled = true;
  7037. return PerfCounter;
  7038. }());
  7039. BABYLON.PerfCounter = PerfCounter;
  7040. /**
  7041. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7042. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7043. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7044. * @param name The name of the class, case should be preserved
  7045. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7046. */
  7047. function className(name, module) {
  7048. return function (target) {
  7049. target["__bjsclassName__"] = name;
  7050. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7051. };
  7052. }
  7053. BABYLON.className = className;
  7054. /**
  7055. * An implementation of a loop for asynchronous functions.
  7056. */
  7057. var AsyncLoop = /** @class */ (function () {
  7058. /**
  7059. * Constroctor.
  7060. * @param iterations the number of iterations.
  7061. * @param _fn the function to run each iteration
  7062. * @param _successCallback the callback that will be called upon succesful execution
  7063. * @param offset starting offset.
  7064. */
  7065. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7066. if (offset === void 0) { offset = 0; }
  7067. this.iterations = iterations;
  7068. this._fn = _fn;
  7069. this._successCallback = _successCallback;
  7070. this.index = offset - 1;
  7071. this._done = false;
  7072. }
  7073. /**
  7074. * Execute the next iteration. Must be called after the last iteration was finished.
  7075. */
  7076. AsyncLoop.prototype.executeNext = function () {
  7077. if (!this._done) {
  7078. if (this.index + 1 < this.iterations) {
  7079. ++this.index;
  7080. this._fn(this);
  7081. }
  7082. else {
  7083. this.breakLoop();
  7084. }
  7085. }
  7086. };
  7087. /**
  7088. * Break the loop and run the success callback.
  7089. */
  7090. AsyncLoop.prototype.breakLoop = function () {
  7091. this._done = true;
  7092. this._successCallback();
  7093. };
  7094. /**
  7095. * Helper function
  7096. */
  7097. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7098. if (offset === void 0) { offset = 0; }
  7099. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7100. loop.executeNext();
  7101. return loop;
  7102. };
  7103. /**
  7104. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7105. * @param iterations total number of iterations
  7106. * @param syncedIterations number of synchronous iterations in each async iteration.
  7107. * @param fn the function to call each iteration.
  7108. * @param callback a success call back that will be called when iterating stops.
  7109. * @param breakFunction a break condition (optional)
  7110. * @param timeout timeout settings for the setTimeout function. default - 0.
  7111. * @constructor
  7112. */
  7113. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7114. if (timeout === void 0) { timeout = 0; }
  7115. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7116. if (breakFunction && breakFunction())
  7117. loop.breakLoop();
  7118. else {
  7119. setTimeout(function () {
  7120. for (var i = 0; i < syncedIterations; ++i) {
  7121. var iteration = (loop.index * syncedIterations) + i;
  7122. if (iteration >= iterations)
  7123. break;
  7124. fn(iteration);
  7125. if (breakFunction && breakFunction()) {
  7126. loop.breakLoop();
  7127. break;
  7128. }
  7129. }
  7130. loop.executeNext();
  7131. }, timeout);
  7132. }
  7133. }, callback);
  7134. };
  7135. return AsyncLoop;
  7136. }());
  7137. BABYLON.AsyncLoop = AsyncLoop;
  7138. })(BABYLON || (BABYLON = {}));
  7139. //# sourceMappingURL=babylon.tools.js.map
  7140. var BABYLON;
  7141. (function (BABYLON) {
  7142. var Internals;
  7143. (function (Internals) {
  7144. var _AlphaState = /** @class */ (function () {
  7145. /**
  7146. * Initializes the state.
  7147. */
  7148. function _AlphaState() {
  7149. this._isAlphaBlendDirty = false;
  7150. this._isBlendFunctionParametersDirty = false;
  7151. this._isBlendEquationParametersDirty = false;
  7152. this._isBlendConstantsDirty = false;
  7153. this._alphaBlend = false;
  7154. this._blendFunctionParameters = new Array(4);
  7155. this._blendEquationParameters = new Array(2);
  7156. this._blendConstants = new Array(4);
  7157. this.reset();
  7158. }
  7159. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7160. get: function () {
  7161. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7162. },
  7163. enumerable: true,
  7164. configurable: true
  7165. });
  7166. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7167. get: function () {
  7168. return this._alphaBlend;
  7169. },
  7170. set: function (value) {
  7171. if (this._alphaBlend === value) {
  7172. return;
  7173. }
  7174. this._alphaBlend = value;
  7175. this._isAlphaBlendDirty = true;
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7181. if (this._blendConstants[0] === r &&
  7182. this._blendConstants[1] === g &&
  7183. this._blendConstants[2] === b &&
  7184. this._blendConstants[3] === a) {
  7185. return;
  7186. }
  7187. this._blendConstants[0] = r;
  7188. this._blendConstants[1] = g;
  7189. this._blendConstants[2] = b;
  7190. this._blendConstants[3] = a;
  7191. this._isBlendConstantsDirty = true;
  7192. };
  7193. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7194. if (this._blendFunctionParameters[0] === value0 &&
  7195. this._blendFunctionParameters[1] === value1 &&
  7196. this._blendFunctionParameters[2] === value2 &&
  7197. this._blendFunctionParameters[3] === value3) {
  7198. return;
  7199. }
  7200. this._blendFunctionParameters[0] = value0;
  7201. this._blendFunctionParameters[1] = value1;
  7202. this._blendFunctionParameters[2] = value2;
  7203. this._blendFunctionParameters[3] = value3;
  7204. this._isBlendFunctionParametersDirty = true;
  7205. };
  7206. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7207. if (this._blendEquationParameters[0] === rgb &&
  7208. this._blendEquationParameters[1] === alpha) {
  7209. return;
  7210. }
  7211. this._blendEquationParameters[0] = rgb;
  7212. this._blendEquationParameters[1] = alpha;
  7213. this._isBlendEquationParametersDirty = true;
  7214. };
  7215. _AlphaState.prototype.reset = function () {
  7216. this._alphaBlend = false;
  7217. this._blendFunctionParameters[0] = null;
  7218. this._blendFunctionParameters[1] = null;
  7219. this._blendFunctionParameters[2] = null;
  7220. this._blendFunctionParameters[3] = null;
  7221. this._blendEquationParameters[0] = null;
  7222. this._blendEquationParameters[1] = null;
  7223. this._blendConstants[0] = null;
  7224. this._blendConstants[1] = null;
  7225. this._blendConstants[2] = null;
  7226. this._blendConstants[3] = null;
  7227. this._isAlphaBlendDirty = true;
  7228. this._isBlendFunctionParametersDirty = false;
  7229. this._isBlendEquationParametersDirty = false;
  7230. this._isBlendConstantsDirty = false;
  7231. };
  7232. _AlphaState.prototype.apply = function (gl) {
  7233. if (!this.isDirty) {
  7234. return;
  7235. }
  7236. // Alpha blend
  7237. if (this._isAlphaBlendDirty) {
  7238. if (this._alphaBlend) {
  7239. gl.enable(gl.BLEND);
  7240. }
  7241. else {
  7242. gl.disable(gl.BLEND);
  7243. }
  7244. this._isAlphaBlendDirty = false;
  7245. }
  7246. // Alpha function
  7247. if (this._isBlendFunctionParametersDirty) {
  7248. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7249. this._isBlendFunctionParametersDirty = false;
  7250. }
  7251. // Alpha equation
  7252. if (this._isBlendEquationParametersDirty) {
  7253. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7254. this._isBlendEquationParametersDirty = false;
  7255. }
  7256. // Constants
  7257. if (this._isBlendConstantsDirty) {
  7258. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7259. this._isBlendConstantsDirty = false;
  7260. }
  7261. };
  7262. return _AlphaState;
  7263. }());
  7264. Internals._AlphaState = _AlphaState;
  7265. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7266. })(BABYLON || (BABYLON = {}));
  7267. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7268. var BABYLON;
  7269. (function (BABYLON) {
  7270. var Internals;
  7271. (function (Internals) {
  7272. var _DepthCullingState = /** @class */ (function () {
  7273. /**
  7274. * Initializes the state.
  7275. */
  7276. function _DepthCullingState() {
  7277. this._isDepthTestDirty = false;
  7278. this._isDepthMaskDirty = false;
  7279. this._isDepthFuncDirty = false;
  7280. this._isCullFaceDirty = false;
  7281. this._isCullDirty = false;
  7282. this._isZOffsetDirty = false;
  7283. this.reset();
  7284. }
  7285. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7286. get: function () {
  7287. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7288. },
  7289. enumerable: true,
  7290. configurable: true
  7291. });
  7292. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7293. get: function () {
  7294. return this._zOffset;
  7295. },
  7296. set: function (value) {
  7297. if (this._zOffset === value) {
  7298. return;
  7299. }
  7300. this._zOffset = value;
  7301. this._isZOffsetDirty = true;
  7302. },
  7303. enumerable: true,
  7304. configurable: true
  7305. });
  7306. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7307. get: function () {
  7308. return this._cullFace;
  7309. },
  7310. set: function (value) {
  7311. if (this._cullFace === value) {
  7312. return;
  7313. }
  7314. this._cullFace = value;
  7315. this._isCullFaceDirty = true;
  7316. },
  7317. enumerable: true,
  7318. configurable: true
  7319. });
  7320. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7321. get: function () {
  7322. return this._cull;
  7323. },
  7324. set: function (value) {
  7325. if (this._cull === value) {
  7326. return;
  7327. }
  7328. this._cull = value;
  7329. this._isCullDirty = true;
  7330. },
  7331. enumerable: true,
  7332. configurable: true
  7333. });
  7334. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7335. get: function () {
  7336. return this._depthFunc;
  7337. },
  7338. set: function (value) {
  7339. if (this._depthFunc === value) {
  7340. return;
  7341. }
  7342. this._depthFunc = value;
  7343. this._isDepthFuncDirty = true;
  7344. },
  7345. enumerable: true,
  7346. configurable: true
  7347. });
  7348. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7349. get: function () {
  7350. return this._depthMask;
  7351. },
  7352. set: function (value) {
  7353. if (this._depthMask === value) {
  7354. return;
  7355. }
  7356. this._depthMask = value;
  7357. this._isDepthMaskDirty = true;
  7358. },
  7359. enumerable: true,
  7360. configurable: true
  7361. });
  7362. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7363. get: function () {
  7364. return this._depthTest;
  7365. },
  7366. set: function (value) {
  7367. if (this._depthTest === value) {
  7368. return;
  7369. }
  7370. this._depthTest = value;
  7371. this._isDepthTestDirty = true;
  7372. },
  7373. enumerable: true,
  7374. configurable: true
  7375. });
  7376. _DepthCullingState.prototype.reset = function () {
  7377. this._depthMask = true;
  7378. this._depthTest = true;
  7379. this._depthFunc = null;
  7380. this._cullFace = null;
  7381. this._cull = null;
  7382. this._zOffset = 0;
  7383. this._isDepthTestDirty = true;
  7384. this._isDepthMaskDirty = true;
  7385. this._isDepthFuncDirty = false;
  7386. this._isCullFaceDirty = false;
  7387. this._isCullDirty = false;
  7388. this._isZOffsetDirty = false;
  7389. };
  7390. _DepthCullingState.prototype.apply = function (gl) {
  7391. if (!this.isDirty) {
  7392. return;
  7393. }
  7394. // Cull
  7395. if (this._isCullDirty) {
  7396. if (this.cull) {
  7397. gl.enable(gl.CULL_FACE);
  7398. }
  7399. else {
  7400. gl.disable(gl.CULL_FACE);
  7401. }
  7402. this._isCullDirty = false;
  7403. }
  7404. // Cull face
  7405. if (this._isCullFaceDirty) {
  7406. gl.cullFace(this.cullFace);
  7407. this._isCullFaceDirty = false;
  7408. }
  7409. // Depth mask
  7410. if (this._isDepthMaskDirty) {
  7411. gl.depthMask(this.depthMask);
  7412. this._isDepthMaskDirty = false;
  7413. }
  7414. // Depth test
  7415. if (this._isDepthTestDirty) {
  7416. if (this.depthTest) {
  7417. gl.enable(gl.DEPTH_TEST);
  7418. }
  7419. else {
  7420. gl.disable(gl.DEPTH_TEST);
  7421. }
  7422. this._isDepthTestDirty = false;
  7423. }
  7424. // Depth func
  7425. if (this._isDepthFuncDirty) {
  7426. gl.depthFunc(this.depthFunc);
  7427. this._isDepthFuncDirty = false;
  7428. }
  7429. // zOffset
  7430. if (this._isZOffsetDirty) {
  7431. if (this.zOffset) {
  7432. gl.enable(gl.POLYGON_OFFSET_FILL);
  7433. gl.polygonOffset(this.zOffset, 0);
  7434. }
  7435. else {
  7436. gl.disable(gl.POLYGON_OFFSET_FILL);
  7437. }
  7438. this._isZOffsetDirty = false;
  7439. }
  7440. };
  7441. return _DepthCullingState;
  7442. }());
  7443. Internals._DepthCullingState = _DepthCullingState;
  7444. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7445. })(BABYLON || (BABYLON = {}));
  7446. //# sourceMappingURL=babylon.depthCullingState.js.map
  7447. var BABYLON;
  7448. (function (BABYLON) {
  7449. var Internals;
  7450. (function (Internals) {
  7451. var _StencilState = /** @class */ (function () {
  7452. function _StencilState() {
  7453. this._isStencilTestDirty = false;
  7454. this._isStencilMaskDirty = false;
  7455. this._isStencilFuncDirty = false;
  7456. this._isStencilOpDirty = false;
  7457. this.reset();
  7458. }
  7459. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7460. get: function () {
  7461. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7467. get: function () {
  7468. return this._stencilFunc;
  7469. },
  7470. set: function (value) {
  7471. if (this._stencilFunc === value) {
  7472. return;
  7473. }
  7474. this._stencilFunc = value;
  7475. this._isStencilFuncDirty = true;
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7481. get: function () {
  7482. return this._stencilFuncRef;
  7483. },
  7484. set: function (value) {
  7485. if (this._stencilFuncRef === value) {
  7486. return;
  7487. }
  7488. this._stencilFuncRef = value;
  7489. this._isStencilFuncDirty = true;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7495. get: function () {
  7496. return this._stencilFuncMask;
  7497. },
  7498. set: function (value) {
  7499. if (this._stencilFuncMask === value) {
  7500. return;
  7501. }
  7502. this._stencilFuncMask = value;
  7503. this._isStencilFuncDirty = true;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7509. get: function () {
  7510. return this._stencilOpStencilFail;
  7511. },
  7512. set: function (value) {
  7513. if (this._stencilOpStencilFail === value) {
  7514. return;
  7515. }
  7516. this._stencilOpStencilFail = value;
  7517. this._isStencilOpDirty = true;
  7518. },
  7519. enumerable: true,
  7520. configurable: true
  7521. });
  7522. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7523. get: function () {
  7524. return this._stencilOpDepthFail;
  7525. },
  7526. set: function (value) {
  7527. if (this._stencilOpDepthFail === value) {
  7528. return;
  7529. }
  7530. this._stencilOpDepthFail = value;
  7531. this._isStencilOpDirty = true;
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7537. get: function () {
  7538. return this._stencilOpStencilDepthPass;
  7539. },
  7540. set: function (value) {
  7541. if (this._stencilOpStencilDepthPass === value) {
  7542. return;
  7543. }
  7544. this._stencilOpStencilDepthPass = value;
  7545. this._isStencilOpDirty = true;
  7546. },
  7547. enumerable: true,
  7548. configurable: true
  7549. });
  7550. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7551. get: function () {
  7552. return this._stencilMask;
  7553. },
  7554. set: function (value) {
  7555. if (this._stencilMask === value) {
  7556. return;
  7557. }
  7558. this._stencilMask = value;
  7559. this._isStencilMaskDirty = true;
  7560. },
  7561. enumerable: true,
  7562. configurable: true
  7563. });
  7564. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7565. get: function () {
  7566. return this._stencilTest;
  7567. },
  7568. set: function (value) {
  7569. if (this._stencilTest === value) {
  7570. return;
  7571. }
  7572. this._stencilTest = value;
  7573. this._isStencilTestDirty = true;
  7574. },
  7575. enumerable: true,
  7576. configurable: true
  7577. });
  7578. _StencilState.prototype.reset = function () {
  7579. this._stencilTest = false;
  7580. this._stencilMask = 0xFF;
  7581. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7582. this._stencilFuncRef = 1;
  7583. this._stencilFuncMask = 0xFF;
  7584. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7585. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7586. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7587. this._isStencilTestDirty = true;
  7588. this._isStencilMaskDirty = true;
  7589. this._isStencilFuncDirty = true;
  7590. this._isStencilOpDirty = true;
  7591. };
  7592. _StencilState.prototype.apply = function (gl) {
  7593. if (!this.isDirty) {
  7594. return;
  7595. }
  7596. // Stencil test
  7597. if (this._isStencilTestDirty) {
  7598. if (this.stencilTest) {
  7599. gl.enable(gl.STENCIL_TEST);
  7600. }
  7601. else {
  7602. gl.disable(gl.STENCIL_TEST);
  7603. }
  7604. this._isStencilTestDirty = false;
  7605. }
  7606. // Stencil mask
  7607. if (this._isStencilMaskDirty) {
  7608. gl.stencilMask(this.stencilMask);
  7609. this._isStencilMaskDirty = false;
  7610. }
  7611. // Stencil func
  7612. if (this._isStencilFuncDirty) {
  7613. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7614. this._isStencilFuncDirty = false;
  7615. }
  7616. // Stencil op
  7617. if (this._isStencilOpDirty) {
  7618. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7619. this._isStencilOpDirty = false;
  7620. }
  7621. };
  7622. return _StencilState;
  7623. }());
  7624. Internals._StencilState = _StencilState;
  7625. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7626. })(BABYLON || (BABYLON = {}));
  7627. //# sourceMappingURL=babylon.stencilState.js.map
  7628. var BABYLON;
  7629. (function (BABYLON) {
  7630. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7631. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7632. };
  7633. var compileRawShader = function (gl, source, type) {
  7634. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7635. gl.shaderSource(shader, source);
  7636. gl.compileShader(shader);
  7637. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7638. var log = gl.getShaderInfoLog(shader);
  7639. if (log) {
  7640. throw new Error(log);
  7641. }
  7642. }
  7643. if (!shader) {
  7644. throw new Error("Something went wrong while compile the shader.");
  7645. }
  7646. return shader;
  7647. };
  7648. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7649. var magFilter = gl.NEAREST;
  7650. var minFilter = gl.NEAREST;
  7651. switch (samplingMode) {
  7652. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7653. magFilter = gl.LINEAR;
  7654. if (generateMipMaps) {
  7655. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7656. }
  7657. else {
  7658. minFilter = gl.LINEAR;
  7659. }
  7660. break;
  7661. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7662. magFilter = gl.LINEAR;
  7663. if (generateMipMaps) {
  7664. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7665. }
  7666. else {
  7667. minFilter = gl.LINEAR;
  7668. }
  7669. break;
  7670. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7671. magFilter = gl.NEAREST;
  7672. if (generateMipMaps) {
  7673. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7674. }
  7675. else {
  7676. minFilter = gl.NEAREST;
  7677. }
  7678. break;
  7679. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7680. magFilter = gl.NEAREST;
  7681. if (generateMipMaps) {
  7682. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7683. }
  7684. else {
  7685. minFilter = gl.NEAREST;
  7686. }
  7687. break;
  7688. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7689. magFilter = gl.NEAREST;
  7690. if (generateMipMaps) {
  7691. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7692. }
  7693. else {
  7694. minFilter = gl.LINEAR;
  7695. }
  7696. break;
  7697. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7698. magFilter = gl.NEAREST;
  7699. if (generateMipMaps) {
  7700. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7701. }
  7702. else {
  7703. minFilter = gl.LINEAR;
  7704. }
  7705. break;
  7706. case BABYLON.Texture.NEAREST_LINEAR:
  7707. magFilter = gl.NEAREST;
  7708. minFilter = gl.LINEAR;
  7709. break;
  7710. case BABYLON.Texture.NEAREST_NEAREST:
  7711. magFilter = gl.NEAREST;
  7712. minFilter = gl.NEAREST;
  7713. break;
  7714. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7715. magFilter = gl.LINEAR;
  7716. if (generateMipMaps) {
  7717. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7718. }
  7719. else {
  7720. minFilter = gl.NEAREST;
  7721. }
  7722. break;
  7723. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7724. magFilter = gl.LINEAR;
  7725. if (generateMipMaps) {
  7726. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7727. }
  7728. else {
  7729. minFilter = gl.NEAREST;
  7730. }
  7731. break;
  7732. case BABYLON.Texture.LINEAR_LINEAR:
  7733. magFilter = gl.LINEAR;
  7734. minFilter = gl.LINEAR;
  7735. break;
  7736. case BABYLON.Texture.LINEAR_NEAREST:
  7737. magFilter = gl.LINEAR;
  7738. minFilter = gl.NEAREST;
  7739. break;
  7740. }
  7741. return {
  7742. min: minFilter,
  7743. mag: magFilter
  7744. };
  7745. };
  7746. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7747. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7748. var img;
  7749. var onload = function () {
  7750. loadedImages[index] = img;
  7751. loadedImages._internalCount++;
  7752. if (scene) {
  7753. scene._removePendingData(img);
  7754. }
  7755. if (loadedImages._internalCount === 6) {
  7756. onfinish(loadedImages);
  7757. }
  7758. };
  7759. var onerror = function (message, exception) {
  7760. if (scene) {
  7761. scene._removePendingData(img);
  7762. }
  7763. if (onErrorCallBack) {
  7764. onErrorCallBack(message, exception);
  7765. }
  7766. };
  7767. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7768. if (scene) {
  7769. scene._addPendingData(img);
  7770. }
  7771. };
  7772. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7773. if (onError === void 0) { onError = null; }
  7774. var loadedImages = [];
  7775. loadedImages._internalCount = 0;
  7776. for (var index = 0; index < 6; index++) {
  7777. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7778. }
  7779. };
  7780. var BufferPointer = /** @class */ (function () {
  7781. function BufferPointer() {
  7782. }
  7783. return BufferPointer;
  7784. }());
  7785. var InstancingAttributeInfo = /** @class */ (function () {
  7786. function InstancingAttributeInfo() {
  7787. }
  7788. return InstancingAttributeInfo;
  7789. }());
  7790. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7791. /**
  7792. * Define options used to create a render target texture
  7793. */
  7794. var RenderTargetCreationOptions = /** @class */ (function () {
  7795. function RenderTargetCreationOptions() {
  7796. }
  7797. return RenderTargetCreationOptions;
  7798. }());
  7799. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7800. /**
  7801. * Regroup several parameters relative to the browser in use
  7802. */
  7803. var EngineCapabilities = /** @class */ (function () {
  7804. function EngineCapabilities() {
  7805. }
  7806. return EngineCapabilities;
  7807. }());
  7808. BABYLON.EngineCapabilities = EngineCapabilities;
  7809. /**
  7810. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7811. */
  7812. var Engine = /** @class */ (function () {
  7813. /**
  7814. * @constructor
  7815. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7816. * @param {boolean} [antialias] - enable antialias
  7817. * @param options - further options to be sent to the getContext function
  7818. */
  7819. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7820. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7821. var _this = this;
  7822. // Public members
  7823. this.forcePOTTextures = false;
  7824. this.isFullscreen = false;
  7825. this.isPointerLock = false;
  7826. this.cullBackFaces = true;
  7827. this.renderEvenInBackground = true;
  7828. this.preventCacheWipeBetweenFrames = false;
  7829. // To enable/disable IDB support and avoid XHR on .manifest
  7830. this.enableOfflineSupport = false;
  7831. this.scenes = new Array();
  7832. this.postProcesses = new Array();
  7833. // Observables
  7834. /**
  7835. * Observable event triggered each time the rendering canvas is resized
  7836. */
  7837. this.onResizeObservable = new BABYLON.Observable();
  7838. /**
  7839. * Observable event triggered each time the canvas loses focus
  7840. */
  7841. this.onCanvasBlurObservable = new BABYLON.Observable();
  7842. /**
  7843. * Observable event triggered each time the canvas gains focus
  7844. */
  7845. this.onCanvasFocusObservable = new BABYLON.Observable();
  7846. /**
  7847. * Observable event triggered each time the canvas receives pointerout event
  7848. */
  7849. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7850. /**
  7851. * Observable event triggered before each texture is initialized
  7852. */
  7853. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7854. //WebVR
  7855. this._vrDisplay = undefined;
  7856. this._vrSupported = false;
  7857. this._vrExclusivePointerMode = false;
  7858. // Uniform buffers list
  7859. this.disableUniformBuffers = false;
  7860. this._uniformBuffers = new Array();
  7861. // Observables
  7862. /**
  7863. * Observable raised when the engine begins a new frame
  7864. */
  7865. this.onBeginFrameObservable = new BABYLON.Observable();
  7866. /**
  7867. * Observable raised when the engine ends the current frame
  7868. */
  7869. this.onEndFrameObservable = new BABYLON.Observable();
  7870. /**
  7871. * Observable raised when the engine is about to compile a shader
  7872. */
  7873. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7874. /**
  7875. * Observable raised when the engine has jsut compiled a shader
  7876. */
  7877. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7878. this._windowIsBackground = false;
  7879. this._webGLVersion = 1.0;
  7880. this._badOS = false;
  7881. this._badDesktopOS = false;
  7882. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7883. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7884. this.onVRRequestPresentStart = new BABYLON.Observable();
  7885. this._colorWrite = true;
  7886. this._drawCalls = new BABYLON.PerfCounter();
  7887. this._renderingQueueLaunched = false;
  7888. this._activeRenderLoops = new Array();
  7889. // Deterministic lockstepMaxSteps
  7890. this._deterministicLockstep = false;
  7891. this._lockstepMaxSteps = 4;
  7892. // Lost context
  7893. this.onContextLostObservable = new BABYLON.Observable();
  7894. this.onContextRestoredObservable = new BABYLON.Observable();
  7895. this._contextWasLost = false;
  7896. this._doNotHandleContextLost = false;
  7897. // FPS
  7898. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7899. this._fps = 60;
  7900. this._deltaTime = 0;
  7901. /**
  7902. * Turn this value on if you want to pause FPS computation when in background
  7903. */
  7904. this.disablePerformanceMonitorInBackground = false;
  7905. // States
  7906. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7907. this._stencilState = new BABYLON.Internals._StencilState();
  7908. this._alphaState = new BABYLON.Internals._AlphaState();
  7909. this._alphaMode = Engine.ALPHA_DISABLE;
  7910. // Cache
  7911. this._internalTexturesCache = new Array();
  7912. this._activeTexturesCache = {};
  7913. this._compiledEffects = {};
  7914. this._vertexAttribArraysEnabled = [];
  7915. this._uintIndicesCurrentlySet = false;
  7916. this._currentBoundBuffer = new Array();
  7917. this._currentBufferPointers = new Array();
  7918. this._currentInstanceLocations = new Array();
  7919. this._currentInstanceBuffers = new Array();
  7920. this._vaoRecordInProgress = false;
  7921. this._mustWipeVertexAttributes = false;
  7922. // Hardware supported Compressed Textures
  7923. this._texturesSupported = new Array();
  7924. this._onVRFullScreenTriggered = function () {
  7925. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7926. //get the old size before we change
  7927. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7928. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7929. //get the width and height, change the render size
  7930. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7931. _this.setHardwareScalingLevel(1);
  7932. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7933. }
  7934. else {
  7935. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7936. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7937. }
  7938. };
  7939. var canvas = null;
  7940. Engine.Instances.push(this);
  7941. if (!canvasOrContext) {
  7942. return;
  7943. }
  7944. options = options || {};
  7945. if (canvasOrContext.getContext) {
  7946. canvas = canvasOrContext;
  7947. this._renderingCanvas = canvas;
  7948. if (antialias != null) {
  7949. options.antialias = antialias;
  7950. }
  7951. if (options.deterministicLockstep === undefined) {
  7952. options.deterministicLockstep = false;
  7953. }
  7954. if (options.lockstepMaxSteps === undefined) {
  7955. options.lockstepMaxSteps = 4;
  7956. }
  7957. if (options.preserveDrawingBuffer === undefined) {
  7958. options.preserveDrawingBuffer = false;
  7959. }
  7960. if (options.audioEngine === undefined) {
  7961. options.audioEngine = true;
  7962. }
  7963. if (options.stencil === undefined) {
  7964. options.stencil = true;
  7965. }
  7966. this._deterministicLockstep = options.deterministicLockstep;
  7967. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7968. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7969. // GL
  7970. if (!options.disableWebGL2Support) {
  7971. try {
  7972. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7973. if (this._gl) {
  7974. this._webGLVersion = 2.0;
  7975. }
  7976. }
  7977. catch (e) {
  7978. // Do nothing
  7979. }
  7980. }
  7981. if (!this._gl) {
  7982. if (!canvas) {
  7983. throw new Error("The provided canvas is null or undefined.");
  7984. }
  7985. try {
  7986. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7987. }
  7988. catch (e) {
  7989. throw new Error("WebGL not supported");
  7990. }
  7991. }
  7992. if (!this._gl) {
  7993. throw new Error("WebGL not supported");
  7994. }
  7995. this._onCanvasFocus = function () {
  7996. _this.onCanvasFocusObservable.notifyObservers(_this);
  7997. };
  7998. this._onCanvasBlur = function () {
  7999. _this.onCanvasBlurObservable.notifyObservers(_this);
  8000. };
  8001. canvas.addEventListener("focus", this._onCanvasFocus);
  8002. canvas.addEventListener("blur", this._onCanvasBlur);
  8003. this._onBlur = function () {
  8004. if (_this.disablePerformanceMonitorInBackground) {
  8005. _this._performanceMonitor.disable();
  8006. }
  8007. _this._windowIsBackground = true;
  8008. };
  8009. this._onFocus = function () {
  8010. if (_this.disablePerformanceMonitorInBackground) {
  8011. _this._performanceMonitor.enable();
  8012. }
  8013. _this._windowIsBackground = false;
  8014. };
  8015. this._onCanvasPointerOut = function () {
  8016. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8017. };
  8018. window.addEventListener("blur", this._onBlur);
  8019. window.addEventListener("focus", this._onFocus);
  8020. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8021. // Context lost
  8022. if (!this._doNotHandleContextLost) {
  8023. this._onContextLost = function (evt) {
  8024. evt.preventDefault();
  8025. _this._contextWasLost = true;
  8026. BABYLON.Tools.Warn("WebGL context lost.");
  8027. _this.onContextLostObservable.notifyObservers(_this);
  8028. };
  8029. this._onContextRestored = function (evt) {
  8030. // Adding a timeout to avoid race condition at browser level
  8031. setTimeout(function () {
  8032. // Rebuild gl context
  8033. _this._initGLContext();
  8034. // Rebuild effects
  8035. _this._rebuildEffects();
  8036. // Rebuild textures
  8037. _this._rebuildInternalTextures();
  8038. // Rebuild buffers
  8039. _this._rebuildBuffers();
  8040. // Cache
  8041. _this.wipeCaches(true);
  8042. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8043. _this.onContextRestoredObservable.notifyObservers(_this);
  8044. _this._contextWasLost = false;
  8045. }, 0);
  8046. };
  8047. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8048. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8049. }
  8050. }
  8051. else {
  8052. this._gl = canvasOrContext;
  8053. this._renderingCanvas = this._gl.canvas;
  8054. if (this._gl.renderbufferStorageMultisample) {
  8055. this._webGLVersion = 2.0;
  8056. }
  8057. options.stencil = this._gl.getContextAttributes().stencil;
  8058. }
  8059. // Viewport
  8060. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8061. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8062. this.resize();
  8063. this._isStencilEnable = options.stencil ? true : false;
  8064. this._initGLContext();
  8065. if (canvas) {
  8066. // Fullscreen
  8067. this._onFullscreenChange = function () {
  8068. if (document.fullscreen !== undefined) {
  8069. _this.isFullscreen = document.fullscreen;
  8070. }
  8071. else if (document.mozFullScreen !== undefined) {
  8072. _this.isFullscreen = document.mozFullScreen;
  8073. }
  8074. else if (document.webkitIsFullScreen !== undefined) {
  8075. _this.isFullscreen = document.webkitIsFullScreen;
  8076. }
  8077. else if (document.msIsFullScreen !== undefined) {
  8078. _this.isFullscreen = document.msIsFullScreen;
  8079. }
  8080. // Pointer lock
  8081. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8082. canvas.requestPointerLock = canvas.requestPointerLock ||
  8083. canvas.msRequestPointerLock ||
  8084. canvas.mozRequestPointerLock ||
  8085. canvas.webkitRequestPointerLock;
  8086. if (canvas.requestPointerLock) {
  8087. canvas.requestPointerLock();
  8088. }
  8089. }
  8090. };
  8091. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8092. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8093. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8094. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8095. // Pointer lock
  8096. this._onPointerLockChange = function () {
  8097. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8098. document.webkitPointerLockElement === canvas ||
  8099. document.msPointerLockElement === canvas ||
  8100. document.pointerLockElement === canvas);
  8101. };
  8102. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8103. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8104. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8105. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8106. this._onVRDisplayPointerRestricted = function () {
  8107. if (canvas) {
  8108. canvas.requestPointerLock();
  8109. }
  8110. };
  8111. this._onVRDisplayPointerUnrestricted = function () {
  8112. document.exitPointerLock();
  8113. };
  8114. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8115. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8116. }
  8117. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8118. Engine.audioEngine = new BABYLON.AudioEngine();
  8119. }
  8120. // Prepare buffer pointers
  8121. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8122. this._currentBufferPointers[i] = new BufferPointer();
  8123. }
  8124. // Load WebVR Devices
  8125. if (options.autoEnableWebVR) {
  8126. this.initWebVR();
  8127. }
  8128. // Detect if we are running on a faulty buggy OS.
  8129. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8130. // Detect if we are running on a faulty buggy desktop OS.
  8131. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8132. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8133. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8134. }
  8135. Object.defineProperty(Engine, "LastCreatedEngine", {
  8136. get: function () {
  8137. if (Engine.Instances.length === 0) {
  8138. return null;
  8139. }
  8140. return Engine.Instances[Engine.Instances.length - 1];
  8141. },
  8142. enumerable: true,
  8143. configurable: true
  8144. });
  8145. Object.defineProperty(Engine, "LastCreatedScene", {
  8146. get: function () {
  8147. var lastCreatedEngine = Engine.LastCreatedEngine;
  8148. if (!lastCreatedEngine) {
  8149. return null;
  8150. }
  8151. if (lastCreatedEngine.scenes.length === 0) {
  8152. return null;
  8153. }
  8154. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8155. },
  8156. enumerable: true,
  8157. configurable: true
  8158. });
  8159. /**
  8160. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8161. */
  8162. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8163. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8164. var engine = Engine.Instances[engineIndex];
  8165. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8166. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8167. }
  8168. }
  8169. };
  8170. Object.defineProperty(Engine, "NEVER", {
  8171. get: function () {
  8172. return Engine._NEVER;
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. Object.defineProperty(Engine, "ALWAYS", {
  8178. get: function () {
  8179. return Engine._ALWAYS;
  8180. },
  8181. enumerable: true,
  8182. configurable: true
  8183. });
  8184. Object.defineProperty(Engine, "LESS", {
  8185. get: function () {
  8186. return Engine._LESS;
  8187. },
  8188. enumerable: true,
  8189. configurable: true
  8190. });
  8191. Object.defineProperty(Engine, "EQUAL", {
  8192. get: function () {
  8193. return Engine._EQUAL;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. Object.defineProperty(Engine, "LEQUAL", {
  8199. get: function () {
  8200. return Engine._LEQUAL;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. Object.defineProperty(Engine, "GREATER", {
  8206. get: function () {
  8207. return Engine._GREATER;
  8208. },
  8209. enumerable: true,
  8210. configurable: true
  8211. });
  8212. Object.defineProperty(Engine, "GEQUAL", {
  8213. get: function () {
  8214. return Engine._GEQUAL;
  8215. },
  8216. enumerable: true,
  8217. configurable: true
  8218. });
  8219. Object.defineProperty(Engine, "NOTEQUAL", {
  8220. get: function () {
  8221. return Engine._NOTEQUAL;
  8222. },
  8223. enumerable: true,
  8224. configurable: true
  8225. });
  8226. Object.defineProperty(Engine, "KEEP", {
  8227. get: function () {
  8228. return Engine._KEEP;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(Engine, "REPLACE", {
  8234. get: function () {
  8235. return Engine._REPLACE;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. Object.defineProperty(Engine, "INCR", {
  8241. get: function () {
  8242. return Engine._INCR;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Object.defineProperty(Engine, "DECR", {
  8248. get: function () {
  8249. return Engine._DECR;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(Engine, "INVERT", {
  8255. get: function () {
  8256. return Engine._INVERT;
  8257. },
  8258. enumerable: true,
  8259. configurable: true
  8260. });
  8261. Object.defineProperty(Engine, "INCR_WRAP", {
  8262. get: function () {
  8263. return Engine._INCR_WRAP;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(Engine, "DECR_WRAP", {
  8269. get: function () {
  8270. return Engine._DECR_WRAP;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8276. get: function () {
  8277. return Engine._ALPHA_DISABLE;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8283. get: function () {
  8284. return Engine._ALPHA_ONEONE;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(Engine, "ALPHA_ADD", {
  8290. get: function () {
  8291. return Engine._ALPHA_ADD;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8297. get: function () {
  8298. return Engine._ALPHA_COMBINE;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8304. get: function () {
  8305. return Engine._ALPHA_SUBTRACT;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8311. get: function () {
  8312. return Engine._ALPHA_MULTIPLY;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8318. get: function () {
  8319. return Engine._ALPHA_MAXIMIZED;
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8325. get: function () {
  8326. return Engine._ALPHA_PREMULTIPLIED;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8332. get: function () {
  8333. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8339. get: function () {
  8340. return Engine._ALPHA_INTERPOLATE;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8346. get: function () {
  8347. return Engine._ALPHA_SCREENMODE;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8353. get: function () {
  8354. return Engine._DELAYLOADSTATE_NONE;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8360. get: function () {
  8361. return Engine._DELAYLOADSTATE_LOADED;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8367. get: function () {
  8368. return Engine._DELAYLOADSTATE_LOADING;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8374. get: function () {
  8375. return Engine._DELAYLOADSTATE_NOTLOADED;
  8376. },
  8377. enumerable: true,
  8378. configurable: true
  8379. });
  8380. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8381. get: function () {
  8382. return Engine._TEXTUREFORMAT_ALPHA;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8388. get: function () {
  8389. return Engine._TEXTUREFORMAT_LUMINANCE;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8395. get: function () {
  8396. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8402. get: function () {
  8403. return Engine._TEXTUREFORMAT_RGB;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8409. get: function () {
  8410. return Engine._TEXTUREFORMAT_RGBA;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8416. get: function () {
  8417. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8423. get: function () {
  8424. return Engine._TEXTURETYPE_FLOAT;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8430. get: function () {
  8431. return Engine._TEXTURETYPE_HALF_FLOAT;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8437. get: function () {
  8438. return Engine._SCALEMODE_FLOOR;
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8444. get: function () {
  8445. return Engine._SCALEMODE_NEAREST;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8451. get: function () {
  8452. return Engine._SCALEMODE_CEILING;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine, "Version", {
  8458. get: function () {
  8459. return "3.1-beta-2";
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8465. get: function () {
  8466. return this._vrExclusivePointerMode;
  8467. },
  8468. enumerable: true,
  8469. configurable: true
  8470. });
  8471. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8472. get: function () {
  8473. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8474. },
  8475. enumerable: true,
  8476. configurable: true
  8477. });
  8478. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8479. get: function () {
  8480. return this._webGLVersion < 2 || this.forcePOTTextures;
  8481. },
  8482. enumerable: true,
  8483. configurable: true
  8484. });
  8485. Object.defineProperty(Engine.prototype, "badOS", {
  8486. get: function () {
  8487. return this._badOS;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8493. get: function () {
  8494. return this._badDesktopOS;
  8495. },
  8496. enumerable: true,
  8497. configurable: true
  8498. });
  8499. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8500. get: function () {
  8501. return this._performanceMonitor;
  8502. },
  8503. enumerable: true,
  8504. configurable: true
  8505. });
  8506. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8507. get: function () {
  8508. return this._texturesSupported;
  8509. },
  8510. enumerable: true,
  8511. configurable: true
  8512. });
  8513. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8514. get: function () {
  8515. return this._textureFormatInUse;
  8516. },
  8517. enumerable: true,
  8518. configurable: true
  8519. });
  8520. Object.defineProperty(Engine.prototype, "currentViewport", {
  8521. get: function () {
  8522. return this._cachedViewport;
  8523. },
  8524. enumerable: true,
  8525. configurable: true
  8526. });
  8527. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8528. // Empty texture
  8529. get: function () {
  8530. if (!this._emptyTexture) {
  8531. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8532. }
  8533. return this._emptyTexture;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8539. get: function () {
  8540. if (!this._emptyTexture3D) {
  8541. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8542. }
  8543. return this._emptyTexture3D;
  8544. },
  8545. enumerable: true,
  8546. configurable: true
  8547. });
  8548. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8549. get: function () {
  8550. if (!this._emptyCubeTexture) {
  8551. var faceData = new Uint8Array(4);
  8552. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8553. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8554. }
  8555. return this._emptyCubeTexture;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Engine.prototype._rebuildInternalTextures = function () {
  8561. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8562. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8563. var internalTexture = currentState_1[_i];
  8564. internalTexture._rebuild();
  8565. }
  8566. };
  8567. Engine.prototype._rebuildEffects = function () {
  8568. for (var key in this._compiledEffects) {
  8569. var effect = this._compiledEffects[key];
  8570. effect._prepareEffect();
  8571. }
  8572. BABYLON.Effect.ResetCache();
  8573. };
  8574. Engine.prototype._rebuildBuffers = function () {
  8575. // Index / Vertex
  8576. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8577. var scene = _a[_i];
  8578. scene.resetCachedMaterial();
  8579. scene._rebuildGeometries();
  8580. scene._rebuildTextures();
  8581. }
  8582. // Uniforms
  8583. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8584. var uniformBuffer = _c[_b];
  8585. uniformBuffer._rebuild();
  8586. }
  8587. };
  8588. Engine.prototype._initGLContext = function () {
  8589. // Caps
  8590. this._caps = new EngineCapabilities();
  8591. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8592. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8593. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8594. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8595. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8596. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8597. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8598. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8599. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8600. // Infos
  8601. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8602. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8603. if (rendererInfo != null) {
  8604. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8605. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8606. }
  8607. if (!this._glVendor) {
  8608. this._glVendor = "Unknown vendor";
  8609. }
  8610. if (!this._glRenderer) {
  8611. this._glRenderer = "Unknown renderer";
  8612. }
  8613. // Constants
  8614. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8615. if (this._gl.RGBA16F !== 0x881A) {
  8616. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8617. }
  8618. if (this._gl.RGBA32F !== 0x8814) {
  8619. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8620. }
  8621. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8622. this._gl.DEPTH24_STENCIL8 = 35056;
  8623. }
  8624. // Extensions
  8625. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8626. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8627. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8628. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8629. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8630. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8631. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8632. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  8633. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8634. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8635. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8636. this._caps.highPrecisionShaderSupported = true;
  8637. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8638. if (this._caps.timerQuery) {
  8639. if (this._webGLVersion === 1) {
  8640. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8641. }
  8642. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8643. }
  8644. // Checks if some of the format renders first to allow the use of webgl inspector.
  8645. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8646. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8647. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8648. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8649. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8650. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8651. if (this._webGLVersion > 1) {
  8652. this._gl.HALF_FLOAT_OES = 0x140B;
  8653. }
  8654. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8655. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8656. // Draw buffers
  8657. if (this._webGLVersion > 1) {
  8658. this._caps.drawBuffersExtension = true;
  8659. }
  8660. else {
  8661. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8662. if (drawBuffersExtension !== null) {
  8663. this._caps.drawBuffersExtension = true;
  8664. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8665. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8666. for (var i = 0; i < 16; i++) {
  8667. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8668. }
  8669. }
  8670. else {
  8671. this._caps.drawBuffersExtension = false;
  8672. }
  8673. }
  8674. // Depth Texture
  8675. if (this._webGLVersion > 1) {
  8676. this._caps.depthTextureExtension = true;
  8677. }
  8678. else {
  8679. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8680. if (depthTextureExtension != null) {
  8681. this._caps.depthTextureExtension = true;
  8682. }
  8683. }
  8684. // Vertex array object
  8685. if (this._webGLVersion > 1) {
  8686. this._caps.vertexArrayObject = true;
  8687. }
  8688. else {
  8689. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8690. if (vertexArrayObjectExtension != null) {
  8691. this._caps.vertexArrayObject = true;
  8692. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8693. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8694. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8695. }
  8696. else {
  8697. this._caps.vertexArrayObject = false;
  8698. }
  8699. }
  8700. // Instances count
  8701. if (this._webGLVersion > 1) {
  8702. this._caps.instancedArrays = true;
  8703. }
  8704. else {
  8705. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8706. if (instanceExtension != null) {
  8707. this._caps.instancedArrays = true;
  8708. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8709. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8710. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8711. }
  8712. else {
  8713. this._caps.instancedArrays = false;
  8714. }
  8715. }
  8716. // Intelligently add supported compressed formats in order to check for.
  8717. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8718. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8719. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8720. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8721. if (this._caps.astc)
  8722. this.texturesSupported.push('-astc.ktx');
  8723. if (this._caps.s3tc)
  8724. this.texturesSupported.push('-dxt.ktx');
  8725. if (this._caps.pvrtc)
  8726. this.texturesSupported.push('-pvrtc.ktx');
  8727. if (this._caps.etc2)
  8728. this.texturesSupported.push('-etc2.ktx');
  8729. if (this._caps.etc1)
  8730. this.texturesSupported.push('-etc1.ktx');
  8731. if (this._gl.getShaderPrecisionFormat) {
  8732. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8733. if (highp) {
  8734. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8735. }
  8736. }
  8737. // Depth buffer
  8738. this.setDepthBuffer(true);
  8739. this.setDepthFunctionToLessOrEqual();
  8740. this.setDepthWrite(true);
  8741. };
  8742. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8743. get: function () {
  8744. return this._webGLVersion;
  8745. },
  8746. enumerable: true,
  8747. configurable: true
  8748. });
  8749. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8750. /**
  8751. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8752. */
  8753. get: function () {
  8754. return this._isStencilEnable;
  8755. },
  8756. enumerable: true,
  8757. configurable: true
  8758. });
  8759. Engine.prototype._prepareWorkingCanvas = function () {
  8760. if (this._workingCanvas) {
  8761. return;
  8762. }
  8763. this._workingCanvas = document.createElement("canvas");
  8764. var context = this._workingCanvas.getContext("2d");
  8765. if (context) {
  8766. this._workingContext = context;
  8767. }
  8768. };
  8769. Engine.prototype.resetTextureCache = function () {
  8770. for (var key in this._activeTexturesCache) {
  8771. this._activeTexturesCache[key] = null;
  8772. }
  8773. };
  8774. Engine.prototype.isDeterministicLockStep = function () {
  8775. return this._deterministicLockstep;
  8776. };
  8777. Engine.prototype.getLockstepMaxSteps = function () {
  8778. return this._lockstepMaxSteps;
  8779. };
  8780. Engine.prototype.getGlInfo = function () {
  8781. return {
  8782. vendor: this._glVendor,
  8783. renderer: this._glRenderer,
  8784. version: this._glVersion
  8785. };
  8786. };
  8787. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8788. if (useScreen === void 0) { useScreen = false; }
  8789. var viewport = camera.viewport;
  8790. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8791. };
  8792. Engine.prototype.getRenderWidth = function (useScreen) {
  8793. if (useScreen === void 0) { useScreen = false; }
  8794. if (!useScreen && this._currentRenderTarget) {
  8795. return this._currentRenderTarget.width;
  8796. }
  8797. return this._gl.drawingBufferWidth;
  8798. };
  8799. Engine.prototype.getRenderHeight = function (useScreen) {
  8800. if (useScreen === void 0) { useScreen = false; }
  8801. if (!useScreen && this._currentRenderTarget) {
  8802. return this._currentRenderTarget.height;
  8803. }
  8804. return this._gl.drawingBufferHeight;
  8805. };
  8806. Engine.prototype.getRenderingCanvas = function () {
  8807. return this._renderingCanvas;
  8808. };
  8809. Engine.prototype.getRenderingCanvasClientRect = function () {
  8810. if (!this._renderingCanvas) {
  8811. return null;
  8812. }
  8813. return this._renderingCanvas.getBoundingClientRect();
  8814. };
  8815. Engine.prototype.setHardwareScalingLevel = function (level) {
  8816. this._hardwareScalingLevel = level;
  8817. this.resize();
  8818. };
  8819. Engine.prototype.getHardwareScalingLevel = function () {
  8820. return this._hardwareScalingLevel;
  8821. };
  8822. Engine.prototype.getLoadedTexturesCache = function () {
  8823. return this._internalTexturesCache;
  8824. };
  8825. Engine.prototype.getCaps = function () {
  8826. return this._caps;
  8827. };
  8828. Object.defineProperty(Engine.prototype, "drawCalls", {
  8829. /** The number of draw calls submitted last frame */
  8830. get: function () {
  8831. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8832. return 0;
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8838. get: function () {
  8839. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8840. return null;
  8841. },
  8842. enumerable: true,
  8843. configurable: true
  8844. });
  8845. Engine.prototype.getDepthFunction = function () {
  8846. return this._depthCullingState.depthFunc;
  8847. };
  8848. Engine.prototype.setDepthFunction = function (depthFunc) {
  8849. this._depthCullingState.depthFunc = depthFunc;
  8850. };
  8851. Engine.prototype.setDepthFunctionToGreater = function () {
  8852. this._depthCullingState.depthFunc = this._gl.GREATER;
  8853. };
  8854. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8855. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8856. };
  8857. Engine.prototype.setDepthFunctionToLess = function () {
  8858. this._depthCullingState.depthFunc = this._gl.LESS;
  8859. };
  8860. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8861. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8862. };
  8863. Engine.prototype.getStencilBuffer = function () {
  8864. return this._stencilState.stencilTest;
  8865. };
  8866. Engine.prototype.setStencilBuffer = function (enable) {
  8867. this._stencilState.stencilTest = enable;
  8868. };
  8869. Engine.prototype.getStencilMask = function () {
  8870. return this._stencilState.stencilMask;
  8871. };
  8872. Engine.prototype.setStencilMask = function (mask) {
  8873. this._stencilState.stencilMask = mask;
  8874. };
  8875. Engine.prototype.getStencilFunction = function () {
  8876. return this._stencilState.stencilFunc;
  8877. };
  8878. Engine.prototype.getStencilFunctionReference = function () {
  8879. return this._stencilState.stencilFuncRef;
  8880. };
  8881. Engine.prototype.getStencilFunctionMask = function () {
  8882. return this._stencilState.stencilFuncMask;
  8883. };
  8884. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8885. this._stencilState.stencilFunc = stencilFunc;
  8886. };
  8887. Engine.prototype.setStencilFunctionReference = function (reference) {
  8888. this._stencilState.stencilFuncRef = reference;
  8889. };
  8890. Engine.prototype.setStencilFunctionMask = function (mask) {
  8891. this._stencilState.stencilFuncMask = mask;
  8892. };
  8893. Engine.prototype.getStencilOperationFail = function () {
  8894. return this._stencilState.stencilOpStencilFail;
  8895. };
  8896. Engine.prototype.getStencilOperationDepthFail = function () {
  8897. return this._stencilState.stencilOpDepthFail;
  8898. };
  8899. Engine.prototype.getStencilOperationPass = function () {
  8900. return this._stencilState.stencilOpStencilDepthPass;
  8901. };
  8902. Engine.prototype.setStencilOperationFail = function (operation) {
  8903. this._stencilState.stencilOpStencilFail = operation;
  8904. };
  8905. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8906. this._stencilState.stencilOpDepthFail = operation;
  8907. };
  8908. Engine.prototype.setStencilOperationPass = function (operation) {
  8909. this._stencilState.stencilOpStencilDepthPass = operation;
  8910. };
  8911. Engine.prototype.setDitheringState = function (value) {
  8912. if (value) {
  8913. this._gl.enable(this._gl.DITHER);
  8914. }
  8915. else {
  8916. this._gl.disable(this._gl.DITHER);
  8917. }
  8918. };
  8919. Engine.prototype.setRasterizerState = function (value) {
  8920. if (value) {
  8921. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  8922. }
  8923. else {
  8924. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  8925. }
  8926. };
  8927. /**
  8928. * stop executing a render loop function and remove it from the execution array
  8929. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8930. */
  8931. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8932. if (!renderFunction) {
  8933. this._activeRenderLoops = [];
  8934. return;
  8935. }
  8936. var index = this._activeRenderLoops.indexOf(renderFunction);
  8937. if (index >= 0) {
  8938. this._activeRenderLoops.splice(index, 1);
  8939. }
  8940. };
  8941. Engine.prototype._renderLoop = function () {
  8942. if (!this._contextWasLost) {
  8943. var shouldRender = true;
  8944. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8945. shouldRender = false;
  8946. }
  8947. if (shouldRender) {
  8948. // Start new frame
  8949. this.beginFrame();
  8950. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8951. var renderFunction = this._activeRenderLoops[index];
  8952. renderFunction();
  8953. }
  8954. // Present
  8955. this.endFrame();
  8956. }
  8957. }
  8958. if (this._activeRenderLoops.length > 0) {
  8959. // Register new frame
  8960. var requester = null;
  8961. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8962. requester = this._vrDisplay;
  8963. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8964. }
  8965. else {
  8966. this._renderingQueueLaunched = false;
  8967. }
  8968. };
  8969. /**
  8970. * Register and execute a render loop. The engine can have more than one render function.
  8971. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8972. * @example
  8973. * engine.runRenderLoop(function () {
  8974. * scene.render()
  8975. * })
  8976. */
  8977. Engine.prototype.runRenderLoop = function (renderFunction) {
  8978. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8979. return;
  8980. }
  8981. this._activeRenderLoops.push(renderFunction);
  8982. if (!this._renderingQueueLaunched) {
  8983. this._renderingQueueLaunched = true;
  8984. this._bindedRenderFunction = this._renderLoop.bind(this);
  8985. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8986. }
  8987. };
  8988. /**
  8989. * Toggle full screen mode.
  8990. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8991. * @param {any} options - an options object to be sent to the requestFullscreen function
  8992. */
  8993. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8994. if (this.isFullscreen) {
  8995. BABYLON.Tools.ExitFullscreen();
  8996. }
  8997. else {
  8998. this._pointerLockRequested = requestPointerLock;
  8999. if (this._renderingCanvas) {
  9000. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9001. }
  9002. }
  9003. };
  9004. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9005. if (stencil === void 0) { stencil = false; }
  9006. this.applyStates();
  9007. var mode = 0;
  9008. if (backBuffer && color) {
  9009. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9010. mode |= this._gl.COLOR_BUFFER_BIT;
  9011. }
  9012. if (depth) {
  9013. this._gl.clearDepth(1.0);
  9014. mode |= this._gl.DEPTH_BUFFER_BIT;
  9015. }
  9016. if (stencil) {
  9017. this._gl.clearStencil(0);
  9018. mode |= this._gl.STENCIL_BUFFER_BIT;
  9019. }
  9020. this._gl.clear(mode);
  9021. };
  9022. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9023. var gl = this._gl;
  9024. // Save state
  9025. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9026. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9027. // Change state
  9028. gl.enable(gl.SCISSOR_TEST);
  9029. gl.scissor(x, y, width, height);
  9030. // Clear
  9031. this.clear(clearColor, true, true, true);
  9032. // Restore state
  9033. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9034. if (curScissor === true) {
  9035. gl.enable(gl.SCISSOR_TEST);
  9036. }
  9037. else {
  9038. gl.disable(gl.SCISSOR_TEST);
  9039. }
  9040. };
  9041. /**
  9042. * Set the WebGL's viewport
  9043. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9044. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9045. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9046. */
  9047. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9048. var width = requiredWidth || this.getRenderWidth();
  9049. var height = requiredHeight || this.getRenderHeight();
  9050. var x = viewport.x || 0;
  9051. var y = viewport.y || 0;
  9052. this._cachedViewport = viewport;
  9053. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9054. };
  9055. /**
  9056. * Directly set the WebGL Viewport
  9057. * The x, y, width & height are directly passed to the WebGL call
  9058. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  9059. */
  9060. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9061. var currentViewport = this._cachedViewport;
  9062. this._cachedViewport = null;
  9063. this._gl.viewport(x, y, width, height);
  9064. return currentViewport;
  9065. };
  9066. Engine.prototype.beginFrame = function () {
  9067. this.onBeginFrameObservable.notifyObservers(this);
  9068. this._measureFps();
  9069. };
  9070. Engine.prototype.endFrame = function () {
  9071. //force a flush in case we are using a bad OS.
  9072. if (this._badOS) {
  9073. this.flushFramebuffer();
  9074. }
  9075. //submit frame to the vr device, if enabled
  9076. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9077. // TODO: We should only submit the frame if we read frameData successfully.
  9078. this._vrDisplay.submitFrame();
  9079. }
  9080. this.onEndFrameObservable.notifyObservers(this);
  9081. };
  9082. /**
  9083. * resize the view according to the canvas' size.
  9084. * @example
  9085. * window.addEventListener("resize", function () {
  9086. * engine.resize();
  9087. * });
  9088. */
  9089. Engine.prototype.resize = function () {
  9090. // We're not resizing the size of the canvas while in VR mode & presenting
  9091. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9092. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9093. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9094. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9095. }
  9096. };
  9097. /**
  9098. * force a specific size of the canvas
  9099. * @param {number} width - the new canvas' width
  9100. * @param {number} height - the new canvas' height
  9101. */
  9102. Engine.prototype.setSize = function (width, height) {
  9103. if (!this._renderingCanvas) {
  9104. return;
  9105. }
  9106. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9107. return;
  9108. }
  9109. this._renderingCanvas.width = width;
  9110. this._renderingCanvas.height = height;
  9111. for (var index = 0; index < this.scenes.length; index++) {
  9112. var scene = this.scenes[index];
  9113. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9114. var cam = scene.cameras[camIndex];
  9115. cam._currentRenderId = 0;
  9116. }
  9117. }
  9118. if (this.onResizeObservable.hasObservers) {
  9119. this.onResizeObservable.notifyObservers(this);
  9120. }
  9121. };
  9122. // WebVR functions
  9123. Engine.prototype.isVRDevicePresent = function () {
  9124. return !!this._vrDisplay;
  9125. };
  9126. Engine.prototype.getVRDevice = function () {
  9127. return this._vrDisplay;
  9128. };
  9129. Engine.prototype.initWebVR = function () {
  9130. var _this = this;
  9131. var notifyObservers = function () {
  9132. var eventArgs = {
  9133. vrDisplay: _this._vrDisplay,
  9134. vrSupported: _this._vrSupported
  9135. };
  9136. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9137. };
  9138. if (!this._onVrDisplayConnect) {
  9139. this._onVrDisplayConnect = function (event) {
  9140. _this._vrDisplay = event.display;
  9141. notifyObservers();
  9142. };
  9143. this._onVrDisplayDisconnect = function () {
  9144. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9145. _this._vrDisplay = undefined;
  9146. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9147. notifyObservers();
  9148. };
  9149. this._onVrDisplayPresentChange = function () {
  9150. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9151. };
  9152. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9153. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9154. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9155. }
  9156. this._getVRDisplays(notifyObservers);
  9157. return this.onVRDisplayChangedObservable;
  9158. };
  9159. Engine.prototype.enableVR = function () {
  9160. var _this = this;
  9161. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9162. var onResolved = function () {
  9163. _this.onVRRequestPresentComplete.notifyObservers(true);
  9164. _this._onVRFullScreenTriggered();
  9165. };
  9166. var onRejected = function () {
  9167. _this.onVRRequestPresentComplete.notifyObservers(false);
  9168. };
  9169. this.onVRRequestPresentStart.notifyObservers(this);
  9170. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9171. }
  9172. };
  9173. Engine.prototype.disableVR = function () {
  9174. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9175. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9176. }
  9177. };
  9178. Engine.prototype._getVRDisplays = function (callback) {
  9179. var _this = this;
  9180. var getWebVRDevices = function (devices) {
  9181. _this._vrSupported = true;
  9182. // note that devices may actually be an empty array. This is fine;
  9183. // we expect this._vrDisplay to be undefined in this case.
  9184. return _this._vrDisplay = devices[0];
  9185. };
  9186. if (navigator.getVRDisplays) {
  9187. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9188. // TODO: System CANNOT support WebVR, despite API presence.
  9189. _this._vrSupported = false;
  9190. callback();
  9191. });
  9192. }
  9193. else {
  9194. // TODO: Browser does not support WebVR
  9195. this._vrDisplay = undefined;
  9196. this._vrSupported = false;
  9197. callback();
  9198. }
  9199. };
  9200. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9201. if (this._currentRenderTarget) {
  9202. this.unBindFramebuffer(this._currentRenderTarget);
  9203. }
  9204. this._currentRenderTarget = texture;
  9205. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9206. var gl = this._gl;
  9207. if (texture.isCube) {
  9208. if (faceIndex === undefined) {
  9209. faceIndex = 0;
  9210. }
  9211. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9212. }
  9213. if (this._cachedViewport && !forceFullscreenViewport) {
  9214. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9215. }
  9216. else {
  9217. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9218. }
  9219. this.wipeCaches();
  9220. };
  9221. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9222. if (this._currentFramebuffer !== framebuffer) {
  9223. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9224. this._currentFramebuffer = framebuffer;
  9225. }
  9226. };
  9227. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9228. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9229. this._currentRenderTarget = null;
  9230. // If MSAA, we need to bitblt back to main texture
  9231. var gl = this._gl;
  9232. if (texture._MSAAFramebuffer) {
  9233. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9234. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9235. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9236. }
  9237. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9238. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9239. gl.generateMipmap(gl.TEXTURE_2D);
  9240. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9241. }
  9242. if (onBeforeUnbind) {
  9243. if (texture._MSAAFramebuffer) {
  9244. // Bind the correct framebuffer
  9245. this.bindUnboundFramebuffer(texture._framebuffer);
  9246. }
  9247. onBeforeUnbind();
  9248. }
  9249. this.bindUnboundFramebuffer(null);
  9250. };
  9251. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9252. if (texture.generateMipMaps) {
  9253. var gl = this._gl;
  9254. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9255. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9256. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9257. }
  9258. };
  9259. Engine.prototype.flushFramebuffer = function () {
  9260. this._gl.flush();
  9261. };
  9262. Engine.prototype.restoreDefaultFramebuffer = function () {
  9263. if (this._currentRenderTarget) {
  9264. this.unBindFramebuffer(this._currentRenderTarget);
  9265. }
  9266. else {
  9267. this.bindUnboundFramebuffer(null);
  9268. }
  9269. if (this._cachedViewport) {
  9270. this.setViewport(this._cachedViewport);
  9271. }
  9272. this.wipeCaches();
  9273. };
  9274. // UBOs
  9275. Engine.prototype.createUniformBuffer = function (elements) {
  9276. var ubo = this._gl.createBuffer();
  9277. if (!ubo) {
  9278. throw new Error("Unable to create uniform buffer");
  9279. }
  9280. this.bindUniformBuffer(ubo);
  9281. if (elements instanceof Float32Array) {
  9282. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9283. }
  9284. else {
  9285. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9286. }
  9287. this.bindUniformBuffer(null);
  9288. ubo.references = 1;
  9289. return ubo;
  9290. };
  9291. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9292. var ubo = this._gl.createBuffer();
  9293. if (!ubo) {
  9294. throw new Error("Unable to create dynamic uniform buffer");
  9295. }
  9296. this.bindUniformBuffer(ubo);
  9297. if (elements instanceof Float32Array) {
  9298. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9299. }
  9300. else {
  9301. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9302. }
  9303. this.bindUniformBuffer(null);
  9304. ubo.references = 1;
  9305. return ubo;
  9306. };
  9307. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9308. this.bindUniformBuffer(uniformBuffer);
  9309. if (offset === undefined) {
  9310. offset = 0;
  9311. }
  9312. if (count === undefined) {
  9313. if (elements instanceof Float32Array) {
  9314. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9315. }
  9316. else {
  9317. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9318. }
  9319. }
  9320. else {
  9321. if (elements instanceof Float32Array) {
  9322. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9323. }
  9324. else {
  9325. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9326. }
  9327. }
  9328. this.bindUniformBuffer(null);
  9329. };
  9330. // VBOs
  9331. Engine.prototype._resetVertexBufferBinding = function () {
  9332. this.bindArrayBuffer(null);
  9333. this._cachedVertexBuffers = null;
  9334. };
  9335. Engine.prototype.createVertexBuffer = function (vertices) {
  9336. var vbo = this._gl.createBuffer();
  9337. if (!vbo) {
  9338. throw new Error("Unable to create vertex buffer");
  9339. }
  9340. this.bindArrayBuffer(vbo);
  9341. if (vertices instanceof Float32Array) {
  9342. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9343. }
  9344. else {
  9345. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9346. }
  9347. this._resetVertexBufferBinding();
  9348. vbo.references = 1;
  9349. return vbo;
  9350. };
  9351. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9352. var vbo = this._gl.createBuffer();
  9353. if (!vbo) {
  9354. throw new Error("Unable to create dynamic vertex buffer");
  9355. }
  9356. this.bindArrayBuffer(vbo);
  9357. if (vertices instanceof Float32Array) {
  9358. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9359. }
  9360. else {
  9361. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9362. }
  9363. this._resetVertexBufferBinding();
  9364. vbo.references = 1;
  9365. return vbo;
  9366. };
  9367. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9368. if (offset === void 0) { offset = 0; }
  9369. // Force cache update
  9370. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9371. this.bindIndexBuffer(indexBuffer);
  9372. var arrayBuffer;
  9373. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9374. arrayBuffer = indices;
  9375. }
  9376. else {
  9377. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9378. }
  9379. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9380. this._resetIndexBufferBinding();
  9381. };
  9382. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9383. this.bindArrayBuffer(vertexBuffer);
  9384. if (offset === undefined) {
  9385. offset = 0;
  9386. }
  9387. if (count === undefined) {
  9388. if (vertices instanceof Float32Array) {
  9389. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9390. }
  9391. else {
  9392. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9393. }
  9394. }
  9395. else {
  9396. if (vertices instanceof Float32Array) {
  9397. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9398. }
  9399. else {
  9400. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9401. }
  9402. }
  9403. this._resetVertexBufferBinding();
  9404. };
  9405. Engine.prototype._resetIndexBufferBinding = function () {
  9406. this.bindIndexBuffer(null);
  9407. this._cachedIndexBuffer = null;
  9408. };
  9409. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9410. var vbo = this._gl.createBuffer();
  9411. if (!vbo) {
  9412. throw new Error("Unable to create index buffer");
  9413. }
  9414. this.bindIndexBuffer(vbo);
  9415. // Check for 32 bits indices
  9416. var arrayBuffer;
  9417. var need32Bits = false;
  9418. if (indices instanceof Uint16Array) {
  9419. arrayBuffer = indices;
  9420. }
  9421. else {
  9422. //check 32 bit support
  9423. if (this._caps.uintIndices) {
  9424. if (indices instanceof Uint32Array) {
  9425. arrayBuffer = indices;
  9426. need32Bits = true;
  9427. }
  9428. else {
  9429. //number[] or Int32Array, check if 32 bit is necessary
  9430. for (var index = 0; index < indices.length; index++) {
  9431. if (indices[index] > 65535) {
  9432. need32Bits = true;
  9433. break;
  9434. }
  9435. }
  9436. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9437. }
  9438. }
  9439. else {
  9440. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9441. arrayBuffer = new Uint16Array(indices);
  9442. }
  9443. }
  9444. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9445. this._resetIndexBufferBinding();
  9446. vbo.references = 1;
  9447. vbo.is32Bits = need32Bits;
  9448. return vbo;
  9449. };
  9450. Engine.prototype.bindArrayBuffer = function (buffer) {
  9451. if (!this._vaoRecordInProgress) {
  9452. this._unbindVertexArrayObject();
  9453. }
  9454. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9455. };
  9456. Engine.prototype.bindUniformBuffer = function (buffer) {
  9457. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9458. };
  9459. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9460. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9461. };
  9462. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9463. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9464. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9465. };
  9466. ;
  9467. Engine.prototype.bindIndexBuffer = function (buffer) {
  9468. if (!this._vaoRecordInProgress) {
  9469. this._unbindVertexArrayObject();
  9470. }
  9471. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9472. };
  9473. Engine.prototype.bindBuffer = function (buffer, target) {
  9474. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9475. this._gl.bindBuffer(target, buffer);
  9476. this._currentBoundBuffer[target] = buffer;
  9477. }
  9478. };
  9479. Engine.prototype.updateArrayBuffer = function (data) {
  9480. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9481. };
  9482. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9483. var pointer = this._currentBufferPointers[indx];
  9484. var changed = false;
  9485. if (!pointer.active) {
  9486. changed = true;
  9487. pointer.active = true;
  9488. pointer.index = indx;
  9489. pointer.size = size;
  9490. pointer.type = type;
  9491. pointer.normalized = normalized;
  9492. pointer.stride = stride;
  9493. pointer.offset = offset;
  9494. pointer.buffer = buffer;
  9495. }
  9496. else {
  9497. if (pointer.buffer !== buffer) {
  9498. pointer.buffer = buffer;
  9499. changed = true;
  9500. }
  9501. if (pointer.size !== size) {
  9502. pointer.size = size;
  9503. changed = true;
  9504. }
  9505. if (pointer.type !== type) {
  9506. pointer.type = type;
  9507. changed = true;
  9508. }
  9509. if (pointer.normalized !== normalized) {
  9510. pointer.normalized = normalized;
  9511. changed = true;
  9512. }
  9513. if (pointer.stride !== stride) {
  9514. pointer.stride = stride;
  9515. changed = true;
  9516. }
  9517. if (pointer.offset !== offset) {
  9518. pointer.offset = offset;
  9519. changed = true;
  9520. }
  9521. }
  9522. if (changed || this._vaoRecordInProgress) {
  9523. this.bindArrayBuffer(buffer);
  9524. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9525. }
  9526. };
  9527. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9528. if (indexBuffer == null) {
  9529. return;
  9530. }
  9531. if (this._cachedIndexBuffer !== indexBuffer) {
  9532. this._cachedIndexBuffer = indexBuffer;
  9533. this.bindIndexBuffer(indexBuffer);
  9534. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9535. }
  9536. };
  9537. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9538. var attributes = effect.getAttributesNames();
  9539. if (!this._vaoRecordInProgress) {
  9540. this._unbindVertexArrayObject();
  9541. }
  9542. this.unbindAllAttributes();
  9543. for (var index = 0; index < attributes.length; index++) {
  9544. var order = effect.getAttributeLocation(index);
  9545. if (order >= 0) {
  9546. var vertexBuffer = vertexBuffers[attributes[index]];
  9547. if (!vertexBuffer) {
  9548. continue;
  9549. }
  9550. this._gl.enableVertexAttribArray(order);
  9551. if (!this._vaoRecordInProgress) {
  9552. this._vertexAttribArraysEnabled[order] = true;
  9553. }
  9554. var buffer = vertexBuffer.getBuffer();
  9555. if (buffer) {
  9556. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9557. if (vertexBuffer.getIsInstanced()) {
  9558. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9559. if (!this._vaoRecordInProgress) {
  9560. this._currentInstanceLocations.push(order);
  9561. this._currentInstanceBuffers.push(buffer);
  9562. }
  9563. }
  9564. }
  9565. }
  9566. }
  9567. };
  9568. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9569. var vao = this._gl.createVertexArray();
  9570. this._vaoRecordInProgress = true;
  9571. this._gl.bindVertexArray(vao);
  9572. this._mustWipeVertexAttributes = true;
  9573. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9574. this.bindIndexBuffer(indexBuffer);
  9575. this._vaoRecordInProgress = false;
  9576. this._gl.bindVertexArray(null);
  9577. return vao;
  9578. };
  9579. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9580. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9581. this._cachedVertexArrayObject = vertexArrayObject;
  9582. this._gl.bindVertexArray(vertexArrayObject);
  9583. this._cachedVertexBuffers = null;
  9584. this._cachedIndexBuffer = null;
  9585. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9586. this._mustWipeVertexAttributes = true;
  9587. }
  9588. };
  9589. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9590. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9591. this._cachedVertexBuffers = vertexBuffer;
  9592. this._cachedEffectForVertexBuffers = effect;
  9593. var attributesCount = effect.getAttributesCount();
  9594. this._unbindVertexArrayObject();
  9595. this.unbindAllAttributes();
  9596. var offset = 0;
  9597. for (var index = 0; index < attributesCount; index++) {
  9598. if (index < vertexDeclaration.length) {
  9599. var order = effect.getAttributeLocation(index);
  9600. if (order >= 0) {
  9601. this._gl.enableVertexAttribArray(order);
  9602. this._vertexAttribArraysEnabled[order] = true;
  9603. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9604. }
  9605. offset += vertexDeclaration[index] * 4;
  9606. }
  9607. }
  9608. }
  9609. this._bindIndexBufferWithCache(indexBuffer);
  9610. };
  9611. Engine.prototype._unbindVertexArrayObject = function () {
  9612. if (!this._cachedVertexArrayObject) {
  9613. return;
  9614. }
  9615. this._cachedVertexArrayObject = null;
  9616. this._gl.bindVertexArray(null);
  9617. };
  9618. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9619. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9620. this._cachedVertexBuffers = vertexBuffers;
  9621. this._cachedEffectForVertexBuffers = effect;
  9622. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9623. }
  9624. this._bindIndexBufferWithCache(indexBuffer);
  9625. };
  9626. Engine.prototype.unbindInstanceAttributes = function () {
  9627. var boundBuffer;
  9628. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9629. var instancesBuffer = this._currentInstanceBuffers[i];
  9630. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9631. boundBuffer = instancesBuffer;
  9632. this.bindArrayBuffer(instancesBuffer);
  9633. }
  9634. var offsetLocation = this._currentInstanceLocations[i];
  9635. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9636. }
  9637. this._currentInstanceBuffers.length = 0;
  9638. this._currentInstanceLocations.length = 0;
  9639. };
  9640. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9641. this._gl.deleteVertexArray(vao);
  9642. };
  9643. Engine.prototype._releaseBuffer = function (buffer) {
  9644. buffer.references--;
  9645. if (buffer.references === 0) {
  9646. this._gl.deleteBuffer(buffer);
  9647. return true;
  9648. }
  9649. return false;
  9650. };
  9651. Engine.prototype.createInstancesBuffer = function (capacity) {
  9652. var buffer = this._gl.createBuffer();
  9653. if (!buffer) {
  9654. throw new Error("Unable to create instance buffer");
  9655. }
  9656. buffer.capacity = capacity;
  9657. this.bindArrayBuffer(buffer);
  9658. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9659. return buffer;
  9660. };
  9661. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9662. this._gl.deleteBuffer(buffer);
  9663. };
  9664. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9665. this.bindArrayBuffer(instancesBuffer);
  9666. if (data) {
  9667. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9668. }
  9669. if (offsetLocations[0].index !== undefined) {
  9670. var stride = 0;
  9671. for (var i = 0; i < offsetLocations.length; i++) {
  9672. var ai = offsetLocations[i];
  9673. stride += ai.attributeSize * 4;
  9674. }
  9675. for (var i = 0; i < offsetLocations.length; i++) {
  9676. var ai = offsetLocations[i];
  9677. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9678. this._gl.enableVertexAttribArray(ai.index);
  9679. this._vertexAttribArraysEnabled[ai.index] = true;
  9680. }
  9681. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9682. this._gl.vertexAttribDivisor(ai.index, 1);
  9683. this._currentInstanceLocations.push(ai.index);
  9684. this._currentInstanceBuffers.push(instancesBuffer);
  9685. }
  9686. }
  9687. else {
  9688. for (var index = 0; index < 4; index++) {
  9689. var offsetLocation = offsetLocations[index];
  9690. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9691. this._gl.enableVertexAttribArray(offsetLocation);
  9692. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9693. }
  9694. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9695. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9696. this._currentInstanceLocations.push(offsetLocation);
  9697. this._currentInstanceBuffers.push(instancesBuffer);
  9698. }
  9699. }
  9700. };
  9701. Engine.prototype.applyStates = function () {
  9702. this._depthCullingState.apply(this._gl);
  9703. this._stencilState.apply(this._gl);
  9704. this._alphaState.apply(this._gl);
  9705. };
  9706. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9707. // Apply states
  9708. this.applyStates();
  9709. this._drawCalls.addCount(1, false);
  9710. // Render
  9711. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9712. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9713. if (instancesCount) {
  9714. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9715. return;
  9716. }
  9717. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9718. };
  9719. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9720. // Apply states
  9721. this.applyStates();
  9722. this._drawCalls.addCount(1, false);
  9723. if (instancesCount) {
  9724. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9725. return;
  9726. }
  9727. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9728. };
  9729. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9730. // Apply states
  9731. this.applyStates();
  9732. this._drawCalls.addCount(1, false);
  9733. if (instancesCount) {
  9734. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9735. return;
  9736. }
  9737. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9738. };
  9739. // Shaders
  9740. Engine.prototype._releaseEffect = function (effect) {
  9741. if (this._compiledEffects[effect._key]) {
  9742. delete this._compiledEffects[effect._key];
  9743. this._deleteProgram(effect.getProgram());
  9744. }
  9745. };
  9746. Engine.prototype._deleteProgram = function (program) {
  9747. if (program) {
  9748. program.__SPECTOR_rebuildProgram = null;
  9749. if (program.transformFeedback) {
  9750. this.deleteTransformFeedback(program.transformFeedback);
  9751. program.transformFeedback = null;
  9752. }
  9753. this._gl.deleteProgram(program);
  9754. }
  9755. };
  9756. /**
  9757. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9758. * @param samplers An array of string used to represent textures
  9759. */
  9760. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9761. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9762. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9763. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9764. if (this._compiledEffects[name]) {
  9765. var compiledEffect = this._compiledEffects[name];
  9766. if (onCompiled && compiledEffect.isReady()) {
  9767. onCompiled(compiledEffect);
  9768. }
  9769. return compiledEffect;
  9770. }
  9771. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9772. effect._key = name;
  9773. this._compiledEffects[name] = effect;
  9774. return effect;
  9775. };
  9776. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9777. if (uniformsNames === void 0) { uniformsNames = []; }
  9778. if (samplers === void 0) { samplers = []; }
  9779. if (defines === void 0) { defines = ""; }
  9780. return this.createEffect({
  9781. vertex: "particles",
  9782. fragmentElement: fragmentName
  9783. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9784. };
  9785. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9786. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9787. context = context || this._gl;
  9788. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9789. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9790. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9791. };
  9792. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9793. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9794. context = context || this._gl;
  9795. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9796. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9797. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9798. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9799. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9800. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9801. return program;
  9802. };
  9803. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9804. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9805. var shaderProgram = context.createProgram();
  9806. if (!shaderProgram) {
  9807. throw new Error("Unable to create program");
  9808. }
  9809. context.attachShader(shaderProgram, vertexShader);
  9810. context.attachShader(shaderProgram, fragmentShader);
  9811. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9812. var transformFeedback = this.createTransformFeedback();
  9813. this.bindTransformFeedback(transformFeedback);
  9814. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9815. shaderProgram.transformFeedback = transformFeedback;
  9816. }
  9817. context.linkProgram(shaderProgram);
  9818. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9819. this.bindTransformFeedback(null);
  9820. }
  9821. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9822. if (!linked) {
  9823. context.validateProgram(shaderProgram);
  9824. var error = context.getProgramInfoLog(shaderProgram);
  9825. if (error) {
  9826. throw new Error(error);
  9827. }
  9828. }
  9829. context.deleteShader(vertexShader);
  9830. context.deleteShader(fragmentShader);
  9831. return shaderProgram;
  9832. };
  9833. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9834. var results = new Array();
  9835. for (var index = 0; index < uniformsNames.length; index++) {
  9836. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9837. }
  9838. return results;
  9839. };
  9840. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9841. var results = [];
  9842. for (var index = 0; index < attributesNames.length; index++) {
  9843. try {
  9844. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9845. }
  9846. catch (e) {
  9847. results.push(-1);
  9848. }
  9849. }
  9850. return results;
  9851. };
  9852. Engine.prototype.enableEffect = function (effect) {
  9853. if (!effect) {
  9854. return;
  9855. }
  9856. // Use program
  9857. this.setProgram(effect.getProgram());
  9858. this._currentEffect = effect;
  9859. if (effect.onBind) {
  9860. effect.onBind(effect);
  9861. }
  9862. effect.onBindObservable.notifyObservers(effect);
  9863. };
  9864. Engine.prototype.setIntArray = function (uniform, array) {
  9865. if (!uniform)
  9866. return;
  9867. this._gl.uniform1iv(uniform, array);
  9868. };
  9869. Engine.prototype.setIntArray2 = function (uniform, array) {
  9870. if (!uniform || array.length % 2 !== 0)
  9871. return;
  9872. this._gl.uniform2iv(uniform, array);
  9873. };
  9874. Engine.prototype.setIntArray3 = function (uniform, array) {
  9875. if (!uniform || array.length % 3 !== 0)
  9876. return;
  9877. this._gl.uniform3iv(uniform, array);
  9878. };
  9879. Engine.prototype.setIntArray4 = function (uniform, array) {
  9880. if (!uniform || array.length % 4 !== 0)
  9881. return;
  9882. this._gl.uniform4iv(uniform, array);
  9883. };
  9884. Engine.prototype.setFloatArray = function (uniform, array) {
  9885. if (!uniform)
  9886. return;
  9887. this._gl.uniform1fv(uniform, array);
  9888. };
  9889. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9890. if (!uniform || array.length % 2 !== 0)
  9891. return;
  9892. this._gl.uniform2fv(uniform, array);
  9893. };
  9894. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9895. if (!uniform || array.length % 3 !== 0)
  9896. return;
  9897. this._gl.uniform3fv(uniform, array);
  9898. };
  9899. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9900. if (!uniform || array.length % 4 !== 0)
  9901. return;
  9902. this._gl.uniform4fv(uniform, array);
  9903. };
  9904. Engine.prototype.setArray = function (uniform, array) {
  9905. if (!uniform)
  9906. return;
  9907. this._gl.uniform1fv(uniform, array);
  9908. };
  9909. Engine.prototype.setArray2 = function (uniform, array) {
  9910. if (!uniform || array.length % 2 !== 0)
  9911. return;
  9912. this._gl.uniform2fv(uniform, array);
  9913. };
  9914. Engine.prototype.setArray3 = function (uniform, array) {
  9915. if (!uniform || array.length % 3 !== 0)
  9916. return;
  9917. this._gl.uniform3fv(uniform, array);
  9918. };
  9919. Engine.prototype.setArray4 = function (uniform, array) {
  9920. if (!uniform || array.length % 4 !== 0)
  9921. return;
  9922. this._gl.uniform4fv(uniform, array);
  9923. };
  9924. Engine.prototype.setMatrices = function (uniform, matrices) {
  9925. if (!uniform)
  9926. return;
  9927. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9928. };
  9929. Engine.prototype.setMatrix = function (uniform, matrix) {
  9930. if (!uniform)
  9931. return;
  9932. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9933. };
  9934. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9935. if (!uniform)
  9936. return;
  9937. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9938. };
  9939. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9940. if (!uniform)
  9941. return;
  9942. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9943. };
  9944. Engine.prototype.setFloat = function (uniform, value) {
  9945. if (!uniform)
  9946. return;
  9947. this._gl.uniform1f(uniform, value);
  9948. };
  9949. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9950. if (!uniform)
  9951. return;
  9952. this._gl.uniform2f(uniform, x, y);
  9953. };
  9954. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9955. if (!uniform)
  9956. return;
  9957. this._gl.uniform3f(uniform, x, y, z);
  9958. };
  9959. Engine.prototype.setBool = function (uniform, bool) {
  9960. if (!uniform)
  9961. return;
  9962. this._gl.uniform1i(uniform, bool);
  9963. };
  9964. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9965. if (!uniform)
  9966. return;
  9967. this._gl.uniform4f(uniform, x, y, z, w);
  9968. };
  9969. Engine.prototype.setColor3 = function (uniform, color3) {
  9970. if (!uniform)
  9971. return;
  9972. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9973. };
  9974. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9975. if (!uniform)
  9976. return;
  9977. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9978. };
  9979. // States
  9980. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9981. if (zOffset === void 0) { zOffset = 0; }
  9982. if (reverseSide === void 0) { reverseSide = false; }
  9983. // Culling
  9984. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9985. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9986. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9987. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9988. if (culling) {
  9989. this._depthCullingState.cullFace = cullFace;
  9990. this._depthCullingState.cull = true;
  9991. }
  9992. else {
  9993. this._depthCullingState.cull = false;
  9994. }
  9995. }
  9996. // Z offset
  9997. this.setZOffset(zOffset);
  9998. };
  9999. Engine.prototype.setZOffset = function (value) {
  10000. this._depthCullingState.zOffset = value;
  10001. };
  10002. Engine.prototype.getZOffset = function () {
  10003. return this._depthCullingState.zOffset;
  10004. };
  10005. Engine.prototype.setDepthBuffer = function (enable) {
  10006. this._depthCullingState.depthTest = enable;
  10007. };
  10008. Engine.prototype.getDepthWrite = function () {
  10009. return this._depthCullingState.depthMask;
  10010. };
  10011. Engine.prototype.setDepthWrite = function (enable) {
  10012. this._depthCullingState.depthMask = enable;
  10013. };
  10014. Engine.prototype.setColorWrite = function (enable) {
  10015. this._gl.colorMask(enable, enable, enable, enable);
  10016. this._colorWrite = enable;
  10017. };
  10018. Engine.prototype.getColorWrite = function () {
  10019. return this._colorWrite;
  10020. };
  10021. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10022. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10023. };
  10024. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10025. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10026. if (this._alphaMode === mode) {
  10027. return;
  10028. }
  10029. switch (mode) {
  10030. case Engine.ALPHA_DISABLE:
  10031. this._alphaState.alphaBlend = false;
  10032. break;
  10033. case Engine.ALPHA_PREMULTIPLIED:
  10034. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10035. this._alphaState.alphaBlend = true;
  10036. break;
  10037. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10038. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10039. this._alphaState.alphaBlend = true;
  10040. break;
  10041. case Engine.ALPHA_COMBINE:
  10042. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10043. this._alphaState.alphaBlend = true;
  10044. break;
  10045. case Engine.ALPHA_ONEONE:
  10046. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10047. this._alphaState.alphaBlend = true;
  10048. break;
  10049. case Engine.ALPHA_ADD:
  10050. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10051. this._alphaState.alphaBlend = true;
  10052. break;
  10053. case Engine.ALPHA_SUBTRACT:
  10054. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10055. this._alphaState.alphaBlend = true;
  10056. break;
  10057. case Engine.ALPHA_MULTIPLY:
  10058. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10059. this._alphaState.alphaBlend = true;
  10060. break;
  10061. case Engine.ALPHA_MAXIMIZED:
  10062. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10063. this._alphaState.alphaBlend = true;
  10064. break;
  10065. case Engine.ALPHA_INTERPOLATE:
  10066. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10067. this._alphaState.alphaBlend = true;
  10068. break;
  10069. case Engine.ALPHA_SCREENMODE:
  10070. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10071. this._alphaState.alphaBlend = true;
  10072. break;
  10073. }
  10074. if (!noDepthWriteChange) {
  10075. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10076. }
  10077. this._alphaMode = mode;
  10078. };
  10079. Engine.prototype.getAlphaMode = function () {
  10080. return this._alphaMode;
  10081. };
  10082. Engine.prototype.setAlphaTesting = function (enable) {
  10083. this._alphaTest = enable;
  10084. };
  10085. Engine.prototype.getAlphaTesting = function () {
  10086. return !!this._alphaTest;
  10087. };
  10088. // Textures
  10089. Engine.prototype.wipeCaches = function (bruteForce) {
  10090. if (this.preventCacheWipeBetweenFrames) {
  10091. return;
  10092. }
  10093. this.resetTextureCache();
  10094. this._currentEffect = null;
  10095. // 6/8/2017: deltakosh: Should not be required anymore.
  10096. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10097. if (bruteForce) {
  10098. this._currentProgram = null;
  10099. this._stencilState.reset();
  10100. this._depthCullingState.reset();
  10101. this.setDepthFunctionToLessOrEqual();
  10102. this._alphaState.reset();
  10103. }
  10104. this._cachedVertexBuffers = null;
  10105. this._cachedIndexBuffer = null;
  10106. this._cachedEffectForVertexBuffers = null;
  10107. this._unbindVertexArrayObject();
  10108. this.bindIndexBuffer(null);
  10109. this.bindArrayBuffer(null);
  10110. };
  10111. /**
  10112. * Set the compressed texture format to use, based on the formats you have, and the formats
  10113. * supported by the hardware / browser.
  10114. *
  10115. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10116. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10117. * to API arguments needed to compressed textures. This puts the burden on the container
  10118. * generator to house the arcane code for determining these for current & future formats.
  10119. *
  10120. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10121. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10122. *
  10123. * Note: The result of this call is not taken into account when a texture is base64.
  10124. *
  10125. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10126. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10127. *
  10128. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10129. * @returns The extension selected.
  10130. */
  10131. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10132. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10133. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10134. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10135. return this._textureFormatInUse = this._texturesSupported[i];
  10136. }
  10137. }
  10138. }
  10139. // actively set format to nothing, to allow this to be called more than once
  10140. // and possibly fail the 2nd time
  10141. this._textureFormatInUse = null;
  10142. return null;
  10143. };
  10144. Engine.prototype._createTexture = function () {
  10145. var texture = this._gl.createTexture();
  10146. if (!texture) {
  10147. throw new Error("Unable to create texture");
  10148. }
  10149. return texture;
  10150. };
  10151. /**
  10152. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10153. * @param {string} urlArg- This contains one of the following:
  10154. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10155. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10156. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10157. *
  10158. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10159. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10160. * @param {Scene} scene- Needed for loading to the correct scene.
  10161. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10162. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10163. * @param {callback} onError- Optional callback to be called upon failure.
  10164. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10165. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10166. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10167. *
  10168. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10169. */
  10170. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10171. var _this = this;
  10172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10173. if (onLoad === void 0) { onLoad = null; }
  10174. if (onError === void 0) { onError = null; }
  10175. if (buffer === void 0) { buffer = null; }
  10176. if (fallBack === void 0) { fallBack = null; }
  10177. if (format === void 0) { format = null; }
  10178. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10179. var fromData = url.substr(0, 5) === "data:";
  10180. var fromBlob = url.substr(0, 5) === "blob:";
  10181. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10182. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10183. // establish the file extension, if possible
  10184. var lastDot = url.lastIndexOf('.');
  10185. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10186. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10187. var isTGA = (extension === ".tga");
  10188. // determine if a ktx file should be substituted
  10189. var isKTX = false;
  10190. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10191. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10192. isKTX = true;
  10193. }
  10194. if (scene) {
  10195. scene._addPendingData(texture);
  10196. }
  10197. texture.url = url;
  10198. texture.generateMipMaps = !noMipmap;
  10199. texture.samplingMode = samplingMode;
  10200. texture.invertY = invertY;
  10201. if (!this._doNotHandleContextLost) {
  10202. // Keep a link to the buffer only if we plan to handle context lost
  10203. texture._buffer = buffer;
  10204. }
  10205. if (onLoad) {
  10206. texture.onLoadedObservable.add(onLoad);
  10207. }
  10208. if (!fallBack)
  10209. this._internalTexturesCache.push(texture);
  10210. var onerror = function () {
  10211. if (scene) {
  10212. scene._removePendingData(texture);
  10213. }
  10214. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10215. if (isKTX) {
  10216. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10217. }
  10218. else if ((isTGA || isDDS) && BABYLON.Tools.UseFallbackTexture) {
  10219. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10220. }
  10221. else if (onError) {
  10222. onError();
  10223. }
  10224. };
  10225. var callback = null;
  10226. // processing for non-image formats
  10227. if (isKTX || isTGA || isDDS) {
  10228. if (isKTX) {
  10229. callback = function (data) {
  10230. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10231. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10232. ktx.uploadLevels(_this._gl, !noMipmap);
  10233. return false;
  10234. }, samplingMode);
  10235. };
  10236. }
  10237. else if (isTGA) {
  10238. callback = function (arrayBuffer) {
  10239. var data = new Uint8Array(arrayBuffer);
  10240. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10241. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10242. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10243. return false;
  10244. }, samplingMode);
  10245. };
  10246. }
  10247. else if (isDDS) {
  10248. callback = function (data) {
  10249. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10250. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10251. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10252. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10253. return false;
  10254. }, samplingMode);
  10255. };
  10256. }
  10257. if (!buffer) {
  10258. BABYLON.Tools.LoadFile(url, function (data) {
  10259. if (callback) {
  10260. callback(data);
  10261. }
  10262. }, undefined, scene ? scene.database : undefined, true, onerror);
  10263. }
  10264. else {
  10265. if (callback) {
  10266. callback(buffer);
  10267. }
  10268. }
  10269. // image format processing
  10270. }
  10271. else {
  10272. var onload = function (img) {
  10273. if (fromBlob && !_this._doNotHandleContextLost) {
  10274. // We need to store the image if we need to rebuild the texture
  10275. // in case of a webgl context lost
  10276. texture._buffer = img;
  10277. }
  10278. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10279. var gl = _this._gl;
  10280. var isPot = (img.width === potWidth && img.height === potHeight);
  10281. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10282. if (isPot) {
  10283. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10284. return false;
  10285. }
  10286. // Using shaders to rescale because canvas.drawImage is lossy
  10287. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10288. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10289. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10291. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10292. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10293. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10294. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10295. _this._releaseTexture(source);
  10296. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10297. continuationCallback();
  10298. });
  10299. return true;
  10300. }, samplingMode);
  10301. };
  10302. if (!fromData || isBase64)
  10303. if (buffer instanceof HTMLImageElement) {
  10304. onload(buffer);
  10305. }
  10306. else {
  10307. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10308. }
  10309. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10310. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10311. else
  10312. onload(buffer);
  10313. }
  10314. return texture;
  10315. };
  10316. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10317. var _this = this;
  10318. var rtt = this.createRenderTargetTexture({
  10319. width: destination.width,
  10320. height: destination.height,
  10321. }, {
  10322. generateMipMaps: false,
  10323. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10324. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10325. generateDepthBuffer: false,
  10326. generateStencilBuffer: false
  10327. });
  10328. if (!this._rescalePostProcess) {
  10329. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10330. }
  10331. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10332. _this._rescalePostProcess.onApply = function (effect) {
  10333. effect._bindTexture("textureSampler", source);
  10334. };
  10335. var hostingScene = scene;
  10336. if (!hostingScene) {
  10337. hostingScene = _this.scenes[_this.scenes.length - 1];
  10338. }
  10339. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10340. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10341. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10342. _this.unBindFramebuffer(rtt);
  10343. _this._releaseTexture(rtt);
  10344. if (onComplete) {
  10345. onComplete();
  10346. }
  10347. });
  10348. };
  10349. Engine.prototype._getInternalFormat = function (format) {
  10350. var internalFormat = this._gl.RGBA;
  10351. switch (format) {
  10352. case Engine.TEXTUREFORMAT_ALPHA:
  10353. internalFormat = this._gl.ALPHA;
  10354. break;
  10355. case Engine.TEXTUREFORMAT_LUMINANCE:
  10356. internalFormat = this._gl.LUMINANCE;
  10357. break;
  10358. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10359. internalFormat = this._gl.LUMINANCE_ALPHA;
  10360. break;
  10361. case Engine.TEXTUREFORMAT_RGB:
  10362. internalFormat = this._gl.RGB;
  10363. break;
  10364. case Engine.TEXTUREFORMAT_RGBA:
  10365. internalFormat = this._gl.RGBA;
  10366. break;
  10367. }
  10368. return internalFormat;
  10369. };
  10370. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10371. if (compression === void 0) { compression = null; }
  10372. if (!texture) {
  10373. return;
  10374. }
  10375. var internalFormat = this._getInternalFormat(format);
  10376. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10377. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10378. if (!this._doNotHandleContextLost) {
  10379. texture._bufferView = data;
  10380. texture.format = format;
  10381. texture.invertY = invertY;
  10382. texture._compression = compression;
  10383. }
  10384. if (texture.width % 4 !== 0) {
  10385. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10386. }
  10387. if (compression && data) {
  10388. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10389. }
  10390. else {
  10391. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10392. }
  10393. if (texture.generateMipMaps) {
  10394. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10395. }
  10396. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10397. this.resetTextureCache();
  10398. texture.isReady = true;
  10399. };
  10400. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10401. if (compression === void 0) { compression = null; }
  10402. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10403. texture.baseWidth = width;
  10404. texture.baseHeight = height;
  10405. texture.width = width;
  10406. texture.height = height;
  10407. texture.format = format;
  10408. texture.generateMipMaps = generateMipMaps;
  10409. texture.samplingMode = samplingMode;
  10410. texture.invertY = invertY;
  10411. texture._compression = compression;
  10412. if (!this._doNotHandleContextLost) {
  10413. texture._bufferView = data;
  10414. }
  10415. this.updateRawTexture(texture, data, format, invertY, compression);
  10416. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10417. // Filters
  10418. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10419. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10420. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10421. if (generateMipMaps) {
  10422. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10423. }
  10424. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10425. this._internalTexturesCache.push(texture);
  10426. return texture;
  10427. };
  10428. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10429. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10430. texture.baseWidth = width;
  10431. texture.baseHeight = height;
  10432. if (generateMipMaps) {
  10433. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10434. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10435. }
  10436. this.resetTextureCache();
  10437. texture.width = width;
  10438. texture.height = height;
  10439. texture.isReady = false;
  10440. texture.generateMipMaps = generateMipMaps;
  10441. texture.samplingMode = samplingMode;
  10442. this.updateTextureSamplingMode(samplingMode, texture);
  10443. this._internalTexturesCache.push(texture);
  10444. return texture;
  10445. };
  10446. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10447. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10448. if (texture.isCube) {
  10449. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10450. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10451. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10452. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10453. }
  10454. else if (texture.is3D) {
  10455. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10456. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10457. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10458. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10459. }
  10460. else {
  10461. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10462. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10463. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10464. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10465. }
  10466. texture.samplingMode = samplingMode;
  10467. };
  10468. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10469. if (premulAlpha === void 0) { premulAlpha = false; }
  10470. if (!texture) {
  10471. return;
  10472. }
  10473. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10474. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10475. if (premulAlpha) {
  10476. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10477. }
  10478. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10479. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10480. if (texture.generateMipMaps) {
  10481. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10482. }
  10483. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10484. if (premulAlpha) {
  10485. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10486. }
  10487. this.resetTextureCache();
  10488. texture.isReady = true;
  10489. };
  10490. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10491. if (!texture || texture._isDisabled) {
  10492. return;
  10493. }
  10494. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10495. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10496. try {
  10497. // Testing video texture support
  10498. if (this._videoTextureSupported === undefined) {
  10499. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10500. if (this._gl.getError() !== 0) {
  10501. this._videoTextureSupported = false;
  10502. }
  10503. else {
  10504. this._videoTextureSupported = true;
  10505. }
  10506. }
  10507. // Copy video through the current working canvas if video texture is not supported
  10508. if (!this._videoTextureSupported) {
  10509. if (!texture._workingCanvas) {
  10510. texture._workingCanvas = document.createElement("canvas");
  10511. var context = texture._workingCanvas.getContext("2d");
  10512. if (!context) {
  10513. throw new Error("Unable to get 2d context");
  10514. }
  10515. texture._workingContext = context;
  10516. texture._workingCanvas.width = texture.width;
  10517. texture._workingCanvas.height = texture.height;
  10518. }
  10519. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10520. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10521. }
  10522. else {
  10523. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10524. }
  10525. if (texture.generateMipMaps) {
  10526. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10527. }
  10528. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10529. this.resetTextureCache();
  10530. texture.isReady = true;
  10531. }
  10532. catch (ex) {
  10533. // Something unexpected
  10534. // Let's disable the texture
  10535. texture._isDisabled = true;
  10536. }
  10537. };
  10538. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10539. var fullOptions = new RenderTargetCreationOptions();
  10540. if (options !== undefined && typeof options === "object") {
  10541. fullOptions.generateMipMaps = options.generateMipMaps;
  10542. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10543. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10544. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10545. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10546. }
  10547. else {
  10548. fullOptions.generateMipMaps = options;
  10549. fullOptions.generateDepthBuffer = true;
  10550. fullOptions.generateStencilBuffer = false;
  10551. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10552. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10553. }
  10554. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10555. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10556. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10557. }
  10558. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10559. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10560. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10561. }
  10562. var gl = this._gl;
  10563. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10564. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10565. var width = size.width || size;
  10566. var height = size.height || size;
  10567. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10568. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10569. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10570. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10571. }
  10572. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10573. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10576. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10577. // Create the framebuffer
  10578. var framebuffer = gl.createFramebuffer();
  10579. this.bindUnboundFramebuffer(framebuffer);
  10580. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10581. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10582. if (fullOptions.generateMipMaps) {
  10583. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10584. }
  10585. // Unbind
  10586. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10587. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10588. this.bindUnboundFramebuffer(null);
  10589. texture._framebuffer = framebuffer;
  10590. texture.baseWidth = width;
  10591. texture.baseHeight = height;
  10592. texture.width = width;
  10593. texture.height = height;
  10594. texture.isReady = true;
  10595. texture.samples = 1;
  10596. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10597. texture.samplingMode = fullOptions.samplingMode;
  10598. texture.type = fullOptions.type;
  10599. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10600. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10601. this.resetTextureCache();
  10602. this._internalTexturesCache.push(texture);
  10603. return texture;
  10604. };
  10605. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10606. var generateMipMaps = false;
  10607. var generateDepthBuffer = true;
  10608. var generateStencilBuffer = false;
  10609. var generateDepthTexture = false;
  10610. var textureCount = 1;
  10611. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10612. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10613. var types = [], samplingModes = [];
  10614. if (options !== undefined) {
  10615. generateMipMaps = options.generateMipMaps;
  10616. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10617. generateStencilBuffer = options.generateStencilBuffer;
  10618. generateDepthTexture = options.generateDepthTexture;
  10619. textureCount = options.textureCount || 1;
  10620. if (options.types) {
  10621. types = options.types;
  10622. }
  10623. if (options.samplingModes) {
  10624. samplingModes = options.samplingModes;
  10625. }
  10626. }
  10627. var gl = this._gl;
  10628. // Create the framebuffer
  10629. var framebuffer = gl.createFramebuffer();
  10630. this.bindUnboundFramebuffer(framebuffer);
  10631. var width = size.width || size;
  10632. var height = size.height || size;
  10633. var textures = [];
  10634. var attachments = [];
  10635. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10636. for (var i = 0; i < textureCount; i++) {
  10637. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10638. var type = types[i] || defaultType;
  10639. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10640. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10641. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10642. }
  10643. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10644. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10645. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10646. }
  10647. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10648. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10649. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10650. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10651. }
  10652. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10653. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10654. textures.push(texture);
  10655. attachments.push(attachment);
  10656. gl.activeTexture(gl["TEXTURE" + i]);
  10657. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10658. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10659. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10660. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10661. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10662. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10663. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10664. if (generateMipMaps) {
  10665. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10666. }
  10667. // Unbind
  10668. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10669. texture._framebuffer = framebuffer;
  10670. texture._depthStencilBuffer = depthStencilBuffer;
  10671. texture.baseWidth = width;
  10672. texture.baseHeight = height;
  10673. texture.width = width;
  10674. texture.height = height;
  10675. texture.isReady = true;
  10676. texture.samples = 1;
  10677. texture.generateMipMaps = generateMipMaps;
  10678. texture.samplingMode = samplingMode;
  10679. texture.type = type;
  10680. texture._generateDepthBuffer = generateDepthBuffer;
  10681. texture._generateStencilBuffer = generateStencilBuffer;
  10682. this._internalTexturesCache.push(texture);
  10683. }
  10684. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10685. // Depth texture
  10686. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10687. gl.activeTexture(gl.TEXTURE0);
  10688. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10691. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10693. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10694. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10695. depthTexture._framebuffer = framebuffer;
  10696. depthTexture.baseWidth = width;
  10697. depthTexture.baseHeight = height;
  10698. depthTexture.width = width;
  10699. depthTexture.height = height;
  10700. depthTexture.isReady = true;
  10701. depthTexture.samples = 1;
  10702. depthTexture.generateMipMaps = generateMipMaps;
  10703. depthTexture.samplingMode = gl.NEAREST;
  10704. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10705. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10706. textures.push(depthTexture);
  10707. this._internalTexturesCache.push(depthTexture);
  10708. }
  10709. gl.drawBuffers(attachments);
  10710. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10711. this.bindUnboundFramebuffer(null);
  10712. this.resetTextureCache();
  10713. return textures;
  10714. };
  10715. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10716. if (samples === void 0) { samples = 1; }
  10717. var depthStencilBuffer = null;
  10718. var gl = this._gl;
  10719. // Create the depth/stencil buffer
  10720. if (generateStencilBuffer) {
  10721. depthStencilBuffer = gl.createRenderbuffer();
  10722. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10723. if (samples > 1) {
  10724. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10725. }
  10726. else {
  10727. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10728. }
  10729. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10730. }
  10731. else if (generateDepthBuffer) {
  10732. depthStencilBuffer = gl.createRenderbuffer();
  10733. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10734. if (samples > 1) {
  10735. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10736. }
  10737. else {
  10738. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10739. }
  10740. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10741. }
  10742. return depthStencilBuffer;
  10743. };
  10744. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10745. if (this.webGLVersion < 2 || !texture) {
  10746. return 1;
  10747. }
  10748. if (texture.samples === samples) {
  10749. return samples;
  10750. }
  10751. var gl = this._gl;
  10752. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10753. // Dispose previous render buffers
  10754. if (texture._depthStencilBuffer) {
  10755. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10756. }
  10757. if (texture._MSAAFramebuffer) {
  10758. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10759. }
  10760. if (texture._MSAARenderBuffer) {
  10761. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10762. }
  10763. if (samples > 1) {
  10764. var framebuffer = gl.createFramebuffer();
  10765. if (!framebuffer) {
  10766. throw new Error("Unable to create multi sampled framebuffer");
  10767. }
  10768. texture._MSAAFramebuffer = framebuffer;
  10769. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10770. var colorRenderbuffer = gl.createRenderbuffer();
  10771. if (!colorRenderbuffer) {
  10772. throw new Error("Unable to create multi sampled framebuffer");
  10773. }
  10774. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10775. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10776. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10777. texture._MSAARenderBuffer = colorRenderbuffer;
  10778. }
  10779. else {
  10780. this.bindUnboundFramebuffer(texture._framebuffer);
  10781. }
  10782. texture.samples = samples;
  10783. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10784. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10785. this.bindUnboundFramebuffer(null);
  10786. return samples;
  10787. };
  10788. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10789. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10790. };
  10791. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10792. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10793. };
  10794. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10795. var gl = this._gl;
  10796. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10797. var generateMipMaps = true;
  10798. var generateDepthBuffer = true;
  10799. var generateStencilBuffer = false;
  10800. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10801. if (options !== undefined) {
  10802. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10803. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10804. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10805. if (options.samplingMode !== undefined) {
  10806. samplingMode = options.samplingMode;
  10807. }
  10808. }
  10809. texture.isCube = true;
  10810. texture.generateMipMaps = generateMipMaps;
  10811. texture.samples = 1;
  10812. texture.samplingMode = samplingMode;
  10813. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10814. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10815. for (var face = 0; face < 6; face++) {
  10816. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10817. }
  10818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10822. // Create the framebuffer
  10823. var framebuffer = gl.createFramebuffer();
  10824. this.bindUnboundFramebuffer(framebuffer);
  10825. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10826. // Mipmaps
  10827. if (texture.generateMipMaps) {
  10828. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10829. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10830. }
  10831. // Unbind
  10832. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10833. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10834. this.bindUnboundFramebuffer(null);
  10835. texture._framebuffer = framebuffer;
  10836. texture.width = size;
  10837. texture.height = size;
  10838. texture.isReady = true;
  10839. this.resetTextureCache();
  10840. this._internalTexturesCache.push(texture);
  10841. return texture;
  10842. };
  10843. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10844. var _this = this;
  10845. if (onLoad === void 0) { onLoad = null; }
  10846. if (onError === void 0) { onError = null; }
  10847. if (forcedExtension === void 0) { forcedExtension = null; }
  10848. var callback = function (loadData) {
  10849. if (!loadData) {
  10850. if (onLoad) {
  10851. onLoad(null);
  10852. }
  10853. return;
  10854. }
  10855. var texture = loadData.texture;
  10856. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10857. texture._lodGenerationScale = scale;
  10858. texture._lodGenerationOffset = offset;
  10859. if (_this._caps.textureLOD) {
  10860. // Do not add extra process if texture lod is supported.
  10861. if (onLoad) {
  10862. onLoad(texture);
  10863. }
  10864. return;
  10865. }
  10866. var mipSlices = 3;
  10867. var gl = _this._gl;
  10868. var width = loadData.width;
  10869. if (!width) {
  10870. return;
  10871. }
  10872. var textures = [];
  10873. for (var i = 0; i < mipSlices; i++) {
  10874. //compute LOD from even spacing in smoothness (matching shader calculation)
  10875. var smoothness = i / (mipSlices - 1);
  10876. var roughness = 1 - smoothness;
  10877. var minLODIndex = offset; // roughness = 0
  10878. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10879. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10880. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10881. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10882. glTextureFromLod.isCube = true;
  10883. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10887. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10888. if (loadData.isDDS) {
  10889. var info = loadData.info;
  10890. var data = loadData.data;
  10891. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10892. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10893. }
  10894. else {
  10895. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10896. }
  10897. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10898. // Wrap in a base texture for easy binding.
  10899. var lodTexture = new BABYLON.BaseTexture(scene);
  10900. lodTexture.isCube = true;
  10901. lodTexture._texture = glTextureFromLod;
  10902. glTextureFromLod.isReady = true;
  10903. textures.push(lodTexture);
  10904. }
  10905. texture._lodTextureHigh = textures[2];
  10906. texture._lodTextureMid = textures[1];
  10907. texture._lodTextureLow = textures[0];
  10908. if (onLoad) {
  10909. onLoad(texture);
  10910. }
  10911. };
  10912. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10913. };
  10914. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10915. var _this = this;
  10916. if (onLoad === void 0) { onLoad = null; }
  10917. if (onError === void 0) { onError = null; }
  10918. if (forcedExtension === void 0) { forcedExtension = null; }
  10919. var gl = this._gl;
  10920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10921. texture.isCube = true;
  10922. texture.url = rootUrl;
  10923. texture.generateMipMaps = !noMipmap;
  10924. if (!this._doNotHandleContextLost) {
  10925. texture._extension = forcedExtension;
  10926. texture._files = files;
  10927. }
  10928. var isKTX = false;
  10929. var isDDS = false;
  10930. var lastDot = rootUrl.lastIndexOf('.');
  10931. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10932. if (this._textureFormatInUse) {
  10933. extension = this._textureFormatInUse;
  10934. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10935. isKTX = true;
  10936. }
  10937. else {
  10938. isDDS = (extension === ".dds");
  10939. }
  10940. var onerror = function (request, exception) {
  10941. if (onError) {
  10942. onError(request.status + " " + request.statusText, exception);
  10943. }
  10944. };
  10945. if (isKTX) {
  10946. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10947. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10948. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10949. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10950. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10951. ktx.uploadLevels(_this._gl, !noMipmap);
  10952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10956. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10957. _this.resetTextureCache();
  10958. texture.width = ktx.pixelWidth;
  10959. texture.height = ktx.pixelHeight;
  10960. texture.isReady = true;
  10961. }, undefined, undefined, true, onerror);
  10962. }
  10963. else if (isDDS) {
  10964. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10965. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10966. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10967. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10968. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10969. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10970. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10971. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10972. }
  10973. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10975. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10976. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10977. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10978. _this.resetTextureCache();
  10979. texture.width = info.width;
  10980. texture.height = info.height;
  10981. texture.isReady = true;
  10982. texture.type = info.textureType;
  10983. if (onLoad) {
  10984. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10985. }
  10986. }, undefined, undefined, true, onerror);
  10987. }
  10988. else {
  10989. if (!files) {
  10990. throw new Error("Cannot load cubemap because files were not defined");
  10991. }
  10992. cascadeLoad(rootUrl, scene, function (imgs) {
  10993. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10994. var height = width;
  10995. _this._prepareWorkingCanvas();
  10996. if (!_this._workingCanvas || !_this._workingContext) {
  10997. return;
  10998. }
  10999. _this._workingCanvas.width = width;
  11000. _this._workingCanvas.height = height;
  11001. var faces = [
  11002. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11003. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11004. ];
  11005. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11006. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11007. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11008. for (var index = 0; index < faces.length; index++) {
  11009. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11010. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11011. }
  11012. if (!noMipmap) {
  11013. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11014. }
  11015. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  11017. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11018. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11019. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11020. _this.resetTextureCache();
  11021. texture.width = width;
  11022. texture.height = height;
  11023. texture.isReady = true;
  11024. if (format) {
  11025. texture.format = format;
  11026. }
  11027. texture.onLoadedObservable.notifyObservers(texture);
  11028. texture.onLoadedObservable.clear();
  11029. if (onLoad) {
  11030. onLoad();
  11031. }
  11032. }, files, onError);
  11033. }
  11034. this._internalTexturesCache.push(texture);
  11035. return texture;
  11036. };
  11037. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11038. if (compression === void 0) { compression = null; }
  11039. if (level === void 0) { level = 0; }
  11040. texture._bufferViewArray = data;
  11041. texture.format = format;
  11042. texture.type = type;
  11043. texture.invertY = invertY;
  11044. texture._compression = compression;
  11045. var gl = this._gl;
  11046. var textureType = this._getWebGLTextureType(type);
  11047. var internalFormat = this._getInternalFormat(format);
  11048. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11049. var needConversion = false;
  11050. if (internalFormat === gl.RGB) {
  11051. internalFormat = gl.RGBA;
  11052. needConversion = true;
  11053. }
  11054. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11055. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11056. if (texture.width % 4 !== 0) {
  11057. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11058. }
  11059. // Data are known to be in +X +Y +Z -X -Y -Z
  11060. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11061. var faceData = data[faceIndex];
  11062. if (compression) {
  11063. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11064. }
  11065. else {
  11066. if (needConversion) {
  11067. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11068. }
  11069. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11070. }
  11071. }
  11072. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11073. if (isPot && texture.generateMipMaps && level === 0) {
  11074. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11075. }
  11076. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11077. this.resetTextureCache();
  11078. texture.isReady = true;
  11079. };
  11080. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11081. if (compression === void 0) { compression = null; }
  11082. var gl = this._gl;
  11083. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11084. texture.isCube = true;
  11085. texture.generateMipMaps = generateMipMaps;
  11086. texture.format = format;
  11087. texture.type = type;
  11088. if (!this._doNotHandleContextLost) {
  11089. texture._bufferViewArray = data;
  11090. }
  11091. var textureType = this._getWebGLTextureType(type);
  11092. var internalFormat = this._getInternalFormat(format);
  11093. var needConversion = false;
  11094. if (internalFormat === gl.RGB) {
  11095. internalFormat = gl.RGBA;
  11096. needConversion = true;
  11097. }
  11098. var width = size;
  11099. var height = width;
  11100. texture.width = width;
  11101. texture.height = height;
  11102. // Double check on POT to generate Mips.
  11103. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11104. if (!isPot) {
  11105. generateMipMaps = false;
  11106. }
  11107. // Upload data if needed. The texture won't be ready until then.
  11108. if (data) {
  11109. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11110. }
  11111. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11112. // Filters
  11113. if (data && generateMipMaps) {
  11114. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11115. }
  11116. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11117. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11118. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11119. }
  11120. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11123. }
  11124. else {
  11125. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11128. }
  11129. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11131. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11132. return texture;
  11133. };
  11134. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11135. var _this = this;
  11136. if (onLoad === void 0) { onLoad = null; }
  11137. if (onError === void 0) { onError = null; }
  11138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11139. if (invertY === void 0) { invertY = false; }
  11140. var gl = this._gl;
  11141. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11142. scene._addPendingData(texture);
  11143. texture.url = url;
  11144. this._internalTexturesCache.push(texture);
  11145. var onerror = function (request, exception) {
  11146. scene._removePendingData(texture);
  11147. if (onError) {
  11148. onError(request.status + " " + request.statusText, exception);
  11149. }
  11150. };
  11151. var internalCallback = function (data) {
  11152. var width = texture.width;
  11153. var faceDataArrays = callback(data);
  11154. if (!faceDataArrays) {
  11155. return;
  11156. }
  11157. if (mipmmapGenerator) {
  11158. var textureType = _this._getWebGLTextureType(type);
  11159. var internalFormat = _this._getInternalFormat(format);
  11160. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11161. var needConversion = false;
  11162. if (internalFormat === gl.RGB) {
  11163. internalFormat = gl.RGBA;
  11164. needConversion = true;
  11165. }
  11166. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11167. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11168. var mipData = mipmmapGenerator(faceDataArrays);
  11169. for (var level = 0; level < mipData.length; level++) {
  11170. var mipSize = width >> level;
  11171. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11172. var mipFaceData = mipData[level][faceIndex];
  11173. if (needConversion) {
  11174. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11175. }
  11176. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11177. }
  11178. }
  11179. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11180. }
  11181. else {
  11182. texture.generateMipMaps = !noMipmap;
  11183. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11184. }
  11185. texture.isReady = true;
  11186. _this.resetTextureCache();
  11187. scene._removePendingData(texture);
  11188. if (onLoad) {
  11189. onLoad();
  11190. }
  11191. };
  11192. BABYLON.Tools.LoadFile(url, function (data) {
  11193. internalCallback(data);
  11194. }, undefined, scene.database, true, onerror);
  11195. return texture;
  11196. };
  11197. ;
  11198. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11199. if (compression === void 0) { compression = null; }
  11200. var internalFormat = this._getInternalFormat(format);
  11201. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11202. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11203. if (!this._doNotHandleContextLost) {
  11204. texture._bufferView = data;
  11205. texture.format = format;
  11206. texture.invertY = invertY;
  11207. texture._compression = compression;
  11208. }
  11209. if (texture.width % 4 !== 0) {
  11210. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11211. }
  11212. if (compression && data) {
  11213. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11214. }
  11215. else {
  11216. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11217. }
  11218. if (texture.generateMipMaps) {
  11219. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11220. }
  11221. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11222. this.resetTextureCache();
  11223. texture.isReady = true;
  11224. };
  11225. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11226. if (compression === void 0) { compression = null; }
  11227. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11228. texture.baseWidth = width;
  11229. texture.baseHeight = height;
  11230. texture.baseDepth = depth;
  11231. texture.width = width;
  11232. texture.height = height;
  11233. texture.depth = depth;
  11234. texture.format = format;
  11235. texture.generateMipMaps = generateMipMaps;
  11236. texture.samplingMode = samplingMode;
  11237. texture.is3D = true;
  11238. if (!this._doNotHandleContextLost) {
  11239. texture._bufferView = data;
  11240. }
  11241. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11242. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11243. // Filters
  11244. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11245. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11246. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11247. if (generateMipMaps) {
  11248. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11249. }
  11250. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11251. this._internalTexturesCache.push(texture);
  11252. return texture;
  11253. };
  11254. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11255. var gl = this._gl;
  11256. if (!gl) {
  11257. return;
  11258. }
  11259. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11260. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11261. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11262. if (!noMipmap && !isCompressed) {
  11263. gl.generateMipmap(gl.TEXTURE_2D);
  11264. }
  11265. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11266. this.resetTextureCache();
  11267. if (scene) {
  11268. scene._removePendingData(texture);
  11269. }
  11270. texture.onLoadedObservable.notifyObservers(texture);
  11271. texture.onLoadedObservable.clear();
  11272. };
  11273. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11274. var _this = this;
  11275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11276. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11277. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11278. var gl = this._gl;
  11279. if (!gl) {
  11280. return;
  11281. }
  11282. if (!texture._webGLTexture) {
  11283. this.resetTextureCache();
  11284. if (scene) {
  11285. scene._removePendingData(texture);
  11286. }
  11287. return;
  11288. }
  11289. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11290. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11291. texture.baseWidth = width;
  11292. texture.baseHeight = height;
  11293. texture.width = potWidth;
  11294. texture.height = potHeight;
  11295. texture.isReady = true;
  11296. if (processFunction(potWidth, potHeight, function () {
  11297. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11298. })) {
  11299. // Returning as texture needs extra async steps
  11300. return;
  11301. }
  11302. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11303. };
  11304. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11305. // Create new RGBA data container.
  11306. var rgbaData;
  11307. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11308. rgbaData = new Float32Array(width * height * 4);
  11309. }
  11310. else {
  11311. rgbaData = new Uint32Array(width * height * 4);
  11312. }
  11313. // Convert each pixel.
  11314. for (var x = 0; x < width; x++) {
  11315. for (var y = 0; y < height; y++) {
  11316. var index = (y * width + x) * 3;
  11317. var newIndex = (y * width + x) * 4;
  11318. // Map Old Value to new value.
  11319. rgbaData[newIndex + 0] = rgbData[index + 0];
  11320. rgbaData[newIndex + 1] = rgbData[index + 1];
  11321. rgbaData[newIndex + 2] = rgbData[index + 2];
  11322. // Add fully opaque alpha channel.
  11323. rgbaData[newIndex + 3] = 1;
  11324. }
  11325. }
  11326. return rgbaData;
  11327. };
  11328. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11329. var gl = this._gl;
  11330. if (texture._framebuffer) {
  11331. gl.deleteFramebuffer(texture._framebuffer);
  11332. texture._framebuffer = null;
  11333. }
  11334. if (texture._depthStencilBuffer) {
  11335. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11336. texture._depthStencilBuffer = null;
  11337. }
  11338. if (texture._MSAAFramebuffer) {
  11339. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11340. texture._MSAAFramebuffer = null;
  11341. }
  11342. if (texture._MSAARenderBuffer) {
  11343. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11344. texture._MSAARenderBuffer = null;
  11345. }
  11346. };
  11347. Engine.prototype._releaseTexture = function (texture) {
  11348. var gl = this._gl;
  11349. this._releaseFramebufferObjects(texture);
  11350. gl.deleteTexture(texture._webGLTexture);
  11351. // Unbind channels
  11352. this.unbindAllTextures();
  11353. var index = this._internalTexturesCache.indexOf(texture);
  11354. if (index !== -1) {
  11355. this._internalTexturesCache.splice(index, 1);
  11356. }
  11357. // Integrated fixed lod samplers.
  11358. if (texture._lodTextureHigh) {
  11359. texture._lodTextureHigh.dispose();
  11360. }
  11361. if (texture._lodTextureMid) {
  11362. texture._lodTextureMid.dispose();
  11363. }
  11364. if (texture._lodTextureLow) {
  11365. texture._lodTextureLow.dispose();
  11366. }
  11367. };
  11368. Engine.prototype.setProgram = function (program) {
  11369. if (this._currentProgram !== program) {
  11370. this._gl.useProgram(program);
  11371. this._currentProgram = program;
  11372. }
  11373. };
  11374. Engine.prototype.bindSamplers = function (effect) {
  11375. this.setProgram(effect.getProgram());
  11376. var samplers = effect.getSamplers();
  11377. for (var index = 0; index < samplers.length; index++) {
  11378. var uniform = effect.getUniform(samplers[index]);
  11379. this._gl.uniform1i(uniform, index);
  11380. }
  11381. this._currentEffect = null;
  11382. };
  11383. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11384. if (this._activeTextureChannel !== textureChannel) {
  11385. this._gl.activeTexture(textureChannel);
  11386. this._activeTextureChannel = textureChannel;
  11387. }
  11388. };
  11389. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11390. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  11391. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11392. this._activeTexturesCache[this._activeTextureChannel] = texture;
  11393. }
  11394. };
  11395. Engine.prototype._bindTexture = function (channel, texture) {
  11396. if (channel < 0) {
  11397. return;
  11398. }
  11399. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11400. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11401. };
  11402. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11403. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11404. };
  11405. Engine.prototype.unbindAllTextures = function () {
  11406. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11407. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11408. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11409. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11410. if (this.webGLVersion > 1) {
  11411. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11412. }
  11413. }
  11414. };
  11415. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11416. if (channel < 0) {
  11417. return;
  11418. }
  11419. if (this._setTexture(channel, texture)) {
  11420. this._gl.uniform1i(uniform, channel);
  11421. }
  11422. };
  11423. Engine.prototype._setTexture = function (channel, texture) {
  11424. // Not ready?
  11425. if (!texture) {
  11426. if (this._activeTexturesCache[channel] != null) {
  11427. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11428. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11430. if (this.webGLVersion > 1) {
  11431. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11432. }
  11433. }
  11434. return false;
  11435. }
  11436. // Video
  11437. var alreadyActivated = false;
  11438. if (texture.video) {
  11439. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11440. alreadyActivated = true;
  11441. texture.update();
  11442. }
  11443. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11444. texture.delayLoad();
  11445. return false;
  11446. }
  11447. var internalTexture;
  11448. if (texture.isReady()) {
  11449. internalTexture = texture.getInternalTexture();
  11450. }
  11451. else if (texture.isCube) {
  11452. internalTexture = this.emptyCubeTexture;
  11453. }
  11454. else if (texture.is3D) {
  11455. internalTexture = this.emptyTexture3D;
  11456. }
  11457. else {
  11458. internalTexture = this.emptyTexture;
  11459. }
  11460. if (!alreadyActivated) {
  11461. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11462. }
  11463. if (this._activeTexturesCache[this._activeTextureChannel] === internalTexture) {
  11464. return false;
  11465. }
  11466. if (internalTexture && internalTexture.is3D) {
  11467. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11468. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11469. internalTexture._cachedWrapU = texture.wrapU;
  11470. switch (texture.wrapU) {
  11471. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11472. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11473. break;
  11474. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11475. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11476. break;
  11477. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11478. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11479. break;
  11480. }
  11481. }
  11482. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11483. internalTexture._cachedWrapV = texture.wrapV;
  11484. switch (texture.wrapV) {
  11485. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11486. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11487. break;
  11488. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11489. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11490. break;
  11491. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11492. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11493. break;
  11494. }
  11495. }
  11496. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11497. internalTexture._cachedWrapR = texture.wrapR;
  11498. switch (texture.wrapV) {
  11499. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11500. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11501. break;
  11502. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11503. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11504. break;
  11505. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11506. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11507. break;
  11508. }
  11509. }
  11510. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11511. }
  11512. else if (internalTexture && internalTexture.isCube) {
  11513. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11514. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11515. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11516. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11517. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11518. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11519. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11520. }
  11521. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11522. }
  11523. else {
  11524. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11525. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11526. internalTexture._cachedWrapU = texture.wrapU;
  11527. switch (texture.wrapU) {
  11528. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11530. break;
  11531. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11532. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11533. break;
  11534. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11535. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11536. break;
  11537. }
  11538. }
  11539. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11540. internalTexture._cachedWrapV = texture.wrapV;
  11541. switch (texture.wrapV) {
  11542. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11543. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11544. break;
  11545. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11546. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11547. break;
  11548. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11549. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11550. break;
  11551. }
  11552. }
  11553. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11554. }
  11555. return true;
  11556. };
  11557. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11558. if (channel < 0 || !uniform) {
  11559. return;
  11560. }
  11561. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11562. this._textureUnits = new Int32Array(textures.length);
  11563. }
  11564. for (var i = 0; i < textures.length; i++) {
  11565. this._textureUnits[i] = channel + i;
  11566. }
  11567. this._gl.uniform1iv(uniform, this._textureUnits);
  11568. for (var index = 0; index < textures.length; index++) {
  11569. this._setTexture(channel + index, textures[index]);
  11570. }
  11571. };
  11572. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11573. var internalTexture = texture.getInternalTexture();
  11574. if (!internalTexture) {
  11575. return;
  11576. }
  11577. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11578. var value = texture.anisotropicFilteringLevel;
  11579. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11580. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11581. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11582. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11583. }
  11584. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11585. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11586. internalTexture._cachedAnisotropicFilteringLevel = value;
  11587. }
  11588. };
  11589. Engine.prototype.readPixels = function (x, y, width, height) {
  11590. var data = new Uint8Array(height * width * 4);
  11591. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11592. return data;
  11593. };
  11594. /**
  11595. * Add an externaly attached data from its key.
  11596. * This method call will fail and return false, if such key already exists.
  11597. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11598. * @param key the unique key that identifies the data
  11599. * @param data the data object to associate to the key for this Engine instance
  11600. * @return true if no such key were already present and the data was added successfully, false otherwise
  11601. */
  11602. Engine.prototype.addExternalData = function (key, data) {
  11603. if (!this._externalData) {
  11604. this._externalData = new BABYLON.StringDictionary();
  11605. }
  11606. return this._externalData.add(key, data);
  11607. };
  11608. /**
  11609. * Get an externaly attached data from its key
  11610. * @param key the unique key that identifies the data
  11611. * @return the associated data, if present (can be null), or undefined if not present
  11612. */
  11613. Engine.prototype.getExternalData = function (key) {
  11614. if (!this._externalData) {
  11615. this._externalData = new BABYLON.StringDictionary();
  11616. }
  11617. return this._externalData.get(key);
  11618. };
  11619. /**
  11620. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11621. * @param key the unique key that identifies the data
  11622. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11623. * @return the associated data, can be null if the factory returned null.
  11624. */
  11625. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11626. if (!this._externalData) {
  11627. this._externalData = new BABYLON.StringDictionary();
  11628. }
  11629. return this._externalData.getOrAddWithFactory(key, factory);
  11630. };
  11631. /**
  11632. * Remove an externaly attached data from the Engine instance
  11633. * @param key the unique key that identifies the data
  11634. * @return true if the data was successfully removed, false if it doesn't exist
  11635. */
  11636. Engine.prototype.removeExternalData = function (key) {
  11637. if (!this._externalData) {
  11638. this._externalData = new BABYLON.StringDictionary();
  11639. }
  11640. return this._externalData.remove(key);
  11641. };
  11642. Engine.prototype.unbindAllAttributes = function () {
  11643. if (this._mustWipeVertexAttributes) {
  11644. this._mustWipeVertexAttributes = false;
  11645. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11646. this._gl.disableVertexAttribArray(i);
  11647. this._vertexAttribArraysEnabled[i] = false;
  11648. this._currentBufferPointers[i].active = false;
  11649. }
  11650. return;
  11651. }
  11652. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11653. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11654. continue;
  11655. }
  11656. this._gl.disableVertexAttribArray(i);
  11657. this._vertexAttribArraysEnabled[i] = false;
  11658. this._currentBufferPointers[i].active = false;
  11659. }
  11660. };
  11661. Engine.prototype.releaseEffects = function () {
  11662. for (var name in this._compiledEffects) {
  11663. this._deleteProgram(this._compiledEffects[name]._program);
  11664. }
  11665. this._compiledEffects = {};
  11666. };
  11667. // Dispose
  11668. Engine.prototype.dispose = function () {
  11669. this.hideLoadingUI();
  11670. this.stopRenderLoop();
  11671. // Release postProcesses
  11672. while (this.postProcesses.length) {
  11673. this.postProcesses[0].dispose();
  11674. }
  11675. // Empty texture
  11676. if (this._emptyTexture) {
  11677. this._releaseTexture(this._emptyTexture);
  11678. this._emptyTexture = null;
  11679. }
  11680. if (this._emptyCubeTexture) {
  11681. this._releaseTexture(this._emptyCubeTexture);
  11682. this._emptyCubeTexture = null;
  11683. }
  11684. // Rescale PP
  11685. if (this._rescalePostProcess) {
  11686. this._rescalePostProcess.dispose();
  11687. }
  11688. // Release scenes
  11689. while (this.scenes.length) {
  11690. this.scenes[0].dispose();
  11691. }
  11692. // Release audio engine
  11693. if (Engine.audioEngine) {
  11694. Engine.audioEngine.dispose();
  11695. }
  11696. // Release effects
  11697. this.releaseEffects();
  11698. // Unbind
  11699. this.unbindAllAttributes();
  11700. if (this._dummyFramebuffer) {
  11701. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11702. }
  11703. //WebVR
  11704. this.disableVR();
  11705. // Events
  11706. window.removeEventListener("blur", this._onBlur);
  11707. window.removeEventListener("focus", this._onFocus);
  11708. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11709. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11710. if (this._renderingCanvas) {
  11711. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11712. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11713. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11714. if (!this._doNotHandleContextLost) {
  11715. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11716. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11717. }
  11718. }
  11719. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11720. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11721. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11722. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11723. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11724. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11725. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11726. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11727. if (this._onVrDisplayConnect) {
  11728. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11729. if (this._onVrDisplayDisconnect) {
  11730. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11731. }
  11732. if (this._onVrDisplayPresentChange) {
  11733. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11734. }
  11735. this._onVrDisplayConnect = null;
  11736. this._onVrDisplayDisconnect = null;
  11737. }
  11738. // Remove from Instances
  11739. var index = Engine.Instances.indexOf(this);
  11740. if (index >= 0) {
  11741. Engine.Instances.splice(index, 1);
  11742. }
  11743. this._workingCanvas = null;
  11744. this._workingContext = null;
  11745. this._currentBufferPointers = [];
  11746. this._renderingCanvas = null;
  11747. this._currentProgram = null;
  11748. this.onResizeObservable.clear();
  11749. this.onCanvasBlurObservable.clear();
  11750. this.onCanvasFocusObservable.clear();
  11751. this.onCanvasPointerOutObservable.clear();
  11752. this.onBeginFrameObservable.clear();
  11753. this.onEndFrameObservable.clear();
  11754. BABYLON.Effect.ResetCache();
  11755. };
  11756. // Loading screen
  11757. Engine.prototype.displayLoadingUI = function () {
  11758. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11759. return;
  11760. }
  11761. var loadingScreen = this.loadingScreen;
  11762. if (loadingScreen) {
  11763. loadingScreen.displayLoadingUI();
  11764. }
  11765. };
  11766. Engine.prototype.hideLoadingUI = function () {
  11767. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11768. return;
  11769. }
  11770. var loadingScreen = this.loadingScreen;
  11771. if (loadingScreen) {
  11772. loadingScreen.hideLoadingUI();
  11773. }
  11774. };
  11775. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11776. get: function () {
  11777. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11778. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11779. return this._loadingScreen;
  11780. },
  11781. set: function (loadingScreen) {
  11782. this._loadingScreen = loadingScreen;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11788. set: function (text) {
  11789. this.loadingScreen.loadingUIText = text;
  11790. },
  11791. enumerable: true,
  11792. configurable: true
  11793. });
  11794. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11795. set: function (color) {
  11796. this.loadingScreen.loadingUIBackgroundColor = color;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Engine.prototype.attachContextLostEvent = function (callback) {
  11802. if (this._renderingCanvas) {
  11803. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11804. }
  11805. };
  11806. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11807. if (this._renderingCanvas) {
  11808. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11809. }
  11810. };
  11811. Engine.prototype.getVertexShaderSource = function (program) {
  11812. var shaders = this._gl.getAttachedShaders(program);
  11813. if (!shaders) {
  11814. return null;
  11815. }
  11816. return this._gl.getShaderSource(shaders[0]);
  11817. };
  11818. Engine.prototype.getFragmentShaderSource = function (program) {
  11819. var shaders = this._gl.getAttachedShaders(program);
  11820. if (!shaders) {
  11821. return null;
  11822. }
  11823. return this._gl.getShaderSource(shaders[1]);
  11824. };
  11825. Engine.prototype.getError = function () {
  11826. return this._gl.getError();
  11827. };
  11828. // FPS
  11829. Engine.prototype.getFps = function () {
  11830. return this._fps;
  11831. };
  11832. Engine.prototype.getDeltaTime = function () {
  11833. return this._deltaTime;
  11834. };
  11835. Engine.prototype._measureFps = function () {
  11836. this._performanceMonitor.sampleFrame();
  11837. this._fps = this._performanceMonitor.averageFPS;
  11838. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11839. };
  11840. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11841. if (faceIndex === void 0) { faceIndex = -1; }
  11842. var gl = this._gl;
  11843. if (!this._dummyFramebuffer) {
  11844. var dummy = gl.createFramebuffer();
  11845. if (!dummy) {
  11846. throw new Error("Unable to create dummy framebuffer");
  11847. }
  11848. this._dummyFramebuffer = dummy;
  11849. }
  11850. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11851. if (faceIndex > -1) {
  11852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11853. }
  11854. else {
  11855. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11856. }
  11857. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11858. var buffer;
  11859. switch (readType) {
  11860. case gl.UNSIGNED_BYTE:
  11861. buffer = new Uint8Array(4 * width * height);
  11862. readType = gl.UNSIGNED_BYTE;
  11863. break;
  11864. default:
  11865. buffer = new Float32Array(4 * width * height);
  11866. readType = gl.FLOAT;
  11867. break;
  11868. }
  11869. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11870. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11871. return buffer;
  11872. };
  11873. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11874. if (this._webGLVersion > 1) {
  11875. return this._caps.colorBufferFloat;
  11876. }
  11877. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11878. };
  11879. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11880. if (this._webGLVersion > 1) {
  11881. return this._caps.colorBufferFloat;
  11882. }
  11883. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11884. };
  11885. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11886. Engine.prototype._canRenderToFramebuffer = function (type) {
  11887. var gl = this._gl;
  11888. //clear existing errors
  11889. while (gl.getError() !== gl.NO_ERROR) { }
  11890. var successful = true;
  11891. var texture = gl.createTexture();
  11892. gl.bindTexture(gl.TEXTURE_2D, texture);
  11893. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11896. var fb = gl.createFramebuffer();
  11897. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11898. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11899. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11900. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11901. successful = successful && (gl.getError() === gl.NO_ERROR);
  11902. //try render by clearing frame buffer's color buffer
  11903. if (successful) {
  11904. gl.clear(gl.COLOR_BUFFER_BIT);
  11905. successful = successful && (gl.getError() === gl.NO_ERROR);
  11906. }
  11907. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11908. if (successful) {
  11909. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11910. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11911. var readFormat = gl.RGBA;
  11912. var readType = gl.UNSIGNED_BYTE;
  11913. var buffer = new Uint8Array(4);
  11914. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11915. successful = successful && (gl.getError() === gl.NO_ERROR);
  11916. }
  11917. //clean up
  11918. gl.deleteTexture(texture);
  11919. gl.deleteFramebuffer(fb);
  11920. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11921. //clear accumulated errors
  11922. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11923. return successful;
  11924. };
  11925. Engine.prototype._getWebGLTextureType = function (type) {
  11926. if (type === Engine.TEXTURETYPE_FLOAT) {
  11927. return this._gl.FLOAT;
  11928. }
  11929. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11930. // Add Half Float Constant.
  11931. return this._gl.HALF_FLOAT_OES;
  11932. }
  11933. return this._gl.UNSIGNED_BYTE;
  11934. };
  11935. ;
  11936. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11937. if (this._webGLVersion === 1) {
  11938. return this._gl.RGBA;
  11939. }
  11940. if (type === Engine.TEXTURETYPE_FLOAT) {
  11941. return this._gl.RGBA32F;
  11942. }
  11943. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11944. return this._gl.RGBA16F;
  11945. }
  11946. return this._gl.RGBA;
  11947. };
  11948. ;
  11949. Engine.prototype.createQuery = function () {
  11950. return this._gl.createQuery();
  11951. };
  11952. Engine.prototype.deleteQuery = function (query) {
  11953. this._gl.deleteQuery(query);
  11954. return this;
  11955. };
  11956. Engine.prototype.isQueryResultAvailable = function (query) {
  11957. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11958. };
  11959. Engine.prototype.getQueryResult = function (query) {
  11960. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11961. };
  11962. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  11963. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11964. this._gl.beginQuery(glAlgorithm, query);
  11965. return this;
  11966. };
  11967. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  11968. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11969. this._gl.endQuery(glAlgorithm);
  11970. return this;
  11971. };
  11972. /* Time queries */
  11973. Engine.prototype._createTimeQuery = function () {
  11974. var timerQuery = this._caps.timerQuery;
  11975. if (timerQuery.createQueryEXT) {
  11976. return timerQuery.createQueryEXT();
  11977. }
  11978. return this.createQuery();
  11979. };
  11980. Engine.prototype._deleteTimeQuery = function (query) {
  11981. var timerQuery = this._caps.timerQuery;
  11982. if (timerQuery.deleteQueryEXT) {
  11983. timerQuery.deleteQueryEXT(query);
  11984. return;
  11985. }
  11986. this.deleteQuery(query);
  11987. };
  11988. Engine.prototype._getTimeQueryResult = function (query) {
  11989. var timerQuery = this._caps.timerQuery;
  11990. if (timerQuery.getQueryObjectEXT) {
  11991. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  11992. }
  11993. return this.getQueryResult(query);
  11994. };
  11995. Engine.prototype._getTimeQueryAvailability = function (query) {
  11996. var timerQuery = this._caps.timerQuery;
  11997. if (timerQuery.getQueryObjectEXT) {
  11998. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  11999. }
  12000. return this.isQueryResultAvailable(query);
  12001. };
  12002. Engine.prototype.startTimeQuery = function () {
  12003. var timerQuery = this._caps.timerQuery;
  12004. if (!timerQuery) {
  12005. return null;
  12006. }
  12007. var token = new BABYLON._TimeToken();
  12008. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12009. if (this._caps.canUseTimestampForTimerQuery) {
  12010. token._startTimeQuery = this._createTimeQuery();
  12011. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12012. }
  12013. else {
  12014. if (this._currentNonTimestampToken) {
  12015. return this._currentNonTimestampToken;
  12016. }
  12017. token._timeElapsedQuery = this._createTimeQuery();
  12018. if (timerQuery.beginQueryEXT) {
  12019. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12020. }
  12021. else {
  12022. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12023. }
  12024. this._currentNonTimestampToken = token;
  12025. }
  12026. return token;
  12027. };
  12028. Engine.prototype.endTimeQuery = function (token) {
  12029. var timerQuery = this._caps.timerQuery;
  12030. if (!timerQuery || !token) {
  12031. return -1;
  12032. }
  12033. if (this._caps.canUseTimestampForTimerQuery) {
  12034. if (!token._startTimeQuery) {
  12035. return -1;
  12036. }
  12037. if (!token._endTimeQuery) {
  12038. token._endTimeQuery = this._createTimeQuery();
  12039. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12040. }
  12041. }
  12042. else if (!token._timeElapsedQueryEnded) {
  12043. if (!token._timeElapsedQuery) {
  12044. return -1;
  12045. }
  12046. if (timerQuery.endQueryEXT) {
  12047. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12048. }
  12049. else {
  12050. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12051. }
  12052. token._timeElapsedQueryEnded = true;
  12053. }
  12054. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12055. var available = false;
  12056. if (token._endTimeQuery) {
  12057. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12058. }
  12059. else if (token._timeElapsedQuery) {
  12060. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12061. }
  12062. if (available && !disjoint) {
  12063. var result = 0;
  12064. if (this._caps.canUseTimestampForTimerQuery) {
  12065. if (!token._startTimeQuery || !token._endTimeQuery) {
  12066. return -1;
  12067. }
  12068. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12069. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12070. result = timeEnd - timeStart;
  12071. this._deleteTimeQuery(token._startTimeQuery);
  12072. this._deleteTimeQuery(token._endTimeQuery);
  12073. token._startTimeQuery = null;
  12074. token._endTimeQuery = null;
  12075. }
  12076. else {
  12077. if (!token._timeElapsedQuery) {
  12078. return -1;
  12079. }
  12080. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12081. this._deleteTimeQuery(token._timeElapsedQuery);
  12082. token._timeElapsedQuery = null;
  12083. token._timeElapsedQueryEnded = false;
  12084. this._currentNonTimestampToken = null;
  12085. }
  12086. return result;
  12087. }
  12088. return -1;
  12089. };
  12090. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12091. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12092. };
  12093. // Transform feedback
  12094. Engine.prototype.createTransformFeedback = function () {
  12095. return this._gl.createTransformFeedback();
  12096. };
  12097. Engine.prototype.deleteTransformFeedback = function (value) {
  12098. this._gl.deleteTransformFeedback(value);
  12099. };
  12100. Engine.prototype.bindTransformFeedback = function (value) {
  12101. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12102. };
  12103. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12104. if (usePoints === void 0) { usePoints = true; }
  12105. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12106. };
  12107. Engine.prototype.endTransformFeedback = function () {
  12108. this._gl.endTransformFeedback();
  12109. };
  12110. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12111. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12112. };
  12113. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12114. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12115. };
  12116. // Statics
  12117. Engine.isSupported = function () {
  12118. try {
  12119. var tempcanvas = document.createElement("canvas");
  12120. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12121. return gl != null && !!window.WebGLRenderingContext;
  12122. }
  12123. catch (e) {
  12124. return false;
  12125. }
  12126. };
  12127. Engine.Instances = new Array();
  12128. // Const statics
  12129. Engine._ALPHA_DISABLE = 0;
  12130. Engine._ALPHA_ADD = 1;
  12131. Engine._ALPHA_COMBINE = 2;
  12132. Engine._ALPHA_SUBTRACT = 3;
  12133. Engine._ALPHA_MULTIPLY = 4;
  12134. Engine._ALPHA_MAXIMIZED = 5;
  12135. Engine._ALPHA_ONEONE = 6;
  12136. Engine._ALPHA_PREMULTIPLIED = 7;
  12137. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12138. Engine._ALPHA_INTERPOLATE = 9;
  12139. Engine._ALPHA_SCREENMODE = 10;
  12140. Engine._DELAYLOADSTATE_NONE = 0;
  12141. Engine._DELAYLOADSTATE_LOADED = 1;
  12142. Engine._DELAYLOADSTATE_LOADING = 2;
  12143. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12144. Engine._TEXTUREFORMAT_ALPHA = 0;
  12145. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12146. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12147. Engine._TEXTUREFORMAT_RGB = 4;
  12148. Engine._TEXTUREFORMAT_RGBA = 5;
  12149. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12150. Engine._TEXTURETYPE_FLOAT = 1;
  12151. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12152. // Depht or Stencil test Constants.
  12153. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12154. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  12155. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  12156. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  12157. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  12158. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  12159. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  12160. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  12161. // Stencil Actions Constants.
  12162. Engine._KEEP = 0x1E00;
  12163. Engine._REPLACE = 0x1E01;
  12164. Engine._INCR = 0x1E02;
  12165. Engine._DECR = 0x1E03;
  12166. Engine._INVERT = 0x150A;
  12167. Engine._INCR_WRAP = 0x8507;
  12168. Engine._DECR_WRAP = 0x8508;
  12169. // Texture rescaling mode
  12170. Engine._SCALEMODE_FLOOR = 1;
  12171. Engine._SCALEMODE_NEAREST = 2;
  12172. Engine._SCALEMODE_CEILING = 3;
  12173. // Updatable statics so stick with vars here
  12174. Engine.CollisionsEpsilon = 0.001;
  12175. Engine.CodeRepository = "src/";
  12176. Engine.ShadersRepository = "src/Shaders/";
  12177. return Engine;
  12178. }());
  12179. BABYLON.Engine = Engine;
  12180. })(BABYLON || (BABYLON = {}));
  12181. //# sourceMappingURL=babylon.engine.js.map
  12182. var BABYLON;
  12183. (function (BABYLON) {
  12184. /**
  12185. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12186. */
  12187. var Node = /** @class */ (function () {
  12188. /**
  12189. * @constructor
  12190. * @param {string} name - the name and id to be given to this node
  12191. * @param {BABYLON.Scene} the scene this node will be added to
  12192. */
  12193. function Node(name, scene) {
  12194. if (scene === void 0) { scene = null; }
  12195. this.state = "";
  12196. this.metadata = null;
  12197. this.doNotSerialize = false;
  12198. this.animations = new Array();
  12199. this._ranges = {};
  12200. this._isEnabled = true;
  12201. this._isReady = true;
  12202. this._currentRenderId = -1;
  12203. this._parentRenderId = -1;
  12204. /**
  12205. * An event triggered when the mesh is disposed.
  12206. * @type {BABYLON.Observable}
  12207. */
  12208. this.onDisposeObservable = new BABYLON.Observable();
  12209. // Behaviors
  12210. this._behaviors = new Array();
  12211. this.name = name;
  12212. this.id = name;
  12213. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12214. this.uniqueId = this._scene.getUniqueId();
  12215. this._initCache();
  12216. }
  12217. Object.defineProperty(Node.prototype, "parent", {
  12218. get: function () {
  12219. return this._parentNode;
  12220. },
  12221. set: function (parent) {
  12222. if (this._parentNode === parent) {
  12223. return;
  12224. }
  12225. if (this._parentNode) {
  12226. var index = this._parentNode._children.indexOf(this);
  12227. if (index !== -1) {
  12228. this._parentNode._children.splice(index, 1);
  12229. }
  12230. }
  12231. this._parentNode = parent;
  12232. if (this._parentNode) {
  12233. if (!this._parentNode._children) {
  12234. this._parentNode._children = new Array();
  12235. }
  12236. this._parentNode._children.push(this);
  12237. }
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. Node.prototype.getClassName = function () {
  12243. return "Node";
  12244. };
  12245. Object.defineProperty(Node.prototype, "onDispose", {
  12246. set: function (callback) {
  12247. if (this._onDisposeObserver) {
  12248. this.onDisposeObservable.remove(this._onDisposeObserver);
  12249. }
  12250. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12251. },
  12252. enumerable: true,
  12253. configurable: true
  12254. });
  12255. Node.prototype.getScene = function () {
  12256. return this._scene;
  12257. };
  12258. Node.prototype.getEngine = function () {
  12259. return this._scene.getEngine();
  12260. };
  12261. Node.prototype.addBehavior = function (behavior) {
  12262. var _this = this;
  12263. var index = this._behaviors.indexOf(behavior);
  12264. if (index !== -1) {
  12265. return this;
  12266. }
  12267. behavior.init();
  12268. if (this._scene.isLoading) {
  12269. // We defer the attach when the scene will be loaded
  12270. var observer = this._scene.onDataLoadedObservable.add(function () {
  12271. behavior.attach(_this);
  12272. _this._scene.onDataLoadedObservable.remove(observer);
  12273. });
  12274. }
  12275. else {
  12276. behavior.attach(this);
  12277. }
  12278. this._behaviors.push(behavior);
  12279. return this;
  12280. };
  12281. Node.prototype.removeBehavior = function (behavior) {
  12282. var index = this._behaviors.indexOf(behavior);
  12283. if (index === -1) {
  12284. return this;
  12285. }
  12286. this._behaviors[index].detach();
  12287. this._behaviors.splice(index, 1);
  12288. return this;
  12289. };
  12290. Object.defineProperty(Node.prototype, "behaviors", {
  12291. get: function () {
  12292. return this._behaviors;
  12293. },
  12294. enumerable: true,
  12295. configurable: true
  12296. });
  12297. Node.prototype.getBehaviorByName = function (name) {
  12298. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12299. var behavior = _a[_i];
  12300. if (behavior.name === name) {
  12301. return behavior;
  12302. }
  12303. }
  12304. return null;
  12305. };
  12306. // override it in derived class
  12307. Node.prototype.getWorldMatrix = function () {
  12308. return BABYLON.Matrix.Identity();
  12309. };
  12310. // override it in derived class if you add new variables to the cache
  12311. // and call the parent class method
  12312. Node.prototype._initCache = function () {
  12313. this._cache = {};
  12314. this._cache.parent = undefined;
  12315. };
  12316. Node.prototype.updateCache = function (force) {
  12317. if (!force && this.isSynchronized())
  12318. return;
  12319. this._cache.parent = this.parent;
  12320. this._updateCache();
  12321. };
  12322. // override it in derived class if you add new variables to the cache
  12323. // and call the parent class method if !ignoreParentClass
  12324. Node.prototype._updateCache = function (ignoreParentClass) {
  12325. };
  12326. // override it in derived class if you add new variables to the cache
  12327. Node.prototype._isSynchronized = function () {
  12328. return true;
  12329. };
  12330. Node.prototype._markSyncedWithParent = function () {
  12331. if (this.parent) {
  12332. this._parentRenderId = this.parent._currentRenderId;
  12333. }
  12334. };
  12335. Node.prototype.isSynchronizedWithParent = function () {
  12336. if (!this.parent) {
  12337. return true;
  12338. }
  12339. if (this._parentRenderId !== this.parent._currentRenderId) {
  12340. return false;
  12341. }
  12342. return this.parent.isSynchronized();
  12343. };
  12344. Node.prototype.isSynchronized = function (updateCache) {
  12345. var check = this.hasNewParent();
  12346. check = check || !this.isSynchronizedWithParent();
  12347. check = check || !this._isSynchronized();
  12348. if (updateCache)
  12349. this.updateCache(true);
  12350. return !check;
  12351. };
  12352. Node.prototype.hasNewParent = function (update) {
  12353. if (this._cache.parent === this.parent)
  12354. return false;
  12355. if (update)
  12356. this._cache.parent = this.parent;
  12357. return true;
  12358. };
  12359. /**
  12360. * Is this node ready to be used/rendered
  12361. * @return {boolean} is it ready
  12362. */
  12363. Node.prototype.isReady = function () {
  12364. return this._isReady;
  12365. };
  12366. /**
  12367. * Is this node enabled.
  12368. * If the node has a parent and is enabled, the parent will be inspected as well.
  12369. * @return {boolean} whether this node (and its parent) is enabled.
  12370. * @see setEnabled
  12371. */
  12372. Node.prototype.isEnabled = function () {
  12373. if (!this._isEnabled) {
  12374. return false;
  12375. }
  12376. if (this.parent) {
  12377. return this.parent.isEnabled();
  12378. }
  12379. return true;
  12380. };
  12381. /**
  12382. * Set the enabled state of this node.
  12383. * @param {boolean} value - the new enabled state
  12384. * @see isEnabled
  12385. */
  12386. Node.prototype.setEnabled = function (value) {
  12387. this._isEnabled = value;
  12388. };
  12389. /**
  12390. * Is this node a descendant of the given node.
  12391. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12392. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12393. * @see parent
  12394. */
  12395. Node.prototype.isDescendantOf = function (ancestor) {
  12396. if (this.parent) {
  12397. if (this.parent === ancestor) {
  12398. return true;
  12399. }
  12400. return this.parent.isDescendantOf(ancestor);
  12401. }
  12402. return false;
  12403. };
  12404. /**
  12405. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12406. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12407. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  12408. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12409. */
  12410. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12411. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12412. if (!this._children) {
  12413. return;
  12414. }
  12415. for (var index = 0; index < this._children.length; index++) {
  12416. var item = this._children[index];
  12417. if (!predicate || predicate(item)) {
  12418. results.push(item);
  12419. }
  12420. if (!directDescendantsOnly) {
  12421. item._getDescendants(results, false, predicate);
  12422. }
  12423. }
  12424. };
  12425. /**
  12426. * Will return all nodes that have this node as ascendant.
  12427. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  12428. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12429. * @return {BABYLON.Node[]} all children nodes of all types.
  12430. */
  12431. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12432. var results = new Array();
  12433. this._getDescendants(results, directDescendantsOnly, predicate);
  12434. return results;
  12435. };
  12436. /**
  12437. * Get all child-meshes of this node.
  12438. */
  12439. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12440. var results = [];
  12441. this._getDescendants(results, directDecendantsOnly, function (node) {
  12442. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12443. });
  12444. return results;
  12445. };
  12446. /**
  12447. * Get all direct children of this node.
  12448. */
  12449. Node.prototype.getChildren = function (predicate) {
  12450. return this.getDescendants(true, predicate);
  12451. };
  12452. Node.prototype._setReady = function (state) {
  12453. if (state === this._isReady) {
  12454. return;
  12455. }
  12456. if (!state) {
  12457. this._isReady = false;
  12458. return;
  12459. }
  12460. this._isReady = true;
  12461. if (this.onReady) {
  12462. this.onReady(this);
  12463. }
  12464. };
  12465. Node.prototype.getAnimationByName = function (name) {
  12466. for (var i = 0; i < this.animations.length; i++) {
  12467. var animation = this.animations[i];
  12468. if (animation.name === name) {
  12469. return animation;
  12470. }
  12471. }
  12472. return null;
  12473. };
  12474. Node.prototype.createAnimationRange = function (name, from, to) {
  12475. // check name not already in use
  12476. if (!this._ranges[name]) {
  12477. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12478. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12479. if (this.animations[i]) {
  12480. this.animations[i].createRange(name, from, to);
  12481. }
  12482. }
  12483. }
  12484. };
  12485. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12486. if (deleteFrames === void 0) { deleteFrames = true; }
  12487. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12488. if (this.animations[i]) {
  12489. this.animations[i].deleteRange(name, deleteFrames);
  12490. }
  12491. }
  12492. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12493. };
  12494. Node.prototype.getAnimationRange = function (name) {
  12495. return this._ranges[name];
  12496. };
  12497. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12498. var range = this.getAnimationRange(name);
  12499. if (!range) {
  12500. return;
  12501. }
  12502. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12503. };
  12504. Node.prototype.serializeAnimationRanges = function () {
  12505. var serializationRanges = [];
  12506. for (var name in this._ranges) {
  12507. var localRange = this._ranges[name];
  12508. if (!localRange) {
  12509. continue;
  12510. }
  12511. var range = {};
  12512. range.name = name;
  12513. range.from = localRange.from;
  12514. range.to = localRange.to;
  12515. serializationRanges.push(range);
  12516. }
  12517. return serializationRanges;
  12518. };
  12519. Node.prototype.dispose = function () {
  12520. this.parent = null;
  12521. // Callback
  12522. this.onDisposeObservable.notifyObservers(this);
  12523. this.onDisposeObservable.clear();
  12524. // Behaviors
  12525. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12526. var behavior = _a[_i];
  12527. behavior.detach();
  12528. }
  12529. this._behaviors = [];
  12530. };
  12531. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12532. if (parsedNode.ranges) {
  12533. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12534. var data = parsedNode.ranges[index];
  12535. node.createAnimationRange(data.name, data.from, data.to);
  12536. }
  12537. }
  12538. };
  12539. __decorate([
  12540. BABYLON.serialize()
  12541. ], Node.prototype, "name", void 0);
  12542. __decorate([
  12543. BABYLON.serialize()
  12544. ], Node.prototype, "id", void 0);
  12545. __decorate([
  12546. BABYLON.serialize()
  12547. ], Node.prototype, "uniqueId", void 0);
  12548. __decorate([
  12549. BABYLON.serialize()
  12550. ], Node.prototype, "state", void 0);
  12551. __decorate([
  12552. BABYLON.serialize()
  12553. ], Node.prototype, "metadata", void 0);
  12554. return Node;
  12555. }());
  12556. BABYLON.Node = Node;
  12557. })(BABYLON || (BABYLON = {}));
  12558. //# sourceMappingURL=babylon.node.js.map
  12559. var BABYLON;
  12560. (function (BABYLON) {
  12561. var BoundingSphere = /** @class */ (function () {
  12562. function BoundingSphere(minimum, maximum) {
  12563. this.minimum = minimum;
  12564. this.maximum = maximum;
  12565. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12566. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12567. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12568. this.radius = distance * 0.5;
  12569. this.centerWorld = BABYLON.Vector3.Zero();
  12570. this._update(BABYLON.Matrix.Identity());
  12571. }
  12572. // Methods
  12573. BoundingSphere.prototype._update = function (world) {
  12574. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12575. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12576. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12577. };
  12578. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12579. for (var i = 0; i < 6; i++) {
  12580. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12581. return false;
  12582. }
  12583. return true;
  12584. };
  12585. BoundingSphere.prototype.intersectsPoint = function (point) {
  12586. var x = this.centerWorld.x - point.x;
  12587. var y = this.centerWorld.y - point.y;
  12588. var z = this.centerWorld.z - point.z;
  12589. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12590. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12591. return false;
  12592. return true;
  12593. };
  12594. // Statics
  12595. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12596. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12597. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12598. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12599. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12600. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12601. return false;
  12602. return true;
  12603. };
  12604. return BoundingSphere;
  12605. }());
  12606. BABYLON.BoundingSphere = BoundingSphere;
  12607. })(BABYLON || (BABYLON = {}));
  12608. //# sourceMappingURL=babylon.boundingSphere.js.map
  12609. var BABYLON;
  12610. (function (BABYLON) {
  12611. var BoundingBox = /** @class */ (function () {
  12612. function BoundingBox(minimum, maximum) {
  12613. this.minimum = minimum;
  12614. this.maximum = maximum;
  12615. this.vectors = new Array();
  12616. this.vectorsWorld = new Array();
  12617. // Bounding vectors
  12618. this.vectors.push(this.minimum.clone());
  12619. this.vectors.push(this.maximum.clone());
  12620. this.vectors.push(this.minimum.clone());
  12621. this.vectors[2].x = this.maximum.x;
  12622. this.vectors.push(this.minimum.clone());
  12623. this.vectors[3].y = this.maximum.y;
  12624. this.vectors.push(this.minimum.clone());
  12625. this.vectors[4].z = this.maximum.z;
  12626. this.vectors.push(this.maximum.clone());
  12627. this.vectors[5].z = this.minimum.z;
  12628. this.vectors.push(this.maximum.clone());
  12629. this.vectors[6].x = this.minimum.x;
  12630. this.vectors.push(this.maximum.clone());
  12631. this.vectors[7].y = this.minimum.y;
  12632. // OBB
  12633. this.center = this.maximum.add(this.minimum).scale(0.5);
  12634. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12635. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12636. // World
  12637. for (var index = 0; index < this.vectors.length; index++) {
  12638. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12639. }
  12640. this.minimumWorld = BABYLON.Vector3.Zero();
  12641. this.maximumWorld = BABYLON.Vector3.Zero();
  12642. this.centerWorld = BABYLON.Vector3.Zero();
  12643. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12644. this._update(BABYLON.Matrix.Identity());
  12645. }
  12646. // Methods
  12647. BoundingBox.prototype.getWorldMatrix = function () {
  12648. return this._worldMatrix;
  12649. };
  12650. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12651. this._worldMatrix.copyFrom(matrix);
  12652. return this;
  12653. };
  12654. BoundingBox.prototype._update = function (world) {
  12655. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12656. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12657. for (var index = 0; index < this.vectors.length; index++) {
  12658. var v = this.vectorsWorld[index];
  12659. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12660. if (v.x < this.minimumWorld.x)
  12661. this.minimumWorld.x = v.x;
  12662. if (v.y < this.minimumWorld.y)
  12663. this.minimumWorld.y = v.y;
  12664. if (v.z < this.minimumWorld.z)
  12665. this.minimumWorld.z = v.z;
  12666. if (v.x > this.maximumWorld.x)
  12667. this.maximumWorld.x = v.x;
  12668. if (v.y > this.maximumWorld.y)
  12669. this.maximumWorld.y = v.y;
  12670. if (v.z > this.maximumWorld.z)
  12671. this.maximumWorld.z = v.z;
  12672. }
  12673. // Extend
  12674. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12675. this.extendSizeWorld.scaleInPlace(0.5);
  12676. // OBB
  12677. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12678. this.centerWorld.scaleInPlace(0.5);
  12679. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12680. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12681. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12682. this._worldMatrix = world;
  12683. };
  12684. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12685. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12686. };
  12687. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12688. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12689. };
  12690. BoundingBox.prototype.intersectsPoint = function (point) {
  12691. var delta = -BABYLON.Epsilon;
  12692. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12693. return false;
  12694. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12695. return false;
  12696. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12697. return false;
  12698. return true;
  12699. };
  12700. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12701. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12702. };
  12703. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12704. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12705. return false;
  12706. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12707. return false;
  12708. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12709. return false;
  12710. return true;
  12711. };
  12712. // Statics
  12713. BoundingBox.Intersects = function (box0, box1) {
  12714. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12715. return false;
  12716. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12717. return false;
  12718. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12719. return false;
  12720. return true;
  12721. };
  12722. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12723. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12724. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12725. return (num <= (sphereRadius * sphereRadius));
  12726. };
  12727. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12728. for (var p = 0; p < 6; p++) {
  12729. for (var i = 0; i < 8; i++) {
  12730. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12731. return false;
  12732. }
  12733. }
  12734. }
  12735. return true;
  12736. };
  12737. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12738. for (var p = 0; p < 6; p++) {
  12739. var inCount = 8;
  12740. for (var i = 0; i < 8; i++) {
  12741. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12742. --inCount;
  12743. }
  12744. else {
  12745. break;
  12746. }
  12747. }
  12748. if (inCount === 0)
  12749. return false;
  12750. }
  12751. return true;
  12752. };
  12753. return BoundingBox;
  12754. }());
  12755. BABYLON.BoundingBox = BoundingBox;
  12756. })(BABYLON || (BABYLON = {}));
  12757. //# sourceMappingURL=babylon.boundingBox.js.map
  12758. var BABYLON;
  12759. (function (BABYLON) {
  12760. var computeBoxExtents = function (axis, box) {
  12761. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12762. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12763. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12764. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12765. var r = r0 + r1 + r2;
  12766. return {
  12767. min: p - r,
  12768. max: p + r
  12769. };
  12770. };
  12771. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12772. var axisOverlap = function (axis, box0, box1) {
  12773. var result0 = computeBoxExtents(axis, box0);
  12774. var result1 = computeBoxExtents(axis, box1);
  12775. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12776. };
  12777. var BoundingInfo = /** @class */ (function () {
  12778. function BoundingInfo(minimum, maximum) {
  12779. this.minimum = minimum;
  12780. this.maximum = maximum;
  12781. this._isLocked = false;
  12782. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12783. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12784. }
  12785. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12786. get: function () {
  12787. return this._isLocked;
  12788. },
  12789. set: function (value) {
  12790. this._isLocked = value;
  12791. },
  12792. enumerable: true,
  12793. configurable: true
  12794. });
  12795. // Methods
  12796. BoundingInfo.prototype.update = function (world) {
  12797. if (this._isLocked) {
  12798. return;
  12799. }
  12800. this.boundingBox._update(world);
  12801. this.boundingSphere._update(world);
  12802. };
  12803. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12804. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12805. return false;
  12806. return this.boundingBox.isInFrustum(frustumPlanes);
  12807. };
  12808. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12809. /**
  12810. * Gets the world distance between the min and max points of the bounding box
  12811. */
  12812. get: function () {
  12813. var boundingBox = this.boundingBox;
  12814. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12815. return size.length();
  12816. },
  12817. enumerable: true,
  12818. configurable: true
  12819. });
  12820. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12821. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12822. };
  12823. BoundingInfo.prototype._checkCollision = function (collider) {
  12824. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12825. };
  12826. BoundingInfo.prototype.intersectsPoint = function (point) {
  12827. if (!this.boundingSphere.centerWorld) {
  12828. return false;
  12829. }
  12830. if (!this.boundingSphere.intersectsPoint(point)) {
  12831. return false;
  12832. }
  12833. if (!this.boundingBox.intersectsPoint(point)) {
  12834. return false;
  12835. }
  12836. return true;
  12837. };
  12838. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12839. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12840. return false;
  12841. }
  12842. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12843. return false;
  12844. }
  12845. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12846. return false;
  12847. }
  12848. if (!precise) {
  12849. return true;
  12850. }
  12851. var box0 = this.boundingBox;
  12852. var box1 = boundingInfo.boundingBox;
  12853. if (!axisOverlap(box0.directions[0], box0, box1))
  12854. return false;
  12855. if (!axisOverlap(box0.directions[1], box0, box1))
  12856. return false;
  12857. if (!axisOverlap(box0.directions[2], box0, box1))
  12858. return false;
  12859. if (!axisOverlap(box1.directions[0], box0, box1))
  12860. return false;
  12861. if (!axisOverlap(box1.directions[1], box0, box1))
  12862. return false;
  12863. if (!axisOverlap(box1.directions[2], box0, box1))
  12864. return false;
  12865. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12866. return false;
  12867. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12868. return false;
  12869. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12870. return false;
  12871. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12872. return false;
  12873. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12874. return false;
  12875. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12876. return false;
  12877. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12878. return false;
  12879. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12880. return false;
  12881. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12882. return false;
  12883. return true;
  12884. };
  12885. return BoundingInfo;
  12886. }());
  12887. BABYLON.BoundingInfo = BoundingInfo;
  12888. })(BABYLON || (BABYLON = {}));
  12889. //# sourceMappingURL=babylon.boundingInfo.js.map
  12890. var BABYLON;
  12891. (function (BABYLON) {
  12892. var AbstractMesh = /** @class */ (function (_super) {
  12893. __extends(AbstractMesh, _super);
  12894. // Constructor
  12895. function AbstractMesh(name, scene) {
  12896. if (scene === void 0) { scene = null; }
  12897. var _this = _super.call(this, name, scene) || this;
  12898. _this._facetNb = 0; // facet number
  12899. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12900. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12901. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12902. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12903. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12904. _this._subDiv = {
  12905. max: 1,
  12906. X: 1,
  12907. Y: 1,
  12908. Z: 1
  12909. };
  12910. // Normal matrix
  12911. _this._nonUniformScaling = false;
  12912. // Events
  12913. /**
  12914. * An event triggered when this mesh collides with another one
  12915. * @type {BABYLON.Observable}
  12916. */
  12917. _this.onCollideObservable = new BABYLON.Observable();
  12918. /**
  12919. * An event triggered when the collision's position changes
  12920. * @type {BABYLON.Observable}
  12921. */
  12922. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12923. /**
  12924. * An event triggered after the world matrix is updated
  12925. * @type {BABYLON.Observable}
  12926. */
  12927. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12928. /**
  12929. * An event triggered when material is changed
  12930. * @type {BABYLON.Observable}
  12931. */
  12932. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12933. // Properties
  12934. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12935. _this.position = BABYLON.Vector3.Zero();
  12936. /**
  12937. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12938. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12939. * or
  12940. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  12941. * for more info check WebGl documentations
  12942. */
  12943. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12944. /**
  12945. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  12946. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12947. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12948. * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  12949. */
  12950. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12951. /**
  12952. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  12953. * The default value is -1 which means don't break the query and wait till the result.
  12954. */
  12955. _this.occlusionRetryCount = -1;
  12956. _this._occlusionInternalRetryCounter = 0;
  12957. _this._isOccluded = false;
  12958. _this._isOcclusionQueryInProgress = false;
  12959. _this._rotation = BABYLON.Vector3.Zero();
  12960. _this._scaling = BABYLON.Vector3.One();
  12961. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12962. _this.visibility = 1.0;
  12963. _this.alphaIndex = Number.MAX_VALUE;
  12964. _this.infiniteDistance = false;
  12965. _this.isVisible = true;
  12966. _this.isPickable = true;
  12967. _this.showBoundingBox = false;
  12968. _this.showSubMeshesBoundingBox = false;
  12969. _this.isBlocker = false;
  12970. _this.enablePointerMoveEvents = false;
  12971. _this.renderingGroupId = 0;
  12972. _this._receiveShadows = false;
  12973. _this.renderOutline = false;
  12974. _this.outlineColor = BABYLON.Color3.Red();
  12975. _this.outlineWidth = 0.02;
  12976. _this.renderOverlay = false;
  12977. _this.overlayColor = BABYLON.Color3.Red();
  12978. _this.overlayAlpha = 0.5;
  12979. _this._hasVertexAlpha = false;
  12980. _this._useVertexColors = true;
  12981. _this._computeBonesUsingShaders = true;
  12982. _this._numBoneInfluencers = 4;
  12983. _this._applyFog = true;
  12984. _this.scalingDeterminant = 1;
  12985. _this.useOctreeForRenderingSelection = true;
  12986. _this.useOctreeForPicking = true;
  12987. _this.useOctreeForCollisions = true;
  12988. _this._layerMask = 0x0FFFFFFF;
  12989. /**
  12990. * True if the mesh must be rendered in any case.
  12991. */
  12992. _this.alwaysSelectAsActiveMesh = false;
  12993. // Collisions
  12994. _this._checkCollisions = false;
  12995. _this._collisionMask = -1;
  12996. _this._collisionGroup = -1;
  12997. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12998. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12999. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13000. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13001. // Edges
  13002. _this.edgesWidth = 1;
  13003. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  13004. // Cache
  13005. _this._localWorld = BABYLON.Matrix.Zero();
  13006. _this._worldMatrix = BABYLON.Matrix.Zero();
  13007. _this._absolutePosition = BABYLON.Vector3.Zero();
  13008. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  13009. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  13010. _this._isDirty = false;
  13011. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13012. _this._postMultiplyPivotMatrix = false;
  13013. _this._isDisposed = false;
  13014. _this._renderId = 0;
  13015. _this._intersectionsInProgress = new Array();
  13016. _this._isWorldMatrixFrozen = false;
  13017. _this._unIndexed = false;
  13018. _this._lightSources = new Array();
  13019. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13020. if (collidedMesh === void 0) { collidedMesh = null; }
  13021. //TODO move this to the collision coordinator!
  13022. if (_this.getScene().workerCollisions)
  13023. newPosition.multiplyInPlace(_this._collider.radius);
  13024. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  13025. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  13026. _this.position.addInPlace(_this._diffPositionForCollisions);
  13027. }
  13028. if (collidedMesh) {
  13029. _this.onCollideObservable.notifyObservers(collidedMesh);
  13030. }
  13031. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  13032. };
  13033. _this.getScene().addMesh(_this);
  13034. _this._resyncLightSources();
  13035. return _this;
  13036. }
  13037. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  13038. get: function () {
  13039. return AbstractMesh._BILLBOARDMODE_NONE;
  13040. },
  13041. enumerable: true,
  13042. configurable: true
  13043. });
  13044. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  13045. get: function () {
  13046. return AbstractMesh._BILLBOARDMODE_X;
  13047. },
  13048. enumerable: true,
  13049. configurable: true
  13050. });
  13051. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  13052. get: function () {
  13053. return AbstractMesh._BILLBOARDMODE_Y;
  13054. },
  13055. enumerable: true,
  13056. configurable: true
  13057. });
  13058. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  13059. get: function () {
  13060. return AbstractMesh._BILLBOARDMODE_Z;
  13061. },
  13062. enumerable: true,
  13063. configurable: true
  13064. });
  13065. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  13066. get: function () {
  13067. return AbstractMesh._BILLBOARDMODE_ALL;
  13068. },
  13069. enumerable: true,
  13070. configurable: true
  13071. });
  13072. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  13073. /**
  13074. * Read-only : the number of facets in the mesh
  13075. */
  13076. get: function () {
  13077. return this._facetNb;
  13078. },
  13079. enumerable: true,
  13080. configurable: true
  13081. });
  13082. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  13083. /**
  13084. * The number (integer) of subdivisions per axis in the partioning space
  13085. */
  13086. get: function () {
  13087. return this._partitioningSubdivisions;
  13088. },
  13089. set: function (nb) {
  13090. this._partitioningSubdivisions = nb;
  13091. },
  13092. enumerable: true,
  13093. configurable: true
  13094. });
  13095. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13096. /**
  13097. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13098. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13099. */
  13100. get: function () {
  13101. return this._partitioningBBoxRatio;
  13102. },
  13103. set: function (ratio) {
  13104. this._partitioningBBoxRatio = ratio;
  13105. },
  13106. enumerable: true,
  13107. configurable: true
  13108. });
  13109. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13110. /**
  13111. * Read-only boolean : is the feature facetData enabled ?
  13112. */
  13113. get: function () {
  13114. return this._facetDataEnabled;
  13115. },
  13116. enumerable: true,
  13117. configurable: true
  13118. });
  13119. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13120. get: function () {
  13121. return this._nonUniformScaling;
  13122. },
  13123. set: function (value) {
  13124. if (this._nonUniformScaling === value) {
  13125. return;
  13126. }
  13127. this._nonUniformScaling = true;
  13128. this._markSubMeshesAsMiscDirty();
  13129. },
  13130. enumerable: true,
  13131. configurable: true
  13132. });
  13133. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13134. set: function (callback) {
  13135. if (this._onCollideObserver) {
  13136. this.onCollideObservable.remove(this._onCollideObserver);
  13137. }
  13138. this._onCollideObserver = this.onCollideObservable.add(callback);
  13139. },
  13140. enumerable: true,
  13141. configurable: true
  13142. });
  13143. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13144. set: function (callback) {
  13145. if (this._onCollisionPositionChangeObserver) {
  13146. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13147. }
  13148. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13149. },
  13150. enumerable: true,
  13151. configurable: true
  13152. });
  13153. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13154. /**
  13155. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  13156. */
  13157. get: function () {
  13158. return this._isOccluded;
  13159. },
  13160. set: function (value) {
  13161. this._isOccluded = value;
  13162. },
  13163. enumerable: true,
  13164. configurable: true
  13165. });
  13166. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13167. /**
  13168. * Flag to check the progress status of the query
  13169. */
  13170. get: function () {
  13171. return this._isOcclusionQueryInProgress;
  13172. },
  13173. enumerable: true,
  13174. configurable: true
  13175. });
  13176. Object.defineProperty(AbstractMesh.prototype, "material", {
  13177. get: function () {
  13178. return this._material;
  13179. },
  13180. set: function (value) {
  13181. if (this._material === value) {
  13182. return;
  13183. }
  13184. this._material = value;
  13185. if (this.onMaterialChangedObservable.hasObservers) {
  13186. this.onMaterialChangedObservable.notifyObservers(this);
  13187. }
  13188. if (!this.subMeshes) {
  13189. return;
  13190. }
  13191. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13192. var subMesh = _a[_i];
  13193. subMesh.setEffect(null);
  13194. }
  13195. },
  13196. enumerable: true,
  13197. configurable: true
  13198. });
  13199. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13200. get: function () {
  13201. return this._receiveShadows;
  13202. },
  13203. set: function (value) {
  13204. if (this._receiveShadows === value) {
  13205. return;
  13206. }
  13207. this._receiveShadows = value;
  13208. this._markSubMeshesAsLightDirty();
  13209. },
  13210. enumerable: true,
  13211. configurable: true
  13212. });
  13213. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13214. get: function () {
  13215. return this._hasVertexAlpha;
  13216. },
  13217. set: function (value) {
  13218. if (this._hasVertexAlpha === value) {
  13219. return;
  13220. }
  13221. this._hasVertexAlpha = value;
  13222. this._markSubMeshesAsAttributesDirty();
  13223. },
  13224. enumerable: true,
  13225. configurable: true
  13226. });
  13227. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13228. get: function () {
  13229. return this._useVertexColors;
  13230. },
  13231. set: function (value) {
  13232. if (this._useVertexColors === value) {
  13233. return;
  13234. }
  13235. this._useVertexColors = value;
  13236. this._markSubMeshesAsAttributesDirty();
  13237. },
  13238. enumerable: true,
  13239. configurable: true
  13240. });
  13241. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13242. get: function () {
  13243. return this._computeBonesUsingShaders;
  13244. },
  13245. set: function (value) {
  13246. if (this._computeBonesUsingShaders === value) {
  13247. return;
  13248. }
  13249. this._computeBonesUsingShaders = value;
  13250. this._markSubMeshesAsAttributesDirty();
  13251. },
  13252. enumerable: true,
  13253. configurable: true
  13254. });
  13255. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13256. get: function () {
  13257. return this._numBoneInfluencers;
  13258. },
  13259. set: function (value) {
  13260. if (this._numBoneInfluencers === value) {
  13261. return;
  13262. }
  13263. this._numBoneInfluencers = value;
  13264. this._markSubMeshesAsAttributesDirty();
  13265. },
  13266. enumerable: true,
  13267. configurable: true
  13268. });
  13269. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13270. get: function () {
  13271. return this._applyFog;
  13272. },
  13273. set: function (value) {
  13274. if (this._applyFog === value) {
  13275. return;
  13276. }
  13277. this._applyFog = value;
  13278. this._markSubMeshesAsMiscDirty();
  13279. },
  13280. enumerable: true,
  13281. configurable: true
  13282. });
  13283. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13284. get: function () {
  13285. return this._layerMask;
  13286. },
  13287. set: function (value) {
  13288. if (value === this._layerMask) {
  13289. return;
  13290. }
  13291. this._layerMask = value;
  13292. this._resyncLightSources();
  13293. },
  13294. enumerable: true,
  13295. configurable: true
  13296. });
  13297. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13298. get: function () {
  13299. return this._collisionMask;
  13300. },
  13301. set: function (mask) {
  13302. this._collisionMask = !isNaN(mask) ? mask : -1;
  13303. },
  13304. enumerable: true,
  13305. configurable: true
  13306. });
  13307. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13308. get: function () {
  13309. return this._collisionGroup;
  13310. },
  13311. set: function (mask) {
  13312. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13313. },
  13314. enumerable: true,
  13315. configurable: true
  13316. });
  13317. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13318. get: function () {
  13319. return null;
  13320. },
  13321. enumerable: true,
  13322. configurable: true
  13323. });
  13324. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13325. get: function () {
  13326. return this._skeleton;
  13327. },
  13328. set: function (value) {
  13329. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13330. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13331. }
  13332. if (value && value.needInitialSkinMatrix) {
  13333. value._registerMeshWithPoseMatrix(this);
  13334. }
  13335. this._skeleton = value;
  13336. if (!this._skeleton) {
  13337. this._bonesTransformMatrices = null;
  13338. }
  13339. this._markSubMeshesAsAttributesDirty();
  13340. },
  13341. enumerable: true,
  13342. configurable: true
  13343. });
  13344. /**
  13345. * Boolean : true if the mesh has been disposed.
  13346. */
  13347. AbstractMesh.prototype.isDisposed = function () {
  13348. return this._isDisposed;
  13349. };
  13350. /**
  13351. * Returns the string "AbstractMesh"
  13352. */
  13353. AbstractMesh.prototype.getClassName = function () {
  13354. return "AbstractMesh";
  13355. };
  13356. /**
  13357. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13358. */
  13359. AbstractMesh.prototype.toString = function (fullDetails) {
  13360. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13361. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13362. if (this._skeleton) {
  13363. ret += ", skeleton: " + this._skeleton.name;
  13364. }
  13365. if (fullDetails) {
  13366. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13367. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13368. }
  13369. return ret;
  13370. };
  13371. AbstractMesh.prototype._rebuild = function () {
  13372. if (this._occlusionQuery) {
  13373. this._occlusionQuery = null;
  13374. }
  13375. if (this._edgesRenderer) {
  13376. this._edgesRenderer._rebuild();
  13377. }
  13378. if (!this.subMeshes) {
  13379. return;
  13380. }
  13381. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13382. var subMesh = _a[_i];
  13383. subMesh._rebuild();
  13384. }
  13385. };
  13386. AbstractMesh.prototype._resyncLightSources = function () {
  13387. this._lightSources.length = 0;
  13388. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13389. var light = _a[_i];
  13390. if (!light.isEnabled()) {
  13391. continue;
  13392. }
  13393. if (light.canAffectMesh(this)) {
  13394. this._lightSources.push(light);
  13395. }
  13396. }
  13397. this._markSubMeshesAsLightDirty();
  13398. };
  13399. AbstractMesh.prototype._resyncLighSource = function (light) {
  13400. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13401. var index = this._lightSources.indexOf(light);
  13402. if (index === -1) {
  13403. if (!isIn) {
  13404. return;
  13405. }
  13406. this._lightSources.push(light);
  13407. }
  13408. else {
  13409. if (isIn) {
  13410. return;
  13411. }
  13412. this._lightSources.splice(index, 1);
  13413. }
  13414. this._markSubMeshesAsLightDirty();
  13415. };
  13416. AbstractMesh.prototype._removeLightSource = function (light) {
  13417. var index = this._lightSources.indexOf(light);
  13418. if (index === -1) {
  13419. return;
  13420. }
  13421. this._lightSources.splice(index, 1);
  13422. };
  13423. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13424. if (!this.subMeshes) {
  13425. return;
  13426. }
  13427. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13428. var subMesh = _a[_i];
  13429. if (subMesh._materialDefines) {
  13430. func(subMesh._materialDefines);
  13431. }
  13432. }
  13433. };
  13434. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13435. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13436. };
  13437. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13438. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13439. };
  13440. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13441. if (!this.subMeshes) {
  13442. return;
  13443. }
  13444. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13445. var subMesh = _a[_i];
  13446. var material = subMesh.getMaterial();
  13447. if (material) {
  13448. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13449. }
  13450. }
  13451. };
  13452. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13453. /**
  13454. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13455. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13456. * Default : (0.0, 0.0, 0.0)
  13457. */
  13458. get: function () {
  13459. return this._rotation;
  13460. },
  13461. set: function (newRotation) {
  13462. this._rotation = newRotation;
  13463. },
  13464. enumerable: true,
  13465. configurable: true
  13466. });
  13467. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13468. /**
  13469. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13470. * Default : (1.0, 1.0, 1.0)
  13471. */
  13472. get: function () {
  13473. return this._scaling;
  13474. },
  13475. set: function (newScaling) {
  13476. this._scaling = newScaling;
  13477. if (this.physicsImpostor) {
  13478. this.physicsImpostor.forceUpdate();
  13479. }
  13480. },
  13481. enumerable: true,
  13482. configurable: true
  13483. });
  13484. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13485. /**
  13486. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13487. * It's null by default.
  13488. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  13489. */
  13490. get: function () {
  13491. return this._rotationQuaternion;
  13492. },
  13493. set: function (quaternion) {
  13494. this._rotationQuaternion = quaternion;
  13495. //reset the rotation vector.
  13496. if (quaternion && this.rotation.length()) {
  13497. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13498. }
  13499. },
  13500. enumerable: true,
  13501. configurable: true
  13502. });
  13503. // Methods
  13504. /**
  13505. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13506. * Returns the AbstractMesh.
  13507. */
  13508. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13509. this._poseMatrix.copyFrom(matrix);
  13510. return this;
  13511. };
  13512. /**
  13513. * Returns the mesh Pose matrix.
  13514. * Returned object : Matrix
  13515. */
  13516. AbstractMesh.prototype.getPoseMatrix = function () {
  13517. return this._poseMatrix;
  13518. };
  13519. /**
  13520. * Disables the mesh edger rendering mode.
  13521. * Returns the AbstractMesh.
  13522. */
  13523. AbstractMesh.prototype.disableEdgesRendering = function () {
  13524. if (this._edgesRenderer) {
  13525. this._edgesRenderer.dispose();
  13526. this._edgesRenderer = null;
  13527. }
  13528. return this;
  13529. };
  13530. /**
  13531. * Enables the edge rendering mode on the mesh.
  13532. * This mode makes the mesh edges visible.
  13533. * Returns the AbstractMesh.
  13534. */
  13535. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13536. if (epsilon === void 0) { epsilon = 0.95; }
  13537. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13538. this.disableEdgesRendering();
  13539. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13540. return this;
  13541. };
  13542. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13543. /**
  13544. * Returns true if the mesh is blocked. Used by the class Mesh.
  13545. * Returns the boolean `false` by default.
  13546. */
  13547. get: function () {
  13548. return false;
  13549. },
  13550. enumerable: true,
  13551. configurable: true
  13552. });
  13553. /**
  13554. * Returns the mesh itself by default, used by the class Mesh.
  13555. * Returned type : AbstractMesh
  13556. */
  13557. AbstractMesh.prototype.getLOD = function (camera) {
  13558. return this;
  13559. };
  13560. /**
  13561. * Returns 0 by default, used by the class Mesh.
  13562. * Returns an integer.
  13563. */
  13564. AbstractMesh.prototype.getTotalVertices = function () {
  13565. return 0;
  13566. };
  13567. /**
  13568. * Returns null by default, used by the class Mesh.
  13569. * Returned type : integer array
  13570. */
  13571. AbstractMesh.prototype.getIndices = function () {
  13572. return null;
  13573. };
  13574. /**
  13575. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13576. * Returned type : float array or Float32Array
  13577. */
  13578. AbstractMesh.prototype.getVerticesData = function (kind) {
  13579. return null;
  13580. };
  13581. /**
  13582. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13583. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13584. * The `data` are either a numeric array either a Float32Array.
  13585. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13586. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  13587. * Note that a new underlying VertexBuffer object is created each call.
  13588. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13589. *
  13590. * Possible `kind` values :
  13591. * - BABYLON.VertexBuffer.PositionKind
  13592. * - BABYLON.VertexBuffer.UVKind
  13593. * - BABYLON.VertexBuffer.UV2Kind
  13594. * - BABYLON.VertexBuffer.UV3Kind
  13595. * - BABYLON.VertexBuffer.UV4Kind
  13596. * - BABYLON.VertexBuffer.UV5Kind
  13597. * - BABYLON.VertexBuffer.UV6Kind
  13598. * - BABYLON.VertexBuffer.ColorKind
  13599. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13600. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13601. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13602. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13603. *
  13604. * Returns the Mesh.
  13605. */
  13606. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13607. return this;
  13608. };
  13609. /**
  13610. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13611. * If the mesh has no geometry, it is simply returned as it is.
  13612. * The `data` are either a numeric array either a Float32Array.
  13613. * No new underlying VertexBuffer object is created.
  13614. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13615. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13616. *
  13617. * Possible `kind` values :
  13618. * - BABYLON.VertexBuffer.PositionKind
  13619. * - BABYLON.VertexBuffer.UVKind
  13620. * - BABYLON.VertexBuffer.UV2Kind
  13621. * - BABYLON.VertexBuffer.UV3Kind
  13622. * - BABYLON.VertexBuffer.UV4Kind
  13623. * - BABYLON.VertexBuffer.UV5Kind
  13624. * - BABYLON.VertexBuffer.UV6Kind
  13625. * - BABYLON.VertexBuffer.ColorKind
  13626. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13627. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13628. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13629. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13630. *
  13631. * Returns the Mesh.
  13632. */
  13633. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13634. return this;
  13635. };
  13636. /**
  13637. * Sets the mesh indices.
  13638. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13639. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13640. * This method creates a new index buffer each call.
  13641. * Returns the Mesh.
  13642. */
  13643. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13644. return this;
  13645. };
  13646. /** Returns false by default, used by the class Mesh.
  13647. * Returns a boolean
  13648. */
  13649. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13650. return false;
  13651. };
  13652. /**
  13653. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13654. * Returns a BoundingInfo
  13655. */
  13656. AbstractMesh.prototype.getBoundingInfo = function () {
  13657. if (this._masterMesh) {
  13658. return this._masterMesh.getBoundingInfo();
  13659. }
  13660. if (!this._boundingInfo) {
  13661. this._updateBoundingInfo();
  13662. }
  13663. return this._boundingInfo;
  13664. };
  13665. /**
  13666. * Sets a mesh new object BoundingInfo.
  13667. * Returns the AbstractMesh.
  13668. */
  13669. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13670. this._boundingInfo = boundingInfo;
  13671. return this;
  13672. };
  13673. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13674. get: function () {
  13675. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13676. },
  13677. enumerable: true,
  13678. configurable: true
  13679. });
  13680. AbstractMesh.prototype._preActivate = function () {
  13681. };
  13682. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13683. };
  13684. AbstractMesh.prototype._activate = function (renderId) {
  13685. this._renderId = renderId;
  13686. };
  13687. /**
  13688. * Returns the latest update of the World matrix
  13689. * Returns a Matrix.
  13690. */
  13691. AbstractMesh.prototype.getWorldMatrix = function () {
  13692. if (this._masterMesh) {
  13693. return this._masterMesh.getWorldMatrix();
  13694. }
  13695. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13696. this.computeWorldMatrix();
  13697. }
  13698. return this._worldMatrix;
  13699. };
  13700. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13701. /**
  13702. * Returns directly the latest state of the mesh World matrix.
  13703. * A Matrix is returned.
  13704. */
  13705. get: function () {
  13706. return this._worldMatrix;
  13707. },
  13708. enumerable: true,
  13709. configurable: true
  13710. });
  13711. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13712. /**
  13713. * Returns the current mesh absolute position.
  13714. * Retuns a Vector3.
  13715. */
  13716. get: function () {
  13717. return this._absolutePosition;
  13718. },
  13719. enumerable: true,
  13720. configurable: true
  13721. });
  13722. /**
  13723. * Prevents the World matrix to be computed any longer.
  13724. * Returns the AbstractMesh.
  13725. */
  13726. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13727. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13728. this.computeWorldMatrix(true);
  13729. this._isWorldMatrixFrozen = true;
  13730. return this;
  13731. };
  13732. /**
  13733. * Allows back the World matrix computation.
  13734. * Returns the AbstractMesh.
  13735. */
  13736. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13737. this._isWorldMatrixFrozen = false;
  13738. this.computeWorldMatrix(true);
  13739. return this;
  13740. };
  13741. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13742. /**
  13743. * True if the World matrix has been frozen.
  13744. * Returns a boolean.
  13745. */
  13746. get: function () {
  13747. return this._isWorldMatrixFrozen;
  13748. },
  13749. enumerable: true,
  13750. configurable: true
  13751. });
  13752. /**
  13753. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13754. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13755. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13756. * The passed axis is also normalized.
  13757. * Returns the AbstractMesh.
  13758. */
  13759. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13760. axis.normalize();
  13761. if (!this.rotationQuaternion) {
  13762. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13763. this.rotation = BABYLON.Vector3.Zero();
  13764. }
  13765. var rotationQuaternion;
  13766. if (!space || space === BABYLON.Space.LOCAL) {
  13767. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13768. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13769. }
  13770. else {
  13771. if (this.parent) {
  13772. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13773. invertParentWorldMatrix.invert();
  13774. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13775. }
  13776. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13777. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13778. }
  13779. return this;
  13780. };
  13781. /**
  13782. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13783. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13784. * The passed axis is also normalized.
  13785. * Returns the AbstractMesh.
  13786. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13787. */
  13788. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13789. axis.normalize();
  13790. if (!this.rotationQuaternion) {
  13791. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13792. this.rotation.copyFromFloats(0, 0, 0);
  13793. }
  13794. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13795. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13796. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13797. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13798. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13799. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13800. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13801. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13802. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13803. return this;
  13804. };
  13805. /**
  13806. * Translates the mesh along the axis vector for the passed distance in the given space.
  13807. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13808. * Returns the AbstractMesh.
  13809. */
  13810. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13811. var displacementVector = axis.scale(distance);
  13812. if (!space || space === BABYLON.Space.LOCAL) {
  13813. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13814. this.setPositionWithLocalVector(tempV3);
  13815. }
  13816. else {
  13817. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13818. }
  13819. return this;
  13820. };
  13821. /**
  13822. * Adds a rotation step to the mesh current rotation.
  13823. * x, y, z are Euler angles expressed in radians.
  13824. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13825. * This means this rotation is made in the mesh local space only.
  13826. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13827. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13828. * ```javascript
  13829. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13830. * ```
  13831. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13832. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  13833. * Returns the AbstractMesh.
  13834. */
  13835. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13836. var rotationQuaternion;
  13837. if (this.rotationQuaternion) {
  13838. rotationQuaternion = this.rotationQuaternion;
  13839. }
  13840. else {
  13841. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13842. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13843. }
  13844. var accumulation = BABYLON.Tmp.Quaternion[0];
  13845. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13846. rotationQuaternion.multiplyInPlace(accumulation);
  13847. if (!this.rotationQuaternion) {
  13848. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13849. }
  13850. return this;
  13851. };
  13852. /**
  13853. * Retuns the mesh absolute position in the World.
  13854. * Returns a Vector3.
  13855. */
  13856. AbstractMesh.prototype.getAbsolutePosition = function () {
  13857. this.computeWorldMatrix();
  13858. return this._absolutePosition;
  13859. };
  13860. /**
  13861. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13862. * Returns the AbstractMesh.
  13863. */
  13864. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13865. if (!absolutePosition) {
  13866. return this;
  13867. }
  13868. var absolutePositionX;
  13869. var absolutePositionY;
  13870. var absolutePositionZ;
  13871. if (absolutePosition.x === undefined) {
  13872. if (arguments.length < 3) {
  13873. return this;
  13874. }
  13875. absolutePositionX = arguments[0];
  13876. absolutePositionY = arguments[1];
  13877. absolutePositionZ = arguments[2];
  13878. }
  13879. else {
  13880. absolutePositionX = absolutePosition.x;
  13881. absolutePositionY = absolutePosition.y;
  13882. absolutePositionZ = absolutePosition.z;
  13883. }
  13884. if (this.parent) {
  13885. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13886. invertParentWorldMatrix.invert();
  13887. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13888. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13889. }
  13890. else {
  13891. this.position.x = absolutePositionX;
  13892. this.position.y = absolutePositionY;
  13893. this.position.z = absolutePositionZ;
  13894. }
  13895. return this;
  13896. };
  13897. // ================================== Point of View Movement =================================
  13898. /**
  13899. * Perform relative position change from the point of view of behind the front of the mesh.
  13900. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13901. * Supports definition of mesh facing forward or backward.
  13902. * @param {number} amountRight
  13903. * @param {number} amountUp
  13904. * @param {number} amountForward
  13905. *
  13906. * Returns the AbstractMesh.
  13907. */
  13908. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13909. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13910. return this;
  13911. };
  13912. /**
  13913. * Calculate relative position change from the point of view of behind the front of the mesh.
  13914. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13915. * Supports definition of mesh facing forward or backward.
  13916. * @param {number} amountRight
  13917. * @param {number} amountUp
  13918. * @param {number} amountForward
  13919. *
  13920. * Returns a new Vector3.
  13921. */
  13922. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13923. var rotMatrix = new BABYLON.Matrix();
  13924. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13925. rotQuaternion.toRotationMatrix(rotMatrix);
  13926. var translationDelta = BABYLON.Vector3.Zero();
  13927. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13928. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13929. return translationDelta;
  13930. };
  13931. // ================================== Point of View Rotation =================================
  13932. /**
  13933. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13934. * Supports definition of mesh facing forward or backward.
  13935. * @param {number} flipBack
  13936. * @param {number} twirlClockwise
  13937. * @param {number} tiltRight
  13938. *
  13939. * Returns the AbstractMesh.
  13940. */
  13941. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13942. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13943. return this;
  13944. };
  13945. /**
  13946. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13947. * Supports definition of mesh facing forward or backward.
  13948. * @param {number} flipBack
  13949. * @param {number} twirlClockwise
  13950. * @param {number} tiltRight
  13951. *
  13952. * Returns a new Vector3.
  13953. */
  13954. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13955. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13956. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13957. };
  13958. /**
  13959. * Sets a new pivot matrix to the mesh.
  13960. * Returns the AbstractMesh.
  13961. */
  13962. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13963. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13964. this._pivotMatrix = matrix.clone();
  13965. this._cache.pivotMatrixUpdated = true;
  13966. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13967. if (this._postMultiplyPivotMatrix) {
  13968. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13969. }
  13970. return this;
  13971. };
  13972. /**
  13973. * Returns the mesh pivot matrix.
  13974. * Default : Identity.
  13975. * A Matrix is returned.
  13976. */
  13977. AbstractMesh.prototype.getPivotMatrix = function () {
  13978. return this._pivotMatrix;
  13979. };
  13980. AbstractMesh.prototype._isSynchronized = function () {
  13981. if (this._isDirty) {
  13982. return false;
  13983. }
  13984. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13985. return false;
  13986. if (this._cache.pivotMatrixUpdated) {
  13987. return false;
  13988. }
  13989. if (this.infiniteDistance) {
  13990. return false;
  13991. }
  13992. if (!this._cache.position.equals(this.position))
  13993. return false;
  13994. if (this.rotationQuaternion) {
  13995. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13996. return false;
  13997. }
  13998. if (!this._cache.rotation.equals(this.rotation))
  13999. return false;
  14000. if (!this._cache.scaling.equals(this.scaling))
  14001. return false;
  14002. return true;
  14003. };
  14004. AbstractMesh.prototype._initCache = function () {
  14005. _super.prototype._initCache.call(this);
  14006. this._cache.localMatrixUpdated = false;
  14007. this._cache.position = BABYLON.Vector3.Zero();
  14008. this._cache.scaling = BABYLON.Vector3.Zero();
  14009. this._cache.rotation = BABYLON.Vector3.Zero();
  14010. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14011. this._cache.billboardMode = -1;
  14012. };
  14013. AbstractMesh.prototype.markAsDirty = function (property) {
  14014. if (property === "rotation") {
  14015. this.rotationQuaternion = null;
  14016. }
  14017. this._currentRenderId = Number.MAX_VALUE;
  14018. this._isDirty = true;
  14019. return this;
  14020. };
  14021. /**
  14022. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14023. */
  14024. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  14025. this.computeWorldMatrix(true);
  14026. var min;
  14027. var max;
  14028. var boundingInfo = this.getBoundingInfo();
  14029. if (!this.subMeshes || !boundingInfo) {
  14030. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14031. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14032. }
  14033. else {
  14034. min = boundingInfo.boundingBox.minimumWorld;
  14035. max = boundingInfo.boundingBox.maximumWorld;
  14036. }
  14037. var descendants = this.getDescendants(false);
  14038. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14039. var descendant = descendants_1[_i];
  14040. var childMesh = descendant;
  14041. childMesh.computeWorldMatrix(true);
  14042. var childBoundingInfo = childMesh.getBoundingInfo();
  14043. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  14044. continue;
  14045. }
  14046. var boundingBox = childBoundingInfo.boundingBox;
  14047. var minBox = boundingBox.minimumWorld;
  14048. var maxBox = boundingBox.maximumWorld;
  14049. BABYLON.Tools.CheckExtends(minBox, min, max);
  14050. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14051. }
  14052. return {
  14053. min: min,
  14054. max: max
  14055. };
  14056. };
  14057. /**
  14058. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14059. * Returns the AbstractMesh.
  14060. */
  14061. AbstractMesh.prototype._updateBoundingInfo = function () {
  14062. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14063. this._boundingInfo.update(this.worldMatrixFromCache);
  14064. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14065. return this;
  14066. };
  14067. /**
  14068. * Update a mesh's children BoundingInfo objects only.
  14069. * Returns the AbstractMesh.
  14070. */
  14071. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14072. if (!this.subMeshes) {
  14073. return this;
  14074. }
  14075. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14076. var subMesh = this.subMeshes[subIndex];
  14077. if (!subMesh.IsGlobal) {
  14078. subMesh.updateBoundingInfo(matrix);
  14079. }
  14080. }
  14081. return this;
  14082. };
  14083. /**
  14084. * Computes the mesh World matrix and returns it.
  14085. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14086. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14087. * If the parameter `force`is set to `true`, the actual computation is done.
  14088. * Returns the mesh World Matrix.
  14089. */
  14090. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  14091. if (this._isWorldMatrixFrozen) {
  14092. return this._worldMatrix;
  14093. }
  14094. if (!force && this.isSynchronized(true)) {
  14095. return this._worldMatrix;
  14096. }
  14097. this._cache.position.copyFrom(this.position);
  14098. this._cache.scaling.copyFrom(this.scaling);
  14099. this._cache.pivotMatrixUpdated = false;
  14100. this._cache.billboardMode = this.billboardMode;
  14101. this._currentRenderId = this.getScene().getRenderId();
  14102. this._isDirty = false;
  14103. // Scaling
  14104. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14105. // Rotation
  14106. //rotate, if quaternion is set and rotation was used
  14107. if (this.rotationQuaternion) {
  14108. var len = this.rotation.length();
  14109. if (len) {
  14110. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14111. this.rotation.copyFromFloats(0, 0, 0);
  14112. }
  14113. }
  14114. if (this.rotationQuaternion) {
  14115. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14116. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14117. }
  14118. else {
  14119. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14120. this._cache.rotation.copyFrom(this.rotation);
  14121. }
  14122. // Translation
  14123. var camera = this.getScene().activeCamera;
  14124. if (this.infiniteDistance && !this.parent && camera) {
  14125. var cameraWorldMatrix = camera.getWorldMatrix();
  14126. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14127. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14128. }
  14129. else {
  14130. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14131. }
  14132. // Composing transformations
  14133. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14134. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14135. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14136. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14137. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14138. // Need to decompose each rotation here
  14139. var currentPosition = BABYLON.Tmp.Vector3[3];
  14140. if (this.parent && this.parent.getWorldMatrix) {
  14141. if (this._meshToBoneReferal) {
  14142. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14143. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14144. }
  14145. else {
  14146. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14147. }
  14148. }
  14149. else {
  14150. currentPosition.copyFrom(this.position);
  14151. }
  14152. currentPosition.subtractInPlace(camera.globalPosition);
  14153. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14154. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14155. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14156. }
  14157. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14158. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14159. }
  14160. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14161. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14162. }
  14163. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14164. }
  14165. else {
  14166. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14167. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14168. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14169. }
  14170. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14171. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14172. }
  14173. // Local world
  14174. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14175. // Parent
  14176. if (this.parent && this.parent.getWorldMatrix) {
  14177. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14178. if (this._meshToBoneReferal) {
  14179. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14180. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14181. }
  14182. else {
  14183. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14184. }
  14185. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14186. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14187. this._worldMatrix.copyFrom(this._localWorld);
  14188. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14189. }
  14190. else {
  14191. if (this._meshToBoneReferal) {
  14192. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14193. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14194. }
  14195. else {
  14196. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14197. }
  14198. }
  14199. this._markSyncedWithParent();
  14200. }
  14201. else {
  14202. this._worldMatrix.copyFrom(this._localWorld);
  14203. }
  14204. // Post multiply inverse of pivotMatrix
  14205. if (this._postMultiplyPivotMatrix) {
  14206. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14207. }
  14208. // Normal matrix
  14209. if (this.scaling.isNonUniform) {
  14210. this.nonUniformScaling = true;
  14211. }
  14212. else if (this.parent && this.parent._nonUniformScaling) {
  14213. this.nonUniformScaling = this.parent._nonUniformScaling;
  14214. }
  14215. else {
  14216. this.nonUniformScaling = false;
  14217. }
  14218. // Bounding info
  14219. this._updateBoundingInfo();
  14220. // Absolute position
  14221. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14222. // Callbacks
  14223. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14224. if (!this._poseMatrix) {
  14225. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14226. }
  14227. return this._worldMatrix;
  14228. };
  14229. /**
  14230. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14231. * @param func: callback function to add
  14232. *
  14233. * Returns the AbstractMesh.
  14234. */
  14235. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14236. this.onAfterWorldMatrixUpdateObservable.add(func);
  14237. return this;
  14238. };
  14239. /**
  14240. * Removes a registered callback function.
  14241. * Returns the AbstractMesh.
  14242. */
  14243. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14244. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14245. return this;
  14246. };
  14247. /**
  14248. * Sets the mesh position in its local space.
  14249. * Returns the AbstractMesh.
  14250. */
  14251. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14252. this.computeWorldMatrix();
  14253. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14254. return this;
  14255. };
  14256. /**
  14257. * Returns the mesh position in the local space from the current World matrix values.
  14258. * Returns a new Vector3.
  14259. */
  14260. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14261. this.computeWorldMatrix();
  14262. var invLocalWorldMatrix = this._localWorld.clone();
  14263. invLocalWorldMatrix.invert();
  14264. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14265. };
  14266. /**
  14267. * Translates the mesh along the passed Vector3 in its local space.
  14268. * Returns the AbstractMesh.
  14269. */
  14270. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14271. this.computeWorldMatrix(true);
  14272. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14273. return this;
  14274. };
  14275. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14276. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14277. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14278. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14279. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14280. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14281. /// <returns>Mesh oriented towards targetMesh</returns>
  14282. if (yawCor === void 0) { yawCor = 0; }
  14283. if (pitchCor === void 0) { pitchCor = 0; }
  14284. if (rollCor === void 0) { rollCor = 0; }
  14285. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14286. var dv = AbstractMesh._lookAtVectorCache;
  14287. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14288. targetPoint.subtractToRef(pos, dv);
  14289. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14290. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14291. var pitch = Math.atan2(dv.y, len);
  14292. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14293. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14294. return this;
  14295. };
  14296. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14297. this._meshToBoneReferal = affectedMesh;
  14298. this.parent = bone;
  14299. if (bone.getWorldMatrix().determinant() < 0) {
  14300. this.scalingDeterminant *= -1;
  14301. }
  14302. return this;
  14303. };
  14304. AbstractMesh.prototype.detachFromBone = function () {
  14305. if (!this.parent) {
  14306. return this;
  14307. }
  14308. if (this.parent.getWorldMatrix().determinant() < 0) {
  14309. this.scalingDeterminant *= -1;
  14310. }
  14311. this._meshToBoneReferal = null;
  14312. this.parent = null;
  14313. return this;
  14314. };
  14315. /**
  14316. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14317. * A mesh is in the frustum if its bounding box intersects the frustum.
  14318. * Boolean returned.
  14319. */
  14320. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14321. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14322. };
  14323. /**
  14324. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14325. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14326. * Boolean returned.
  14327. */
  14328. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14329. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14330. ;
  14331. };
  14332. /**
  14333. * True if the mesh intersects another mesh or a SolidParticle object.
  14334. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  14335. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14336. * Returns a boolean.
  14337. */
  14338. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14339. if (precise === void 0) { precise = false; }
  14340. if (!this._boundingInfo || !mesh._boundingInfo) {
  14341. return false;
  14342. }
  14343. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14344. return true;
  14345. }
  14346. if (includeDescendants) {
  14347. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14348. var child = _a[_i];
  14349. if (child.intersectsMesh(mesh, precise, true)) {
  14350. return true;
  14351. }
  14352. }
  14353. }
  14354. return false;
  14355. };
  14356. /**
  14357. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14358. * Returns a boolean.
  14359. */
  14360. AbstractMesh.prototype.intersectsPoint = function (point) {
  14361. if (!this._boundingInfo) {
  14362. return false;
  14363. }
  14364. return this._boundingInfo.intersectsPoint(point);
  14365. };
  14366. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14367. return this.physicsImpostor;
  14368. };
  14369. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14370. if (camera === void 0) { camera = null; }
  14371. if (!camera) {
  14372. camera = this.getScene().activeCamera;
  14373. }
  14374. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14375. };
  14376. /**
  14377. * Returns the distance from the mesh to the active camera.
  14378. * Returns a float.
  14379. */
  14380. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14381. if (camera === void 0) { camera = null; }
  14382. if (!camera) {
  14383. camera = this.getScene().activeCamera;
  14384. }
  14385. return this.absolutePosition.subtract(camera.position).length();
  14386. };
  14387. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14388. if (!this.physicsImpostor) {
  14389. return this;
  14390. }
  14391. this.physicsImpostor.applyImpulse(force, contactPoint);
  14392. return this;
  14393. };
  14394. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14395. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14396. return this;
  14397. }
  14398. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14399. mainPivot: pivot1,
  14400. connectedPivot: pivot2,
  14401. nativeParams: options
  14402. });
  14403. return this;
  14404. };
  14405. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14406. // Collisions
  14407. /**
  14408. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14409. * Default `false`.
  14410. */
  14411. get: function () {
  14412. return this._checkCollisions;
  14413. },
  14414. set: function (collisionEnabled) {
  14415. this._checkCollisions = collisionEnabled;
  14416. if (this.getScene().workerCollisions) {
  14417. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14418. }
  14419. },
  14420. enumerable: true,
  14421. configurable: true
  14422. });
  14423. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14424. var globalPosition = this.getAbsolutePosition();
  14425. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14426. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14427. if (!this._collider) {
  14428. this._collider = new BABYLON.Collider();
  14429. }
  14430. this._collider.radius = this.ellipsoid;
  14431. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14432. return this;
  14433. };
  14434. // Submeshes octree
  14435. /**
  14436. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14437. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14438. * Returns an Octree of submeshes.
  14439. */
  14440. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14441. if (maxCapacity === void 0) { maxCapacity = 64; }
  14442. if (maxDepth === void 0) { maxDepth = 2; }
  14443. if (!this._submeshesOctree) {
  14444. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14445. }
  14446. this.computeWorldMatrix(true);
  14447. var boundingInfo = this.getBoundingInfo();
  14448. // Update octree
  14449. if (boundingInfo) {
  14450. var bbox = boundingInfo.boundingBox;
  14451. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14452. }
  14453. return this._submeshesOctree;
  14454. };
  14455. // Collisions
  14456. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14457. this._generatePointsArray();
  14458. if (!this._positions) {
  14459. return this;
  14460. }
  14461. // Transformation
  14462. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14463. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14464. subMesh._lastColliderWorldVertices = [];
  14465. subMesh._trianglePlanes = [];
  14466. var start = subMesh.verticesStart;
  14467. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14468. for (var i = start; i < end; i++) {
  14469. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14470. }
  14471. }
  14472. // Collide
  14473. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14474. if (collider.collisionFound) {
  14475. collider.collidedMesh = this;
  14476. }
  14477. return this;
  14478. };
  14479. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14480. var subMeshes;
  14481. var len;
  14482. // Octrees
  14483. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14484. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14485. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14486. len = intersections.length;
  14487. subMeshes = intersections.data;
  14488. }
  14489. else {
  14490. subMeshes = this.subMeshes;
  14491. len = subMeshes.length;
  14492. }
  14493. for (var index = 0; index < len; index++) {
  14494. var subMesh = subMeshes[index];
  14495. // Bounding test
  14496. if (len > 1 && !subMesh._checkCollision(collider))
  14497. continue;
  14498. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14499. }
  14500. return this;
  14501. };
  14502. AbstractMesh.prototype._checkCollision = function (collider) {
  14503. // Bounding box test
  14504. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14505. return this;
  14506. // Transformation matrix
  14507. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14508. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14509. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14510. return this;
  14511. };
  14512. // Picking
  14513. AbstractMesh.prototype._generatePointsArray = function () {
  14514. return false;
  14515. };
  14516. /**
  14517. * Checks if the passed Ray intersects with the mesh.
  14518. * Returns an object PickingInfo.
  14519. */
  14520. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14521. var pickingInfo = new BABYLON.PickingInfo();
  14522. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14523. return pickingInfo;
  14524. }
  14525. if (!this._generatePointsArray()) {
  14526. return pickingInfo;
  14527. }
  14528. var intersectInfo = null;
  14529. // Octrees
  14530. var subMeshes;
  14531. var len;
  14532. if (this._submeshesOctree && this.useOctreeForPicking) {
  14533. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14534. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14535. len = intersections.length;
  14536. subMeshes = intersections.data;
  14537. }
  14538. else {
  14539. subMeshes = this.subMeshes;
  14540. len = subMeshes.length;
  14541. }
  14542. for (var index = 0; index < len; index++) {
  14543. var subMesh = subMeshes[index];
  14544. // Bounding test
  14545. if (len > 1 && !subMesh.canIntersects(ray))
  14546. continue;
  14547. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14548. if (currentIntersectInfo) {
  14549. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14550. intersectInfo = currentIntersectInfo;
  14551. intersectInfo.subMeshId = index;
  14552. if (fastCheck) {
  14553. break;
  14554. }
  14555. }
  14556. }
  14557. }
  14558. if (intersectInfo) {
  14559. // Get picked point
  14560. var world = this.getWorldMatrix();
  14561. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14562. var direction = ray.direction.clone();
  14563. direction = direction.scale(intersectInfo.distance);
  14564. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14565. var pickedPoint = worldOrigin.add(worldDirection);
  14566. // Return result
  14567. pickingInfo.hit = true;
  14568. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14569. pickingInfo.pickedPoint = pickedPoint;
  14570. pickingInfo.pickedMesh = this;
  14571. pickingInfo.bu = intersectInfo.bu || 0;
  14572. pickingInfo.bv = intersectInfo.bv || 0;
  14573. pickingInfo.faceId = intersectInfo.faceId;
  14574. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14575. return pickingInfo;
  14576. }
  14577. return pickingInfo;
  14578. };
  14579. /**
  14580. * Clones the mesh, used by the class Mesh.
  14581. * Just returns `null` for an AbstractMesh.
  14582. */
  14583. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14584. return null;
  14585. };
  14586. /**
  14587. * Disposes all the mesh submeshes.
  14588. * Returns the AbstractMesh.
  14589. */
  14590. AbstractMesh.prototype.releaseSubMeshes = function () {
  14591. if (this.subMeshes) {
  14592. while (this.subMeshes.length) {
  14593. this.subMeshes[0].dispose();
  14594. }
  14595. }
  14596. else {
  14597. this.subMeshes = new Array();
  14598. }
  14599. return this;
  14600. };
  14601. /**
  14602. * Disposes the AbstractMesh.
  14603. * Some internal references are kept for further use.
  14604. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14605. * Returns nothing.
  14606. */
  14607. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14608. var _this = this;
  14609. var index;
  14610. // Action manager
  14611. if (this.actionManager) {
  14612. this.actionManager.dispose();
  14613. this.actionManager = null;
  14614. }
  14615. // Skeleton
  14616. this.skeleton = null;
  14617. // Animations
  14618. this.getScene().stopAnimation(this);
  14619. // Physics
  14620. if (this.physicsImpostor) {
  14621. this.physicsImpostor.dispose();
  14622. }
  14623. // Intersections in progress
  14624. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14625. var other = this._intersectionsInProgress[index];
  14626. var pos = other._intersectionsInProgress.indexOf(this);
  14627. other._intersectionsInProgress.splice(pos, 1);
  14628. }
  14629. this._intersectionsInProgress = [];
  14630. // Lights
  14631. var lights = this.getScene().lights;
  14632. lights.forEach(function (light) {
  14633. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14634. if (meshIndex !== -1) {
  14635. light.includedOnlyMeshes.splice(meshIndex, 1);
  14636. }
  14637. meshIndex = light.excludedMeshes.indexOf(_this);
  14638. if (meshIndex !== -1) {
  14639. light.excludedMeshes.splice(meshIndex, 1);
  14640. }
  14641. // Shadow generators
  14642. var generator = light.getShadowGenerator();
  14643. if (generator) {
  14644. var shadowMap = generator.getShadowMap();
  14645. if (shadowMap && shadowMap.renderList) {
  14646. meshIndex = shadowMap.renderList.indexOf(_this);
  14647. if (meshIndex !== -1) {
  14648. shadowMap.renderList.splice(meshIndex, 1);
  14649. }
  14650. }
  14651. }
  14652. });
  14653. // Edges
  14654. if (this._edgesRenderer) {
  14655. this._edgesRenderer.dispose();
  14656. this._edgesRenderer = null;
  14657. }
  14658. // SubMeshes
  14659. if (this.getClassName() !== "InstancedMesh") {
  14660. this.releaseSubMeshes();
  14661. }
  14662. // Octree
  14663. var sceneOctree = this.getScene().selectionOctree;
  14664. if (sceneOctree) {
  14665. var index = sceneOctree.dynamicContent.indexOf(this);
  14666. if (index !== -1) {
  14667. sceneOctree.dynamicContent.splice(index, 1);
  14668. }
  14669. }
  14670. // Query
  14671. var engine = this.getScene().getEngine();
  14672. if (this._occlusionQuery) {
  14673. this._isOcclusionQueryInProgress = false;
  14674. engine.deleteQuery(this._occlusionQuery);
  14675. this._occlusionQuery = null;
  14676. }
  14677. // Engine
  14678. engine.wipeCaches();
  14679. // Remove from scene
  14680. this.getScene().removeMesh(this);
  14681. if (!doNotRecurse) {
  14682. // Particles
  14683. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14684. if (this.getScene().particleSystems[index].emitter === this) {
  14685. this.getScene().particleSystems[index].dispose();
  14686. index--;
  14687. }
  14688. }
  14689. // Children
  14690. var objects = this.getDescendants(true);
  14691. for (index = 0; index < objects.length; index++) {
  14692. objects[index].dispose();
  14693. }
  14694. }
  14695. else {
  14696. var childMeshes = this.getChildMeshes(true);
  14697. for (index = 0; index < childMeshes.length; index++) {
  14698. var child = childMeshes[index];
  14699. child.parent = null;
  14700. child.computeWorldMatrix(true);
  14701. }
  14702. }
  14703. // facet data
  14704. if (this._facetDataEnabled) {
  14705. this.disableFacetData();
  14706. }
  14707. this.onAfterWorldMatrixUpdateObservable.clear();
  14708. this.onCollideObservable.clear();
  14709. this.onCollisionPositionChangeObservable.clear();
  14710. this._isDisposed = true;
  14711. _super.prototype.dispose.call(this);
  14712. };
  14713. /**
  14714. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14715. * This Vector3 is expressed in the World space.
  14716. */
  14717. AbstractMesh.prototype.getDirection = function (localAxis) {
  14718. var result = BABYLON.Vector3.Zero();
  14719. this.getDirectionToRef(localAxis, result);
  14720. return result;
  14721. };
  14722. /**
  14723. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14724. * localAxis is expressed in the mesh local space.
  14725. * result is computed in the Wordl space from the mesh World matrix.
  14726. * Returns the AbstractMesh.
  14727. */
  14728. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14729. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14730. return this;
  14731. };
  14732. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14733. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14734. if (this.getScene().getRenderId() == 0) {
  14735. this.computeWorldMatrix(true);
  14736. }
  14737. var wm = this.getWorldMatrix();
  14738. if (space == BABYLON.Space.WORLD) {
  14739. var tmat = BABYLON.Tmp.Matrix[0];
  14740. wm.invertToRef(tmat);
  14741. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14742. }
  14743. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14744. this._pivotMatrix.m[12] = -point.x;
  14745. this._pivotMatrix.m[13] = -point.y;
  14746. this._pivotMatrix.m[14] = -point.z;
  14747. this._cache.pivotMatrixUpdated = true;
  14748. return this;
  14749. };
  14750. /**
  14751. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14752. */
  14753. AbstractMesh.prototype.getPivotPoint = function () {
  14754. var point = BABYLON.Vector3.Zero();
  14755. this.getPivotPointToRef(point);
  14756. return point;
  14757. };
  14758. /**
  14759. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14760. * Returns the AbstractMesh.
  14761. */
  14762. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14763. result.x = -this._pivotMatrix.m[12];
  14764. result.y = -this._pivotMatrix.m[13];
  14765. result.z = -this._pivotMatrix.m[14];
  14766. return this;
  14767. };
  14768. /**
  14769. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14770. */
  14771. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14772. var point = BABYLON.Vector3.Zero();
  14773. this.getAbsolutePivotPointToRef(point);
  14774. return point;
  14775. };
  14776. /**
  14777. * Defines the passed mesh as the parent of the current mesh.
  14778. * Returns the AbstractMesh.
  14779. */
  14780. AbstractMesh.prototype.setParent = function (mesh) {
  14781. var parent = mesh;
  14782. if (mesh == null) {
  14783. var rotation = BABYLON.Tmp.Quaternion[0];
  14784. var position = BABYLON.Tmp.Vector3[0];
  14785. var scale = BABYLON.Tmp.Vector3[1];
  14786. this.getWorldMatrix().decompose(scale, rotation, position);
  14787. if (this.rotationQuaternion) {
  14788. this.rotationQuaternion.copyFrom(rotation);
  14789. }
  14790. else {
  14791. rotation.toEulerAnglesToRef(this.rotation);
  14792. }
  14793. this.position.x = position.x;
  14794. this.position.y = position.y;
  14795. this.position.z = position.z;
  14796. }
  14797. else {
  14798. var position = BABYLON.Tmp.Vector3[0];
  14799. var m1 = BABYLON.Tmp.Matrix[0];
  14800. parent.getWorldMatrix().invertToRef(m1);
  14801. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14802. this.position.copyFrom(position);
  14803. }
  14804. this.parent = parent;
  14805. return this;
  14806. };
  14807. /**
  14808. * Adds the passed mesh as a child to the current mesh.
  14809. * Returns the AbstractMesh.
  14810. */
  14811. AbstractMesh.prototype.addChild = function (mesh) {
  14812. mesh.setParent(this);
  14813. return this;
  14814. };
  14815. /**
  14816. * Removes the passed mesh from the current mesh children list.
  14817. * Returns the AbstractMesh.
  14818. */
  14819. AbstractMesh.prototype.removeChild = function (mesh) {
  14820. mesh.setParent(null);
  14821. return this;
  14822. };
  14823. /**
  14824. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14825. * Returns the AbstractMesh.
  14826. */
  14827. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14828. result.x = this._pivotMatrix.m[12];
  14829. result.y = this._pivotMatrix.m[13];
  14830. result.z = this._pivotMatrix.m[14];
  14831. this.getPivotPointToRef(result);
  14832. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14833. return this;
  14834. };
  14835. // Facet data
  14836. /**
  14837. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14838. * Returns the AbstractMesh.
  14839. */
  14840. AbstractMesh.prototype._initFacetData = function () {
  14841. if (!this._facetNormals) {
  14842. this._facetNormals = new Array();
  14843. }
  14844. if (!this._facetPositions) {
  14845. this._facetPositions = new Array();
  14846. }
  14847. if (!this._facetPartitioning) {
  14848. this._facetPartitioning = new Array();
  14849. }
  14850. this._facetNb = this.getIndices().length / 3;
  14851. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14852. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14853. for (var f = 0; f < this._facetNb; f++) {
  14854. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14855. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14856. }
  14857. this._facetDataEnabled = true;
  14858. return this;
  14859. };
  14860. /**
  14861. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14862. * This method can be called within the render loop.
  14863. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  14864. * Returns the AbstractMesh.
  14865. */
  14866. AbstractMesh.prototype.updateFacetData = function () {
  14867. if (!this._facetDataEnabled) {
  14868. this._initFacetData();
  14869. }
  14870. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14871. var indices = this.getIndices();
  14872. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14873. var bInfo = this.getBoundingInfo();
  14874. if (!bInfo) {
  14875. return this;
  14876. }
  14877. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14878. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14879. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14880. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14881. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14882. this._subDiv.max = this._partitioningSubdivisions;
  14883. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14884. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14885. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14886. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14887. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14888. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14889. // set the parameters for ComputeNormals()
  14890. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14891. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14892. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14893. this._facetParameters.bInfo = bInfo;
  14894. this._facetParameters.bbSize = this._bbSize;
  14895. this._facetParameters.subDiv = this._subDiv;
  14896. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14897. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14898. return this;
  14899. };
  14900. /**
  14901. * Returns the facetLocalNormals array.
  14902. * The normals are expressed in the mesh local space.
  14903. */
  14904. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14905. if (!this._facetNormals) {
  14906. this.updateFacetData();
  14907. }
  14908. return this._facetNormals;
  14909. };
  14910. /**
  14911. * Returns the facetLocalPositions array.
  14912. * The facet positions are expressed in the mesh local space.
  14913. */
  14914. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14915. if (!this._facetPositions) {
  14916. this.updateFacetData();
  14917. }
  14918. return this._facetPositions;
  14919. };
  14920. /**
  14921. * Returns the facetLocalPartioning array.
  14922. */
  14923. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14924. if (!this._facetPartitioning) {
  14925. this.updateFacetData();
  14926. }
  14927. return this._facetPartitioning;
  14928. };
  14929. /**
  14930. * Returns the i-th facet position in the world system.
  14931. * This method allocates a new Vector3 per call.
  14932. */
  14933. AbstractMesh.prototype.getFacetPosition = function (i) {
  14934. var pos = BABYLON.Vector3.Zero();
  14935. this.getFacetPositionToRef(i, pos);
  14936. return pos;
  14937. };
  14938. /**
  14939. * Sets the reference Vector3 with the i-th facet position in the world system.
  14940. * Returns the AbstractMesh.
  14941. */
  14942. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14943. var localPos = (this.getFacetLocalPositions())[i];
  14944. var world = this.getWorldMatrix();
  14945. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14946. return this;
  14947. };
  14948. /**
  14949. * Returns the i-th facet normal in the world system.
  14950. * This method allocates a new Vector3 per call.
  14951. */
  14952. AbstractMesh.prototype.getFacetNormal = function (i) {
  14953. var norm = BABYLON.Vector3.Zero();
  14954. this.getFacetNormalToRef(i, norm);
  14955. return norm;
  14956. };
  14957. /**
  14958. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14959. * Returns the AbstractMesh.
  14960. */
  14961. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14962. var localNorm = (this.getFacetLocalNormals())[i];
  14963. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14964. return this;
  14965. };
  14966. /**
  14967. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  14968. */
  14969. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14970. var bInfo = this.getBoundingInfo();
  14971. if (!bInfo) {
  14972. return null;
  14973. }
  14974. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14975. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14976. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14977. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14978. return null;
  14979. }
  14980. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14981. };
  14982. /**
  14983. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14984. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14985. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  14986. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14987. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  14988. */
  14989. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14990. if (checkFace === void 0) { checkFace = false; }
  14991. if (facing === void 0) { facing = true; }
  14992. var world = this.getWorldMatrix();
  14993. var invMat = BABYLON.Tmp.Matrix[5];
  14994. world.invertToRef(invMat);
  14995. var invVect = BABYLON.Tmp.Vector3[8];
  14996. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14997. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14998. if (projected) {
  14999. // tranform the local computed projected vector to world coordinates
  15000. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15001. }
  15002. return closest;
  15003. };
  15004. /**
  15005. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15006. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15007. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  15008. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15009. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  15010. */
  15011. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15012. if (checkFace === void 0) { checkFace = false; }
  15013. if (facing === void 0) { facing = true; }
  15014. var closest = null;
  15015. var tmpx = 0.0;
  15016. var tmpy = 0.0;
  15017. var tmpz = 0.0;
  15018. var d = 0.0; // tmp dot facet normal * facet position
  15019. var t0 = 0.0;
  15020. var projx = 0.0;
  15021. var projy = 0.0;
  15022. var projz = 0.0;
  15023. // Get all the facets in the same partitioning block than (x, y, z)
  15024. var facetPositions = this.getFacetLocalPositions();
  15025. var facetNormals = this.getFacetLocalNormals();
  15026. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15027. if (!facetsInBlock) {
  15028. return null;
  15029. }
  15030. // Get the closest facet to (x, y, z)
  15031. var shortest = Number.MAX_VALUE; // init distance vars
  15032. var tmpDistance = shortest;
  15033. var fib; // current facet in the block
  15034. var norm; // current facet normal
  15035. var p0; // current facet barycenter position
  15036. // loop on all the facets in the current partitioning block
  15037. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15038. fib = facetsInBlock[idx];
  15039. norm = facetNormals[fib];
  15040. p0 = facetPositions[fib];
  15041. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15042. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15043. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15044. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15045. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15046. projx = x + norm.x * t0;
  15047. projy = y + norm.y * t0;
  15048. projz = z + norm.z * t0;
  15049. tmpx = projx - x;
  15050. tmpy = projy - y;
  15051. tmpz = projz - z;
  15052. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15053. if (tmpDistance < shortest) {
  15054. shortest = tmpDistance;
  15055. closest = fib;
  15056. if (projected) {
  15057. projected.x = projx;
  15058. projected.y = projy;
  15059. projected.z = projz;
  15060. }
  15061. }
  15062. }
  15063. }
  15064. return closest;
  15065. };
  15066. /**
  15067. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15068. */
  15069. AbstractMesh.prototype.getFacetDataParameters = function () {
  15070. return this._facetParameters;
  15071. };
  15072. /**
  15073. * Disables the feature FacetData and frees the related memory.
  15074. * Returns the AbstractMesh.
  15075. */
  15076. AbstractMesh.prototype.disableFacetData = function () {
  15077. if (this._facetDataEnabled) {
  15078. this._facetDataEnabled = false;
  15079. this._facetPositions = new Array();
  15080. ;
  15081. this._facetNormals = new Array();
  15082. ;
  15083. this._facetPartitioning = new Array();
  15084. ;
  15085. this._facetParameters = null;
  15086. }
  15087. return this;
  15088. };
  15089. /**
  15090. * Creates new normals data for the mesh.
  15091. * @param updatable.
  15092. */
  15093. AbstractMesh.prototype.createNormals = function (updatable) {
  15094. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15095. var indices = this.getIndices();
  15096. var normals;
  15097. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15098. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15099. }
  15100. else {
  15101. normals = [];
  15102. }
  15103. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15104. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15105. };
  15106. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15107. var engine = this.getEngine();
  15108. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15109. this._isOccluded = false;
  15110. return;
  15111. }
  15112. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15113. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15114. if (isOcclusionQueryAvailable) {
  15115. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15116. this._isOcclusionQueryInProgress = false;
  15117. this._occlusionInternalRetryCounter = 0;
  15118. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15119. }
  15120. else {
  15121. this._occlusionInternalRetryCounter++;
  15122. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15123. this._isOcclusionQueryInProgress = false;
  15124. this._occlusionInternalRetryCounter = 0;
  15125. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15126. // if strict continue the last state of the object.
  15127. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15128. }
  15129. else {
  15130. return;
  15131. }
  15132. }
  15133. }
  15134. var scene = this.getScene();
  15135. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15136. if (!this._occlusionQuery) {
  15137. this._occlusionQuery = engine.createQuery();
  15138. }
  15139. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15140. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15141. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15142. this._isOcclusionQueryInProgress = true;
  15143. };
  15144. // Statics
  15145. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15146. AbstractMesh._BILLBOARDMODE_X = 1;
  15147. AbstractMesh._BILLBOARDMODE_Y = 2;
  15148. AbstractMesh._BILLBOARDMODE_Z = 4;
  15149. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15150. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15151. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15152. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15153. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15154. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15155. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15156. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15157. return AbstractMesh;
  15158. }(BABYLON.Node));
  15159. BABYLON.AbstractMesh = AbstractMesh;
  15160. })(BABYLON || (BABYLON = {}));
  15161. //# sourceMappingURL=babylon.abstractMesh.js.map
  15162. var BABYLON;
  15163. (function (BABYLON) {
  15164. var Light = /** @class */ (function (_super) {
  15165. __extends(Light, _super);
  15166. /**
  15167. * Creates a Light object in the scene.
  15168. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15169. */
  15170. function Light(name, scene) {
  15171. var _this = _super.call(this, name, scene) || this;
  15172. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15173. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15174. _this.intensity = 1.0;
  15175. _this.range = Number.MAX_VALUE;
  15176. /**
  15177. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15178. * of light.
  15179. */
  15180. _this._photometricScale = 1.0;
  15181. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15182. _this._radius = 0.00001;
  15183. _this.renderPriority = 0;
  15184. /**
  15185. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15186. * the current shadow generator.
  15187. */
  15188. _this.shadowEnabled = true;
  15189. _this._excludeWithLayerMask = 0;
  15190. _this._includeOnlyWithLayerMask = 0;
  15191. _this._lightmapMode = 0;
  15192. _this._excludedMeshesIds = new Array();
  15193. _this._includedOnlyMeshesIds = new Array();
  15194. _this.getScene().addLight(_this);
  15195. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15196. _this._buildUniformLayout();
  15197. _this.includedOnlyMeshes = new Array();
  15198. _this.excludedMeshes = new Array();
  15199. _this._resyncMeshes();
  15200. return _this;
  15201. }
  15202. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15203. /**
  15204. * If every light affecting the material is in this lightmapMode,
  15205. * material.lightmapTexture adds or multiplies
  15206. * (depends on material.useLightmapAsShadowmap)
  15207. * after every other light calculations.
  15208. */
  15209. get: function () {
  15210. return Light._LIGHTMAP_DEFAULT;
  15211. },
  15212. enumerable: true,
  15213. configurable: true
  15214. });
  15215. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15216. /**
  15217. * material.lightmapTexture as only diffuse lighting from this light
  15218. * adds pnly specular lighting from this light
  15219. * adds dynamic shadows
  15220. */
  15221. get: function () {
  15222. return Light._LIGHTMAP_SPECULAR;
  15223. },
  15224. enumerable: true,
  15225. configurable: true
  15226. });
  15227. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15228. /**
  15229. * material.lightmapTexture as only lighting
  15230. * no light calculation from this light
  15231. * only adds dynamic shadows from this light
  15232. */
  15233. get: function () {
  15234. return Light._LIGHTMAP_SHADOWSONLY;
  15235. },
  15236. enumerable: true,
  15237. configurable: true
  15238. });
  15239. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15240. /**
  15241. * Each light type uses the default quantity according to its type:
  15242. * point/spot lights use luminous intensity
  15243. * directional lights use illuminance
  15244. */
  15245. get: function () {
  15246. return Light._INTENSITYMODE_AUTOMATIC;
  15247. },
  15248. enumerable: true,
  15249. configurable: true
  15250. });
  15251. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15252. /**
  15253. * lumen (lm)
  15254. */
  15255. get: function () {
  15256. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15257. },
  15258. enumerable: true,
  15259. configurable: true
  15260. });
  15261. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15262. /**
  15263. * candela (lm/sr)
  15264. */
  15265. get: function () {
  15266. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15267. },
  15268. enumerable: true,
  15269. configurable: true
  15270. });
  15271. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15272. /**
  15273. * lux (lm/m^2)
  15274. */
  15275. get: function () {
  15276. return Light._INTENSITYMODE_ILLUMINANCE;
  15277. },
  15278. enumerable: true,
  15279. configurable: true
  15280. });
  15281. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15282. /**
  15283. * nit (cd/m^2)
  15284. */
  15285. get: function () {
  15286. return Light._INTENSITYMODE_LUMINANCE;
  15287. },
  15288. enumerable: true,
  15289. configurable: true
  15290. });
  15291. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15292. /**
  15293. * Light type const id of the point light.
  15294. */
  15295. get: function () {
  15296. return Light._LIGHTTYPEID_POINTLIGHT;
  15297. },
  15298. enumerable: true,
  15299. configurable: true
  15300. });
  15301. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15302. /**
  15303. * Light type const id of the directional light.
  15304. */
  15305. get: function () {
  15306. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15307. },
  15308. enumerable: true,
  15309. configurable: true
  15310. });
  15311. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15312. /**
  15313. * Light type const id of the spot light.
  15314. */
  15315. get: function () {
  15316. return Light._LIGHTTYPEID_SPOTLIGHT;
  15317. },
  15318. enumerable: true,
  15319. configurable: true
  15320. });
  15321. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15322. /**
  15323. * Light type const id of the hemispheric light.
  15324. */
  15325. get: function () {
  15326. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15327. },
  15328. enumerable: true,
  15329. configurable: true
  15330. });
  15331. Object.defineProperty(Light.prototype, "intensityMode", {
  15332. /**
  15333. * Gets the photometric scale used to interpret the intensity.
  15334. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15335. */
  15336. get: function () {
  15337. return this._intensityMode;
  15338. },
  15339. /**
  15340. * Sets the photometric scale used to interpret the intensity.
  15341. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15342. */
  15343. set: function (value) {
  15344. this._intensityMode = value;
  15345. this._computePhotometricScale();
  15346. },
  15347. enumerable: true,
  15348. configurable: true
  15349. });
  15350. ;
  15351. ;
  15352. Object.defineProperty(Light.prototype, "radius", {
  15353. /**
  15354. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15355. */
  15356. get: function () {
  15357. return this._radius;
  15358. },
  15359. /**
  15360. * sets the light radius used by PBR Materials to simulate soft area lights.
  15361. */
  15362. set: function (value) {
  15363. this._radius = value;
  15364. this._computePhotometricScale();
  15365. },
  15366. enumerable: true,
  15367. configurable: true
  15368. });
  15369. ;
  15370. ;
  15371. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15372. get: function () {
  15373. return this._includedOnlyMeshes;
  15374. },
  15375. set: function (value) {
  15376. this._includedOnlyMeshes = value;
  15377. this._hookArrayForIncludedOnly(value);
  15378. },
  15379. enumerable: true,
  15380. configurable: true
  15381. });
  15382. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15383. get: function () {
  15384. return this._excludedMeshes;
  15385. },
  15386. set: function (value) {
  15387. this._excludedMeshes = value;
  15388. this._hookArrayForExcluded(value);
  15389. },
  15390. enumerable: true,
  15391. configurable: true
  15392. });
  15393. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15394. get: function () {
  15395. return this._excludeWithLayerMask;
  15396. },
  15397. set: function (value) {
  15398. this._excludeWithLayerMask = value;
  15399. this._resyncMeshes();
  15400. },
  15401. enumerable: true,
  15402. configurable: true
  15403. });
  15404. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15405. get: function () {
  15406. return this._includeOnlyWithLayerMask;
  15407. },
  15408. set: function (value) {
  15409. this._includeOnlyWithLayerMask = value;
  15410. this._resyncMeshes();
  15411. },
  15412. enumerable: true,
  15413. configurable: true
  15414. });
  15415. Object.defineProperty(Light.prototype, "lightmapMode", {
  15416. get: function () {
  15417. return this._lightmapMode;
  15418. },
  15419. set: function (value) {
  15420. if (this._lightmapMode === value) {
  15421. return;
  15422. }
  15423. this._lightmapMode = value;
  15424. this._markMeshesAsLightDirty();
  15425. },
  15426. enumerable: true,
  15427. configurable: true
  15428. });
  15429. Light.prototype._buildUniformLayout = function () {
  15430. // Overridden
  15431. };
  15432. /**
  15433. * Returns the string "Light".
  15434. */
  15435. Light.prototype.getClassName = function () {
  15436. return "Light";
  15437. };
  15438. /**
  15439. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15440. */
  15441. Light.prototype.toString = function (fullDetails) {
  15442. var ret = "Name: " + this.name;
  15443. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15444. if (this.animations) {
  15445. for (var i = 0; i < this.animations.length; i++) {
  15446. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15447. }
  15448. }
  15449. if (fullDetails) {
  15450. }
  15451. return ret;
  15452. };
  15453. /**
  15454. * Set the enabled state of this node.
  15455. * @param {boolean} value - the new enabled state
  15456. * @see isEnabled
  15457. */
  15458. Light.prototype.setEnabled = function (value) {
  15459. _super.prototype.setEnabled.call(this, value);
  15460. this._resyncMeshes();
  15461. };
  15462. /**
  15463. * Returns the Light associated shadow generator.
  15464. */
  15465. Light.prototype.getShadowGenerator = function () {
  15466. return this._shadowGenerator;
  15467. };
  15468. /**
  15469. * Returns a Vector3, the absolute light position in the World.
  15470. */
  15471. Light.prototype.getAbsolutePosition = function () {
  15472. return BABYLON.Vector3.Zero();
  15473. };
  15474. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15475. };
  15476. Light.prototype._getWorldMatrix = function () {
  15477. return BABYLON.Matrix.Identity();
  15478. };
  15479. /**
  15480. * Boolean : True if the light will affect the passed mesh.
  15481. */
  15482. Light.prototype.canAffectMesh = function (mesh) {
  15483. if (!mesh) {
  15484. return true;
  15485. }
  15486. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15487. return false;
  15488. }
  15489. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15490. return false;
  15491. }
  15492. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15493. return false;
  15494. }
  15495. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15496. return false;
  15497. }
  15498. return true;
  15499. };
  15500. /**
  15501. * Returns the light World matrix.
  15502. */
  15503. Light.prototype.getWorldMatrix = function () {
  15504. this._currentRenderId = this.getScene().getRenderId();
  15505. var worldMatrix = this._getWorldMatrix();
  15506. if (this.parent && this.parent.getWorldMatrix) {
  15507. if (!this._parentedWorldMatrix) {
  15508. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15509. }
  15510. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15511. this._markSyncedWithParent();
  15512. return this._parentedWorldMatrix;
  15513. }
  15514. return worldMatrix;
  15515. };
  15516. /**
  15517. * Sort function to order lights for rendering.
  15518. * @param a First Light object to compare to second.
  15519. * @param b Second Light object to compare first.
  15520. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15521. */
  15522. Light.compareLightsPriority = function (a, b) {
  15523. //shadow-casting lights have priority over non-shadow-casting lights
  15524. //the renderPrioirty is a secondary sort criterion
  15525. if (a.shadowEnabled !== b.shadowEnabled) {
  15526. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15527. }
  15528. return b.renderPriority - a.renderPriority;
  15529. };
  15530. /**
  15531. * Disposes the light.
  15532. */
  15533. Light.prototype.dispose = function () {
  15534. if (this._shadowGenerator) {
  15535. this._shadowGenerator.dispose();
  15536. this._shadowGenerator = null;
  15537. }
  15538. // Animations
  15539. this.getScene().stopAnimation(this);
  15540. // Remove from meshes
  15541. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15542. var mesh = _a[_i];
  15543. mesh._removeLightSource(this);
  15544. }
  15545. this._uniformBuffer.dispose();
  15546. // Remove from scene
  15547. this.getScene().removeLight(this);
  15548. _super.prototype.dispose.call(this);
  15549. };
  15550. /**
  15551. * Returns the light type ID (integer).
  15552. */
  15553. Light.prototype.getTypeID = function () {
  15554. return 0;
  15555. };
  15556. /**
  15557. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15558. */
  15559. Light.prototype.getScaledIntensity = function () {
  15560. return this._photometricScale * this.intensity;
  15561. };
  15562. /**
  15563. * Returns a new Light object, named "name", from the current one.
  15564. */
  15565. Light.prototype.clone = function (name) {
  15566. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15567. if (!constructor) {
  15568. return null;
  15569. }
  15570. return BABYLON.SerializationHelper.Clone(constructor, this);
  15571. };
  15572. /**
  15573. * Serializes the current light into a Serialization object.
  15574. * Returns the serialized object.
  15575. */
  15576. Light.prototype.serialize = function () {
  15577. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15578. // Type
  15579. serializationObject.type = this.getTypeID();
  15580. // Parent
  15581. if (this.parent) {
  15582. serializationObject.parentId = this.parent.id;
  15583. }
  15584. // Inclusion / exclusions
  15585. if (this.excludedMeshes.length > 0) {
  15586. serializationObject.excludedMeshesIds = [];
  15587. this.excludedMeshes.forEach(function (mesh) {
  15588. serializationObject.excludedMeshesIds.push(mesh.id);
  15589. });
  15590. }
  15591. if (this.includedOnlyMeshes.length > 0) {
  15592. serializationObject.includedOnlyMeshesIds = [];
  15593. this.includedOnlyMeshes.forEach(function (mesh) {
  15594. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15595. });
  15596. }
  15597. // Animations
  15598. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15599. serializationObject.ranges = this.serializeAnimationRanges();
  15600. return serializationObject;
  15601. };
  15602. /**
  15603. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15604. * This new light is named "name" and added to the passed scene.
  15605. */
  15606. Light.GetConstructorFromName = function (type, name, scene) {
  15607. switch (type) {
  15608. case 0:
  15609. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15610. case 1:
  15611. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15612. case 2:
  15613. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15614. case 3:
  15615. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15616. }
  15617. return null;
  15618. };
  15619. /**
  15620. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15621. */
  15622. Light.Parse = function (parsedLight, scene) {
  15623. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15624. if (!constructor) {
  15625. return null;
  15626. }
  15627. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15628. // Inclusion / exclusions
  15629. if (parsedLight.excludedMeshesIds) {
  15630. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15631. }
  15632. if (parsedLight.includedOnlyMeshesIds) {
  15633. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15634. }
  15635. // Parent
  15636. if (parsedLight.parentId) {
  15637. light._waitingParentId = parsedLight.parentId;
  15638. }
  15639. // Animations
  15640. if (parsedLight.animations) {
  15641. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15642. var parsedAnimation = parsedLight.animations[animationIndex];
  15643. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15644. }
  15645. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15646. }
  15647. if (parsedLight.autoAnimate) {
  15648. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15649. }
  15650. return light;
  15651. };
  15652. Light.prototype._hookArrayForExcluded = function (array) {
  15653. var _this = this;
  15654. var oldPush = array.push;
  15655. array.push = function () {
  15656. var items = [];
  15657. for (var _i = 0; _i < arguments.length; _i++) {
  15658. items[_i] = arguments[_i];
  15659. }
  15660. var result = oldPush.apply(array, items);
  15661. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15662. var item = items_1[_a];
  15663. item._resyncLighSource(_this);
  15664. }
  15665. return result;
  15666. };
  15667. var oldSplice = array.splice;
  15668. array.splice = function (index, deleteCount) {
  15669. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15670. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15671. var item = deleted_1[_i];
  15672. item._resyncLighSource(_this);
  15673. }
  15674. return deleted;
  15675. };
  15676. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15677. var item = array_1[_i];
  15678. item._resyncLighSource(this);
  15679. }
  15680. };
  15681. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15682. var _this = this;
  15683. var oldPush = array.push;
  15684. array.push = function () {
  15685. var items = [];
  15686. for (var _i = 0; _i < arguments.length; _i++) {
  15687. items[_i] = arguments[_i];
  15688. }
  15689. var result = oldPush.apply(array, items);
  15690. _this._resyncMeshes();
  15691. return result;
  15692. };
  15693. var oldSplice = array.splice;
  15694. array.splice = function (index, deleteCount) {
  15695. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15696. _this._resyncMeshes();
  15697. return deleted;
  15698. };
  15699. this._resyncMeshes();
  15700. };
  15701. Light.prototype._resyncMeshes = function () {
  15702. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15703. var mesh = _a[_i];
  15704. mesh._resyncLighSource(this);
  15705. }
  15706. };
  15707. Light.prototype._markMeshesAsLightDirty = function () {
  15708. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15709. var mesh = _a[_i];
  15710. if (mesh._lightSources.indexOf(this) !== -1) {
  15711. mesh._markSubMeshesAsLightDirty();
  15712. }
  15713. }
  15714. };
  15715. /**
  15716. * Recomputes the cached photometric scale if needed.
  15717. */
  15718. Light.prototype._computePhotometricScale = function () {
  15719. this._photometricScale = this._getPhotometricScale();
  15720. this.getScene().resetCachedMaterial();
  15721. };
  15722. /**
  15723. * Returns the Photometric Scale according to the light type and intensity mode.
  15724. */
  15725. Light.prototype._getPhotometricScale = function () {
  15726. var photometricScale = 0.0;
  15727. var lightTypeID = this.getTypeID();
  15728. //get photometric mode
  15729. var photometricMode = this.intensityMode;
  15730. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15731. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15732. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15733. }
  15734. else {
  15735. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15736. }
  15737. }
  15738. //compute photometric scale
  15739. switch (lightTypeID) {
  15740. case Light.LIGHTTYPEID_POINTLIGHT:
  15741. case Light.LIGHTTYPEID_SPOTLIGHT:
  15742. switch (photometricMode) {
  15743. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15744. photometricScale = 1.0 / (4.0 * Math.PI);
  15745. break;
  15746. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15747. photometricScale = 1.0;
  15748. break;
  15749. case Light.INTENSITYMODE_LUMINANCE:
  15750. photometricScale = this.radius * this.radius;
  15751. break;
  15752. }
  15753. break;
  15754. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15755. switch (photometricMode) {
  15756. case Light.INTENSITYMODE_ILLUMINANCE:
  15757. photometricScale = 1.0;
  15758. break;
  15759. case Light.INTENSITYMODE_LUMINANCE:
  15760. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15761. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15762. var apexAngleRadians = this.radius;
  15763. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15764. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15765. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15766. photometricScale = solidAngle;
  15767. break;
  15768. }
  15769. break;
  15770. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15771. // No fall off in hemisperic light.
  15772. photometricScale = 1.0;
  15773. break;
  15774. }
  15775. return photometricScale;
  15776. };
  15777. Light.prototype._reorderLightsInScene = function () {
  15778. var scene = this.getScene();
  15779. if (this._renderPriority != 0) {
  15780. scene.requireLightSorting = true;
  15781. }
  15782. this.getScene().sortLightsByPriority();
  15783. };
  15784. //lightmapMode Consts
  15785. Light._LIGHTMAP_DEFAULT = 0;
  15786. Light._LIGHTMAP_SPECULAR = 1;
  15787. Light._LIGHTMAP_SHADOWSONLY = 2;
  15788. // Intensity Mode Consts
  15789. Light._INTENSITYMODE_AUTOMATIC = 0;
  15790. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15791. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15792. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15793. Light._INTENSITYMODE_LUMINANCE = 4;
  15794. // Light types ids const.
  15795. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15796. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15797. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15798. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15799. __decorate([
  15800. BABYLON.serializeAsColor3()
  15801. ], Light.prototype, "diffuse", void 0);
  15802. __decorate([
  15803. BABYLON.serializeAsColor3()
  15804. ], Light.prototype, "specular", void 0);
  15805. __decorate([
  15806. BABYLON.serialize()
  15807. ], Light.prototype, "intensity", void 0);
  15808. __decorate([
  15809. BABYLON.serialize()
  15810. ], Light.prototype, "range", void 0);
  15811. __decorate([
  15812. BABYLON.serialize()
  15813. ], Light.prototype, "intensityMode", null);
  15814. __decorate([
  15815. BABYLON.serialize()
  15816. ], Light.prototype, "radius", null);
  15817. __decorate([
  15818. BABYLON.serialize()
  15819. ], Light.prototype, "_renderPriority", void 0);
  15820. __decorate([
  15821. BABYLON.expandToProperty("_reorderLightsInScene")
  15822. ], Light.prototype, "renderPriority", void 0);
  15823. __decorate([
  15824. BABYLON.serialize()
  15825. ], Light.prototype, "shadowEnabled", void 0);
  15826. __decorate([
  15827. BABYLON.serialize("excludeWithLayerMask")
  15828. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15829. __decorate([
  15830. BABYLON.serialize("includeOnlyWithLayerMask")
  15831. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15832. __decorate([
  15833. BABYLON.serialize("lightmapMode")
  15834. ], Light.prototype, "_lightmapMode", void 0);
  15835. return Light;
  15836. }(BABYLON.Node));
  15837. BABYLON.Light = Light;
  15838. })(BABYLON || (BABYLON = {}));
  15839. //# sourceMappingURL=babylon.light.js.map
  15840. var BABYLON;
  15841. (function (BABYLON) {
  15842. var Camera = /** @class */ (function (_super) {
  15843. __extends(Camera, _super);
  15844. function Camera(name, position, scene) {
  15845. var _this = _super.call(this, name, scene) || this;
  15846. _this.upVector = BABYLON.Vector3.Up();
  15847. _this.orthoLeft = null;
  15848. _this.orthoRight = null;
  15849. _this.orthoBottom = null;
  15850. _this.orthoTop = null;
  15851. _this.fov = 0.8;
  15852. _this.minZ = 1;
  15853. _this.maxZ = 10000.0;
  15854. _this.inertia = 0.9;
  15855. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15856. _this.isIntermediate = false;
  15857. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15858. _this.layerMask = 0x0FFFFFFF;
  15859. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15860. // Camera rig members
  15861. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15862. _this._rigCameras = new Array();
  15863. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15864. _this._skipRendering = false;
  15865. _this.customRenderTargets = new Array();
  15866. // Observables
  15867. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15868. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15869. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15870. _this.onRestoreStateObservable = new BABYLON.Observable();
  15871. // Cache
  15872. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15873. _this._projectionMatrix = new BABYLON.Matrix();
  15874. _this._doNotComputeProjectionMatrix = false;
  15875. _this._postProcesses = new Array();
  15876. _this._transformMatrix = BABYLON.Matrix.Zero();
  15877. _this._activeMeshes = new BABYLON.SmartArray(256);
  15878. _this._globalPosition = BABYLON.Vector3.Zero();
  15879. _this._refreshFrustumPlanes = true;
  15880. _this.getScene().addCamera(_this);
  15881. if (!_this.getScene().activeCamera) {
  15882. _this.getScene().activeCamera = _this;
  15883. }
  15884. _this.position = position;
  15885. return _this;
  15886. }
  15887. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15888. get: function () {
  15889. return Camera._PERSPECTIVE_CAMERA;
  15890. },
  15891. enumerable: true,
  15892. configurable: true
  15893. });
  15894. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15895. get: function () {
  15896. return Camera._ORTHOGRAPHIC_CAMERA;
  15897. },
  15898. enumerable: true,
  15899. configurable: true
  15900. });
  15901. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15902. get: function () {
  15903. return Camera._FOVMODE_VERTICAL_FIXED;
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15909. get: function () {
  15910. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15911. },
  15912. enumerable: true,
  15913. configurable: true
  15914. });
  15915. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15916. get: function () {
  15917. return Camera._RIG_MODE_NONE;
  15918. },
  15919. enumerable: true,
  15920. configurable: true
  15921. });
  15922. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15923. get: function () {
  15924. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15925. },
  15926. enumerable: true,
  15927. configurable: true
  15928. });
  15929. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15930. get: function () {
  15931. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15932. },
  15933. enumerable: true,
  15934. configurable: true
  15935. });
  15936. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15937. get: function () {
  15938. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15939. },
  15940. enumerable: true,
  15941. configurable: true
  15942. });
  15943. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15944. get: function () {
  15945. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15946. },
  15947. enumerable: true,
  15948. configurable: true
  15949. });
  15950. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15951. get: function () {
  15952. return Camera._RIG_MODE_VR;
  15953. },
  15954. enumerable: true,
  15955. configurable: true
  15956. });
  15957. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15958. get: function () {
  15959. return Camera._RIG_MODE_WEBVR;
  15960. },
  15961. enumerable: true,
  15962. configurable: true
  15963. });
  15964. /**
  15965. * Store current camera state (fov, position, etc..)
  15966. */
  15967. Camera.prototype.storeState = function () {
  15968. this._stateStored = true;
  15969. this._storedFov = this.fov;
  15970. return this;
  15971. };
  15972. /**
  15973. * Restores the camera state values if it has been stored. You must call storeState() first
  15974. */
  15975. Camera.prototype._restoreStateValues = function () {
  15976. if (!this._stateStored) {
  15977. return false;
  15978. }
  15979. this.fov = this._storedFov;
  15980. return true;
  15981. };
  15982. /**
  15983. * Restored camera state. You must call storeState() first
  15984. */
  15985. Camera.prototype.restoreState = function () {
  15986. if (this._restoreStateValues()) {
  15987. this.onRestoreStateObservable.notifyObservers(this);
  15988. return true;
  15989. }
  15990. return false;
  15991. };
  15992. Camera.prototype.getClassName = function () {
  15993. return "Camera";
  15994. };
  15995. /**
  15996. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15997. */
  15998. Camera.prototype.toString = function (fullDetails) {
  15999. var ret = "Name: " + this.name;
  16000. ret += ", type: " + this.getClassName();
  16001. if (this.animations) {
  16002. for (var i = 0; i < this.animations.length; i++) {
  16003. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16004. }
  16005. }
  16006. if (fullDetails) {
  16007. }
  16008. return ret;
  16009. };
  16010. Object.defineProperty(Camera.prototype, "globalPosition", {
  16011. get: function () {
  16012. return this._globalPosition;
  16013. },
  16014. enumerable: true,
  16015. configurable: true
  16016. });
  16017. Camera.prototype.getActiveMeshes = function () {
  16018. return this._activeMeshes;
  16019. };
  16020. Camera.prototype.isActiveMesh = function (mesh) {
  16021. return (this._activeMeshes.indexOf(mesh) !== -1);
  16022. };
  16023. //Cache
  16024. Camera.prototype._initCache = function () {
  16025. _super.prototype._initCache.call(this);
  16026. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16027. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16028. this._cache.mode = undefined;
  16029. this._cache.minZ = undefined;
  16030. this._cache.maxZ = undefined;
  16031. this._cache.fov = undefined;
  16032. this._cache.fovMode = undefined;
  16033. this._cache.aspectRatio = undefined;
  16034. this._cache.orthoLeft = undefined;
  16035. this._cache.orthoRight = undefined;
  16036. this._cache.orthoBottom = undefined;
  16037. this._cache.orthoTop = undefined;
  16038. this._cache.renderWidth = undefined;
  16039. this._cache.renderHeight = undefined;
  16040. };
  16041. Camera.prototype._updateCache = function (ignoreParentClass) {
  16042. if (!ignoreParentClass) {
  16043. _super.prototype._updateCache.call(this);
  16044. }
  16045. this._cache.position.copyFrom(this.position);
  16046. this._cache.upVector.copyFrom(this.upVector);
  16047. };
  16048. // Synchronized
  16049. Camera.prototype._isSynchronized = function () {
  16050. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16051. };
  16052. Camera.prototype._isSynchronizedViewMatrix = function () {
  16053. if (!_super.prototype._isSynchronized.call(this))
  16054. return false;
  16055. return this._cache.position.equals(this.position)
  16056. && this._cache.upVector.equals(this.upVector)
  16057. && this.isSynchronizedWithParent();
  16058. };
  16059. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16060. var check = this._cache.mode === this.mode
  16061. && this._cache.minZ === this.minZ
  16062. && this._cache.maxZ === this.maxZ;
  16063. if (!check) {
  16064. return false;
  16065. }
  16066. var engine = this.getEngine();
  16067. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16068. check = this._cache.fov === this.fov
  16069. && this._cache.fovMode === this.fovMode
  16070. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16071. }
  16072. else {
  16073. check = this._cache.orthoLeft === this.orthoLeft
  16074. && this._cache.orthoRight === this.orthoRight
  16075. && this._cache.orthoBottom === this.orthoBottom
  16076. && this._cache.orthoTop === this.orthoTop
  16077. && this._cache.renderWidth === engine.getRenderWidth()
  16078. && this._cache.renderHeight === engine.getRenderHeight();
  16079. }
  16080. return check;
  16081. };
  16082. // Controls
  16083. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16084. };
  16085. Camera.prototype.detachControl = function (element) {
  16086. };
  16087. Camera.prototype.update = function () {
  16088. this._checkInputs();
  16089. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16090. this._updateRigCameras();
  16091. }
  16092. };
  16093. Camera.prototype._checkInputs = function () {
  16094. this.onAfterCheckInputsObservable.notifyObservers(this);
  16095. };
  16096. Object.defineProperty(Camera.prototype, "rigCameras", {
  16097. get: function () {
  16098. return this._rigCameras;
  16099. },
  16100. enumerable: true,
  16101. configurable: true
  16102. });
  16103. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16104. get: function () {
  16105. return this._rigPostProcess;
  16106. },
  16107. enumerable: true,
  16108. configurable: true
  16109. });
  16110. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16111. // invalidate framebuffer
  16112. if (this._postProcesses.length > 0) {
  16113. this._postProcesses[0].markTextureDirty();
  16114. }
  16115. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16116. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16117. var cam = this._rigCameras[i];
  16118. var rigPostProcess = cam._rigPostProcess;
  16119. // for VR rig, there does not have to be a post process
  16120. if (rigPostProcess) {
  16121. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16122. if (isPass) {
  16123. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16124. cam.isIntermediate = this._postProcesses.length === 0;
  16125. }
  16126. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16127. rigPostProcess.markTextureDirty();
  16128. }
  16129. else {
  16130. cam._postProcesses = this._postProcesses.slice(0);
  16131. }
  16132. }
  16133. };
  16134. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16135. if (insertAt === void 0) { insertAt = null; }
  16136. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16137. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16138. return 0;
  16139. }
  16140. if (insertAt == null || insertAt < 0) {
  16141. this._postProcesses.push(postProcess);
  16142. }
  16143. else {
  16144. this._postProcesses.splice(insertAt, 0, postProcess);
  16145. }
  16146. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16147. return this._postProcesses.indexOf(postProcess);
  16148. };
  16149. Camera.prototype.detachPostProcess = function (postProcess) {
  16150. var idx = this._postProcesses.indexOf(postProcess);
  16151. if (idx !== -1) {
  16152. this._postProcesses.splice(idx, 1);
  16153. }
  16154. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16155. };
  16156. Camera.prototype.getWorldMatrix = function () {
  16157. if (!this._worldMatrix) {
  16158. this._worldMatrix = BABYLON.Matrix.Identity();
  16159. }
  16160. var viewMatrix = this.getViewMatrix();
  16161. viewMatrix.invertToRef(this._worldMatrix);
  16162. return this._worldMatrix;
  16163. };
  16164. Camera.prototype._getViewMatrix = function () {
  16165. return BABYLON.Matrix.Identity();
  16166. };
  16167. Camera.prototype.getViewMatrix = function (force) {
  16168. if (!force && this._isSynchronizedViewMatrix()) {
  16169. return this._computedViewMatrix;
  16170. }
  16171. this.updateCache();
  16172. this._computedViewMatrix = this._getViewMatrix();
  16173. this._currentRenderId = this.getScene().getRenderId();
  16174. this._refreshFrustumPlanes = true;
  16175. if (!this.parent || !this.parent.getWorldMatrix) {
  16176. this._globalPosition.copyFrom(this.position);
  16177. }
  16178. else {
  16179. if (!this._worldMatrix) {
  16180. this._worldMatrix = BABYLON.Matrix.Identity();
  16181. }
  16182. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16183. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16184. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16185. this._computedViewMatrix.invert();
  16186. this._markSyncedWithParent();
  16187. }
  16188. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16189. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16190. }
  16191. this.onViewMatrixChangedObservable.notifyObservers(this);
  16192. return this._computedViewMatrix;
  16193. };
  16194. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16195. this._doNotComputeProjectionMatrix = true;
  16196. if (projection !== undefined) {
  16197. this._projectionMatrix = projection;
  16198. }
  16199. };
  16200. ;
  16201. Camera.prototype.unfreezeProjectionMatrix = function () {
  16202. this._doNotComputeProjectionMatrix = false;
  16203. };
  16204. ;
  16205. Camera.prototype.getProjectionMatrix = function (force) {
  16206. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16207. return this._projectionMatrix;
  16208. }
  16209. // Cache
  16210. this._cache.mode = this.mode;
  16211. this._cache.minZ = this.minZ;
  16212. this._cache.maxZ = this.maxZ;
  16213. // Matrix
  16214. this._refreshFrustumPlanes = true;
  16215. var engine = this.getEngine();
  16216. var scene = this.getScene();
  16217. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16218. this._cache.fov = this.fov;
  16219. this._cache.fovMode = this.fovMode;
  16220. this._cache.aspectRatio = engine.getAspectRatio(this);
  16221. if (this.minZ <= 0) {
  16222. this.minZ = 0.1;
  16223. }
  16224. if (scene.useRightHandedSystem) {
  16225. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16226. }
  16227. else {
  16228. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16229. }
  16230. }
  16231. else {
  16232. var halfWidth = engine.getRenderWidth() / 2.0;
  16233. var halfHeight = engine.getRenderHeight() / 2.0;
  16234. if (scene.useRightHandedSystem) {
  16235. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16236. }
  16237. else {
  16238. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16239. }
  16240. this._cache.orthoLeft = this.orthoLeft;
  16241. this._cache.orthoRight = this.orthoRight;
  16242. this._cache.orthoBottom = this.orthoBottom;
  16243. this._cache.orthoTop = this.orthoTop;
  16244. this._cache.renderWidth = engine.getRenderWidth();
  16245. this._cache.renderHeight = engine.getRenderHeight();
  16246. }
  16247. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16248. return this._projectionMatrix;
  16249. };
  16250. Camera.prototype.getTranformationMatrix = function () {
  16251. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16252. return this._transformMatrix;
  16253. };
  16254. Camera.prototype.updateFrustumPlanes = function () {
  16255. if (!this._refreshFrustumPlanes) {
  16256. return;
  16257. }
  16258. this.getTranformationMatrix();
  16259. if (!this._frustumPlanes) {
  16260. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16261. }
  16262. else {
  16263. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16264. }
  16265. this._refreshFrustumPlanes = false;
  16266. };
  16267. Camera.prototype.isInFrustum = function (target) {
  16268. this.updateFrustumPlanes();
  16269. return target.isInFrustum(this._frustumPlanes);
  16270. };
  16271. Camera.prototype.isCompletelyInFrustum = function (target) {
  16272. this.updateFrustumPlanes();
  16273. return target.isCompletelyInFrustum(this._frustumPlanes);
  16274. };
  16275. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16276. if (length === void 0) { length = 100; }
  16277. if (!transform) {
  16278. transform = this.getWorldMatrix();
  16279. }
  16280. if (!origin) {
  16281. origin = this.position;
  16282. }
  16283. var forward = new BABYLON.Vector3(0, 0, 1);
  16284. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16285. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16286. return new BABYLON.Ray(origin, direction, length);
  16287. };
  16288. Camera.prototype.dispose = function () {
  16289. // Observables
  16290. this.onViewMatrixChangedObservable.clear();
  16291. this.onProjectionMatrixChangedObservable.clear();
  16292. this.onAfterCheckInputsObservable.clear();
  16293. this.onRestoreStateObservable.clear();
  16294. // Inputs
  16295. if (this.inputs) {
  16296. this.inputs.clear();
  16297. }
  16298. // Animations
  16299. this.getScene().stopAnimation(this);
  16300. // Remove from scene
  16301. this.getScene().removeCamera(this);
  16302. while (this._rigCameras.length > 0) {
  16303. var camera = this._rigCameras.pop();
  16304. if (camera) {
  16305. camera.dispose();
  16306. }
  16307. }
  16308. // Postprocesses
  16309. if (this._rigPostProcess) {
  16310. this._rigPostProcess.dispose(this);
  16311. this._rigPostProcess = null;
  16312. this._postProcesses = [];
  16313. }
  16314. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16315. this._rigPostProcess = null;
  16316. this._postProcesses = [];
  16317. }
  16318. else {
  16319. var i = this._postProcesses.length;
  16320. while (--i >= 0) {
  16321. this._postProcesses[i].dispose(this);
  16322. }
  16323. }
  16324. // Render targets
  16325. var i = this.customRenderTargets.length;
  16326. while (--i >= 0) {
  16327. this.customRenderTargets[i].dispose();
  16328. }
  16329. this.customRenderTargets = [];
  16330. // Active Meshes
  16331. this._activeMeshes.dispose();
  16332. _super.prototype.dispose.call(this);
  16333. };
  16334. Object.defineProperty(Camera.prototype, "leftCamera", {
  16335. // ---- Camera rigs section ----
  16336. get: function () {
  16337. if (this._rigCameras.length < 1) {
  16338. return null;
  16339. }
  16340. return this._rigCameras[0];
  16341. },
  16342. enumerable: true,
  16343. configurable: true
  16344. });
  16345. Object.defineProperty(Camera.prototype, "rightCamera", {
  16346. get: function () {
  16347. if (this._rigCameras.length < 2) {
  16348. return null;
  16349. }
  16350. return this._rigCameras[1];
  16351. },
  16352. enumerable: true,
  16353. configurable: true
  16354. });
  16355. Camera.prototype.getLeftTarget = function () {
  16356. if (this._rigCameras.length < 1) {
  16357. return null;
  16358. }
  16359. return this._rigCameras[0].getTarget();
  16360. };
  16361. Camera.prototype.getRightTarget = function () {
  16362. if (this._rigCameras.length < 2) {
  16363. return null;
  16364. }
  16365. return this._rigCameras[1].getTarget();
  16366. };
  16367. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16368. if (this.cameraRigMode === mode) {
  16369. return;
  16370. }
  16371. while (this._rigCameras.length > 0) {
  16372. var camera = this._rigCameras.pop();
  16373. if (camera) {
  16374. camera.dispose();
  16375. }
  16376. }
  16377. this.cameraRigMode = mode;
  16378. this._cameraRigParams = {};
  16379. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16380. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16381. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16382. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16383. // create the rig cameras, unless none
  16384. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16385. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16386. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16387. if (leftCamera && rightCamera) {
  16388. this._rigCameras.push(leftCamera);
  16389. this._rigCameras.push(rightCamera);
  16390. }
  16391. }
  16392. switch (this.cameraRigMode) {
  16393. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16394. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16395. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16396. break;
  16397. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16398. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16399. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16400. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16401. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16402. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16403. break;
  16404. case Camera.RIG_MODE_VR:
  16405. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16406. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16407. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16408. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16409. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16410. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16411. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16412. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16413. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16414. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16415. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16416. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16417. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16418. if (metrics.compensateDistortion) {
  16419. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16420. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16421. }
  16422. break;
  16423. case Camera.RIG_MODE_WEBVR:
  16424. if (rigParams.vrDisplay) {
  16425. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16426. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16427. //Left eye
  16428. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16429. this._rigCameras[0].setCameraRigParameter("left", true);
  16430. //leaving this for future reference
  16431. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16432. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16433. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16434. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16435. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16436. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16437. this._rigCameras[0].parent = this;
  16438. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16439. //Right eye
  16440. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16441. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16442. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16443. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16444. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16445. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16446. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16447. this._rigCameras[1].parent = this;
  16448. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16449. if (Camera.UseAlternateWebVRRendering) {
  16450. this._rigCameras[1]._skipRendering = true;
  16451. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16452. }
  16453. }
  16454. break;
  16455. }
  16456. this._cascadePostProcessesToRigCams();
  16457. this.update();
  16458. };
  16459. Camera.prototype._getVRProjectionMatrix = function () {
  16460. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16461. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16462. return this._projectionMatrix;
  16463. };
  16464. Camera.prototype._updateCameraRotationMatrix = function () {
  16465. //Here for WebVR
  16466. };
  16467. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16468. //Here for WebVR
  16469. };
  16470. /**
  16471. * This function MUST be overwritten by the different WebVR cameras available.
  16472. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16473. */
  16474. Camera.prototype._getWebVRProjectionMatrix = function () {
  16475. return BABYLON.Matrix.Identity();
  16476. };
  16477. /**
  16478. * This function MUST be overwritten by the different WebVR cameras available.
  16479. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16480. */
  16481. Camera.prototype._getWebVRViewMatrix = function () {
  16482. return BABYLON.Matrix.Identity();
  16483. };
  16484. Camera.prototype.setCameraRigParameter = function (name, value) {
  16485. if (!this._cameraRigParams) {
  16486. this._cameraRigParams = {};
  16487. }
  16488. this._cameraRigParams[name] = value;
  16489. //provisionnally:
  16490. if (name === "interaxialDistance") {
  16491. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16492. }
  16493. };
  16494. /**
  16495. * needs to be overridden by children so sub has required properties to be copied
  16496. */
  16497. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16498. return null;
  16499. };
  16500. /**
  16501. * May need to be overridden by children
  16502. */
  16503. Camera.prototype._updateRigCameras = function () {
  16504. for (var i = 0; i < this._rigCameras.length; i++) {
  16505. this._rigCameras[i].minZ = this.minZ;
  16506. this._rigCameras[i].maxZ = this.maxZ;
  16507. this._rigCameras[i].fov = this.fov;
  16508. }
  16509. // only update viewport when ANAGLYPH
  16510. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16511. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16512. }
  16513. };
  16514. Camera.prototype._setupInputs = function () {
  16515. };
  16516. Camera.prototype.serialize = function () {
  16517. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16518. // Type
  16519. serializationObject.type = this.getClassName();
  16520. // Parent
  16521. if (this.parent) {
  16522. serializationObject.parentId = this.parent.id;
  16523. }
  16524. if (this.inputs) {
  16525. this.inputs.serialize(serializationObject);
  16526. }
  16527. // Animations
  16528. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16529. serializationObject.ranges = this.serializeAnimationRanges();
  16530. return serializationObject;
  16531. };
  16532. Camera.prototype.clone = function (name) {
  16533. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16534. };
  16535. Camera.prototype.getDirection = function (localAxis) {
  16536. var result = BABYLON.Vector3.Zero();
  16537. this.getDirectionToRef(localAxis, result);
  16538. return result;
  16539. };
  16540. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16541. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16542. };
  16543. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16544. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16545. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16546. switch (type) {
  16547. case "ArcRotateCamera":
  16548. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16549. case "DeviceOrientationCamera":
  16550. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16551. case "FollowCamera":
  16552. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16553. case "ArcFollowCamera":
  16554. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16555. case "GamepadCamera":
  16556. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16557. case "TouchCamera":
  16558. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16559. case "VirtualJoysticksCamera":
  16560. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16561. case "WebVRFreeCamera":
  16562. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16563. case "WebVRGamepadCamera":
  16564. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16565. case "VRDeviceOrientationFreeCamera":
  16566. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16567. case "VRDeviceOrientationGamepadCamera":
  16568. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16569. case "AnaglyphArcRotateCamera":
  16570. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16571. case "AnaglyphFreeCamera":
  16572. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16573. case "AnaglyphGamepadCamera":
  16574. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16575. case "AnaglyphUniversalCamera":
  16576. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16577. case "StereoscopicArcRotateCamera":
  16578. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16579. case "StereoscopicFreeCamera":
  16580. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16581. case "StereoscopicGamepadCamera":
  16582. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16583. case "StereoscopicUniversalCamera":
  16584. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16585. case "FreeCamera":// Forcing Universal here
  16586. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16587. default:// Universal Camera is the default value
  16588. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16589. }
  16590. };
  16591. Camera.Parse = function (parsedCamera, scene) {
  16592. var type = parsedCamera.type;
  16593. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16594. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16595. // Parent
  16596. if (parsedCamera.parentId) {
  16597. camera._waitingParentId = parsedCamera.parentId;
  16598. }
  16599. //If camera has an input manager, let it parse inputs settings
  16600. if (camera.inputs) {
  16601. camera.inputs.parse(parsedCamera);
  16602. camera._setupInputs();
  16603. }
  16604. if (camera.setPosition) {
  16605. camera.position.copyFromFloats(0, 0, 0);
  16606. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16607. }
  16608. // Target
  16609. if (parsedCamera.target) {
  16610. if (camera.setTarget) {
  16611. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16612. }
  16613. }
  16614. // Apply 3d rig, when found
  16615. if (parsedCamera.cameraRigMode) {
  16616. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16617. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16618. }
  16619. // Animations
  16620. if (parsedCamera.animations) {
  16621. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16622. var parsedAnimation = parsedCamera.animations[animationIndex];
  16623. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16624. }
  16625. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16626. }
  16627. if (parsedCamera.autoAnimate) {
  16628. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16629. }
  16630. return camera;
  16631. };
  16632. // Statics
  16633. Camera._PERSPECTIVE_CAMERA = 0;
  16634. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16635. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16636. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16637. Camera._RIG_MODE_NONE = 0;
  16638. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16639. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16640. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16641. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16642. Camera._RIG_MODE_VR = 20;
  16643. Camera._RIG_MODE_WEBVR = 21;
  16644. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16645. Camera.UseAlternateWebVRRendering = false;
  16646. __decorate([
  16647. BABYLON.serializeAsVector3()
  16648. ], Camera.prototype, "position", void 0);
  16649. __decorate([
  16650. BABYLON.serializeAsVector3()
  16651. ], Camera.prototype, "upVector", void 0);
  16652. __decorate([
  16653. BABYLON.serialize()
  16654. ], Camera.prototype, "orthoLeft", void 0);
  16655. __decorate([
  16656. BABYLON.serialize()
  16657. ], Camera.prototype, "orthoRight", void 0);
  16658. __decorate([
  16659. BABYLON.serialize()
  16660. ], Camera.prototype, "orthoBottom", void 0);
  16661. __decorate([
  16662. BABYLON.serialize()
  16663. ], Camera.prototype, "orthoTop", void 0);
  16664. __decorate([
  16665. BABYLON.serialize()
  16666. ], Camera.prototype, "fov", void 0);
  16667. __decorate([
  16668. BABYLON.serialize()
  16669. ], Camera.prototype, "minZ", void 0);
  16670. __decorate([
  16671. BABYLON.serialize()
  16672. ], Camera.prototype, "maxZ", void 0);
  16673. __decorate([
  16674. BABYLON.serialize()
  16675. ], Camera.prototype, "inertia", void 0);
  16676. __decorate([
  16677. BABYLON.serialize()
  16678. ], Camera.prototype, "mode", void 0);
  16679. __decorate([
  16680. BABYLON.serialize()
  16681. ], Camera.prototype, "layerMask", void 0);
  16682. __decorate([
  16683. BABYLON.serialize()
  16684. ], Camera.prototype, "fovMode", void 0);
  16685. __decorate([
  16686. BABYLON.serialize()
  16687. ], Camera.prototype, "cameraRigMode", void 0);
  16688. __decorate([
  16689. BABYLON.serialize()
  16690. ], Camera.prototype, "interaxialDistance", void 0);
  16691. __decorate([
  16692. BABYLON.serialize()
  16693. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16694. return Camera;
  16695. }(BABYLON.Node));
  16696. BABYLON.Camera = Camera;
  16697. })(BABYLON || (BABYLON = {}));
  16698. //# sourceMappingURL=babylon.camera.js.map
  16699. var BABYLON;
  16700. (function (BABYLON) {
  16701. var RenderingManager = /** @class */ (function () {
  16702. function RenderingManager(scene) {
  16703. this._renderingGroups = new Array();
  16704. this._autoClearDepthStencil = {};
  16705. this._customOpaqueSortCompareFn = {};
  16706. this._customAlphaTestSortCompareFn = {};
  16707. this._customTransparentSortCompareFn = {};
  16708. this._renderinGroupInfo = null;
  16709. this._scene = scene;
  16710. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16711. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16712. }
  16713. }
  16714. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16715. if (depth === void 0) { depth = true; }
  16716. if (stencil === void 0) { stencil = true; }
  16717. if (this._depthStencilBufferAlreadyCleaned) {
  16718. return;
  16719. }
  16720. this._scene.getEngine().clear(null, false, depth, stencil);
  16721. this._depthStencilBufferAlreadyCleaned = true;
  16722. };
  16723. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16724. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16725. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16726. var info = null;
  16727. if (observable) {
  16728. if (!this._renderinGroupInfo) {
  16729. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16730. }
  16731. info = this._renderinGroupInfo;
  16732. info.scene = this._scene;
  16733. info.camera = this._scene.activeCamera;
  16734. }
  16735. // Dispatch sprites
  16736. if (renderSprites) {
  16737. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16738. var manager = this._scene.spriteManagers[index];
  16739. this.dispatchSprites(manager);
  16740. }
  16741. }
  16742. // Render
  16743. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16744. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16745. var renderingGroup = this._renderingGroups[index];
  16746. if (!renderingGroup && !observable)
  16747. continue;
  16748. this._currentIndex = index;
  16749. var renderingGroupMask = 0;
  16750. // Fire PRECLEAR stage
  16751. if (observable && info) {
  16752. renderingGroupMask = Math.pow(2, index);
  16753. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16754. info.renderingGroupId = index;
  16755. observable.notifyObservers(info, renderingGroupMask);
  16756. }
  16757. // Clear depth/stencil if needed
  16758. if (RenderingManager.AUTOCLEAR) {
  16759. var autoClear = this._autoClearDepthStencil[index];
  16760. if (autoClear && autoClear.autoClear) {
  16761. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16762. }
  16763. }
  16764. if (observable && info) {
  16765. // Fire PREOPAQUE stage
  16766. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16767. observable.notifyObservers(info, renderingGroupMask);
  16768. // Fire PRETRANSPARENT stage
  16769. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16770. observable.notifyObservers(info, renderingGroupMask);
  16771. }
  16772. if (renderingGroup)
  16773. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16774. // Fire POSTTRANSPARENT stage
  16775. if (observable && info) {
  16776. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16777. observable.notifyObservers(info, renderingGroupMask);
  16778. }
  16779. }
  16780. };
  16781. RenderingManager.prototype.reset = function () {
  16782. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16783. var renderingGroup = this._renderingGroups[index];
  16784. if (renderingGroup) {
  16785. renderingGroup.prepare();
  16786. }
  16787. }
  16788. };
  16789. RenderingManager.prototype.dispose = function () {
  16790. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16791. var renderingGroup = this._renderingGroups[index];
  16792. if (renderingGroup) {
  16793. renderingGroup.dispose();
  16794. }
  16795. }
  16796. this._renderingGroups.length = 0;
  16797. };
  16798. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16799. if (!this._renderingGroups[renderingGroupId]) {
  16800. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16801. }
  16802. };
  16803. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16804. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16805. this._prepareRenderingGroup(renderingGroupId);
  16806. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16807. };
  16808. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16809. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16810. this._prepareRenderingGroup(renderingGroupId);
  16811. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16812. };
  16813. RenderingManager.prototype.dispatch = function (subMesh) {
  16814. var mesh = subMesh.getMesh();
  16815. var renderingGroupId = mesh.renderingGroupId || 0;
  16816. this._prepareRenderingGroup(renderingGroupId);
  16817. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16818. };
  16819. /**
  16820. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16821. * This allowed control for front to back rendering or reversly depending of the special needs.
  16822. *
  16823. * @param renderingGroupId The rendering group id corresponding to its index
  16824. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16825. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16826. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16827. */
  16828. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16829. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16830. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16831. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16832. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16833. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16834. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16835. if (this._renderingGroups[renderingGroupId]) {
  16836. var group = this._renderingGroups[renderingGroupId];
  16837. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16838. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16839. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16840. }
  16841. };
  16842. /**
  16843. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16844. *
  16845. * @param renderingGroupId The rendering group id corresponding to its index
  16846. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16847. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16848. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16849. */
  16850. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16851. if (depth === void 0) { depth = true; }
  16852. if (stencil === void 0) { stencil = true; }
  16853. this._autoClearDepthStencil[renderingGroupId] = {
  16854. autoClear: autoClearDepthStencil,
  16855. depth: depth,
  16856. stencil: stencil
  16857. };
  16858. };
  16859. /**
  16860. * The max id used for rendering groups (not included)
  16861. */
  16862. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16863. /**
  16864. * The min id used for rendering groups (included)
  16865. */
  16866. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16867. /**
  16868. * Used to globally prevent autoclearing scenes.
  16869. */
  16870. RenderingManager.AUTOCLEAR = true;
  16871. return RenderingManager;
  16872. }());
  16873. BABYLON.RenderingManager = RenderingManager;
  16874. })(BABYLON || (BABYLON = {}));
  16875. //# sourceMappingURL=babylon.renderingManager.js.map
  16876. var BABYLON;
  16877. (function (BABYLON) {
  16878. var RenderingGroup = /** @class */ (function () {
  16879. /**
  16880. * Creates a new rendering group.
  16881. * @param index The rendering group index
  16882. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16883. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16884. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16885. */
  16886. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16887. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16888. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16889. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16890. this.index = index;
  16891. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16892. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16893. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16894. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16895. this._particleSystems = new BABYLON.SmartArray(256);
  16896. this._spriteManagers = new BABYLON.SmartArray(256);
  16897. this._edgesRenderers = new BABYLON.SmartArray(16);
  16898. this._scene = scene;
  16899. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16900. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16901. this.transparentSortCompareFn = transparentSortCompareFn;
  16902. }
  16903. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16904. /**
  16905. * Set the opaque sort comparison function.
  16906. * If null the sub meshes will be render in the order they were created
  16907. */
  16908. set: function (value) {
  16909. this._opaqueSortCompareFn = value;
  16910. if (value) {
  16911. this._renderOpaque = this.renderOpaqueSorted;
  16912. }
  16913. else {
  16914. this._renderOpaque = RenderingGroup.renderUnsorted;
  16915. }
  16916. },
  16917. enumerable: true,
  16918. configurable: true
  16919. });
  16920. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16921. /**
  16922. * Set the alpha test sort comparison function.
  16923. * If null the sub meshes will be render in the order they were created
  16924. */
  16925. set: function (value) {
  16926. this._alphaTestSortCompareFn = value;
  16927. if (value) {
  16928. this._renderAlphaTest = this.renderAlphaTestSorted;
  16929. }
  16930. else {
  16931. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16932. }
  16933. },
  16934. enumerable: true,
  16935. configurable: true
  16936. });
  16937. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16938. /**
  16939. * Set the transparent sort comparison function.
  16940. * If null the sub meshes will be render in the order they were created
  16941. */
  16942. set: function (value) {
  16943. if (value) {
  16944. this._transparentSortCompareFn = value;
  16945. }
  16946. else {
  16947. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16948. }
  16949. this._renderTransparent = this.renderTransparentSorted;
  16950. },
  16951. enumerable: true,
  16952. configurable: true
  16953. });
  16954. /**
  16955. * Render all the sub meshes contained in the group.
  16956. * @param customRenderFunction Used to override the default render behaviour of the group.
  16957. * @returns true if rendered some submeshes.
  16958. */
  16959. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16960. if (customRenderFunction) {
  16961. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16962. return;
  16963. }
  16964. var engine = this._scene.getEngine();
  16965. // Depth only
  16966. if (this._depthOnlySubMeshes.length !== 0) {
  16967. engine.setAlphaTesting(true);
  16968. engine.setColorWrite(false);
  16969. this._renderAlphaTest(this._depthOnlySubMeshes);
  16970. engine.setAlphaTesting(false);
  16971. engine.setColorWrite(true);
  16972. }
  16973. // Opaque
  16974. if (this._opaqueSubMeshes.length !== 0) {
  16975. this._renderOpaque(this._opaqueSubMeshes);
  16976. }
  16977. // Alpha test
  16978. if (this._alphaTestSubMeshes.length !== 0) {
  16979. engine.setAlphaTesting(true);
  16980. this._renderAlphaTest(this._alphaTestSubMeshes);
  16981. engine.setAlphaTesting(false);
  16982. }
  16983. var stencilState = engine.getStencilBuffer();
  16984. engine.setStencilBuffer(false);
  16985. // Sprites
  16986. if (renderSprites) {
  16987. this._renderSprites();
  16988. }
  16989. // Particles
  16990. if (renderParticles) {
  16991. this._renderParticles(activeMeshes);
  16992. }
  16993. if (this.onBeforeTransparentRendering) {
  16994. this.onBeforeTransparentRendering();
  16995. }
  16996. // Transparent
  16997. if (this._transparentSubMeshes.length !== 0) {
  16998. this._renderTransparent(this._transparentSubMeshes);
  16999. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17000. }
  17001. // Set back stencil to false in case it changes before the edge renderer.
  17002. engine.setStencilBuffer(false);
  17003. // Edges
  17004. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17005. this._edgesRenderers.data[edgesRendererIndex].render();
  17006. }
  17007. // Restore Stencil state.
  17008. engine.setStencilBuffer(stencilState);
  17009. };
  17010. /**
  17011. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17012. * @param subMeshes The submeshes to render
  17013. */
  17014. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17015. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17016. };
  17017. /**
  17018. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17019. * @param subMeshes The submeshes to render
  17020. */
  17021. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17022. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17023. };
  17024. /**
  17025. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17026. * @param subMeshes The submeshes to render
  17027. */
  17028. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17029. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17030. };
  17031. /**
  17032. * Renders the submeshes in a specified order.
  17033. * @param subMeshes The submeshes to sort before render
  17034. * @param sortCompareFn The comparison function use to sort
  17035. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17036. * @param transparent Specifies to activate blending if true
  17037. */
  17038. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17039. var subIndex = 0;
  17040. var subMesh;
  17041. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17042. for (; subIndex < subMeshes.length; subIndex++) {
  17043. subMesh = subMeshes.data[subIndex];
  17044. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17045. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17046. }
  17047. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17048. if (sortCompareFn) {
  17049. sortedArray.sort(sortCompareFn);
  17050. }
  17051. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17052. subMesh = sortedArray[subIndex];
  17053. if (transparent) {
  17054. var material = subMesh.getMaterial();
  17055. if (material && material.needDepthPrePass) {
  17056. var engine = material.getScene().getEngine();
  17057. engine.setColorWrite(false);
  17058. engine.setAlphaTesting(true);
  17059. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17060. subMesh.render(false);
  17061. engine.setAlphaTesting(false);
  17062. engine.setColorWrite(true);
  17063. }
  17064. }
  17065. subMesh.render(transparent);
  17066. }
  17067. };
  17068. /**
  17069. * Renders the submeshes in the order they were dispatched (no sort applied).
  17070. * @param subMeshes The submeshes to render
  17071. */
  17072. RenderingGroup.renderUnsorted = function (subMeshes) {
  17073. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17074. var submesh = subMeshes.data[subIndex];
  17075. submesh.render(false);
  17076. }
  17077. };
  17078. /**
  17079. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17080. * are rendered back to front if in the same alpha index.
  17081. *
  17082. * @param a The first submesh
  17083. * @param b The second submesh
  17084. * @returns The result of the comparison
  17085. */
  17086. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17087. // Alpha index first
  17088. if (a._alphaIndex > b._alphaIndex) {
  17089. return 1;
  17090. }
  17091. if (a._alphaIndex < b._alphaIndex) {
  17092. return -1;
  17093. }
  17094. // Then distance to camera
  17095. return RenderingGroup.backToFrontSortCompare(a, b);
  17096. };
  17097. /**
  17098. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17099. * are rendered back to front.
  17100. *
  17101. * @param a The first submesh
  17102. * @param b The second submesh
  17103. * @returns The result of the comparison
  17104. */
  17105. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17106. // Then distance to camera
  17107. if (a._distanceToCamera < b._distanceToCamera) {
  17108. return 1;
  17109. }
  17110. if (a._distanceToCamera > b._distanceToCamera) {
  17111. return -1;
  17112. }
  17113. return 0;
  17114. };
  17115. /**
  17116. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17117. * are rendered front to back (prevent overdraw).
  17118. *
  17119. * @param a The first submesh
  17120. * @param b The second submesh
  17121. * @returns The result of the comparison
  17122. */
  17123. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17124. // Then distance to camera
  17125. if (a._distanceToCamera < b._distanceToCamera) {
  17126. return -1;
  17127. }
  17128. if (a._distanceToCamera > b._distanceToCamera) {
  17129. return 1;
  17130. }
  17131. return 0;
  17132. };
  17133. /**
  17134. * Resets the different lists of submeshes to prepare a new frame.
  17135. */
  17136. RenderingGroup.prototype.prepare = function () {
  17137. this._opaqueSubMeshes.reset();
  17138. this._transparentSubMeshes.reset();
  17139. this._alphaTestSubMeshes.reset();
  17140. this._depthOnlySubMeshes.reset();
  17141. this._particleSystems.reset();
  17142. this._spriteManagers.reset();
  17143. this._edgesRenderers.reset();
  17144. };
  17145. RenderingGroup.prototype.dispose = function () {
  17146. this._opaqueSubMeshes.dispose();
  17147. this._transparentSubMeshes.dispose();
  17148. this._alphaTestSubMeshes.dispose();
  17149. this._depthOnlySubMeshes.dispose();
  17150. this._particleSystems.dispose();
  17151. this._spriteManagers.dispose();
  17152. this._edgesRenderers.dispose();
  17153. };
  17154. /**
  17155. * Inserts the submesh in its correct queue depending on its material.
  17156. * @param subMesh The submesh to dispatch
  17157. */
  17158. RenderingGroup.prototype.dispatch = function (subMesh) {
  17159. var material = subMesh.getMaterial();
  17160. var mesh = subMesh.getMesh();
  17161. if (!material) {
  17162. return;
  17163. }
  17164. if (material.needAlphaBlending() || material.needAlphaBlendingForMesh(mesh)) {
  17165. this._transparentSubMeshes.push(subMesh);
  17166. }
  17167. else if (material.needAlphaTesting()) {
  17168. if (material.needDepthPrePass) {
  17169. this._depthOnlySubMeshes.push(subMesh);
  17170. }
  17171. this._alphaTestSubMeshes.push(subMesh);
  17172. }
  17173. else {
  17174. if (material.needDepthPrePass) {
  17175. this._depthOnlySubMeshes.push(subMesh);
  17176. }
  17177. this._opaqueSubMeshes.push(subMesh); // Opaque
  17178. }
  17179. if (mesh._edgesRenderer) {
  17180. this._edgesRenderers.push(mesh._edgesRenderer);
  17181. }
  17182. };
  17183. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17184. this._spriteManagers.push(spriteManager);
  17185. };
  17186. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17187. this._particleSystems.push(particleSystem);
  17188. };
  17189. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17190. if (this._particleSystems.length === 0) {
  17191. return;
  17192. }
  17193. // Particles
  17194. var activeCamera = this._scene.activeCamera;
  17195. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17196. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17197. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17198. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17199. continue;
  17200. }
  17201. var emitter = particleSystem.emitter;
  17202. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17203. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17204. }
  17205. }
  17206. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17207. };
  17208. RenderingGroup.prototype._renderSprites = function () {
  17209. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17210. return;
  17211. }
  17212. // Sprites
  17213. var activeCamera = this._scene.activeCamera;
  17214. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17215. for (var id = 0; id < this._spriteManagers.length; id++) {
  17216. var spriteManager = this._spriteManagers.data[id];
  17217. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17218. spriteManager.render();
  17219. }
  17220. }
  17221. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17222. };
  17223. return RenderingGroup;
  17224. }());
  17225. BABYLON.RenderingGroup = RenderingGroup;
  17226. })(BABYLON || (BABYLON = {}));
  17227. //# sourceMappingURL=babylon.renderingGroup.js.map
  17228. var BABYLON;
  17229. (function (BABYLON) {
  17230. var ClickInfo = /** @class */ (function () {
  17231. function ClickInfo() {
  17232. this._singleClick = false;
  17233. this._doubleClick = false;
  17234. this._hasSwiped = false;
  17235. this._ignore = false;
  17236. }
  17237. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17238. get: function () {
  17239. return this._singleClick;
  17240. },
  17241. set: function (b) {
  17242. this._singleClick = b;
  17243. },
  17244. enumerable: true,
  17245. configurable: true
  17246. });
  17247. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17248. get: function () {
  17249. return this._doubleClick;
  17250. },
  17251. set: function (b) {
  17252. this._doubleClick = b;
  17253. },
  17254. enumerable: true,
  17255. configurable: true
  17256. });
  17257. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17258. get: function () {
  17259. return this._hasSwiped;
  17260. },
  17261. set: function (b) {
  17262. this._hasSwiped = b;
  17263. },
  17264. enumerable: true,
  17265. configurable: true
  17266. });
  17267. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17268. get: function () {
  17269. return this._ignore;
  17270. },
  17271. set: function (b) {
  17272. this._ignore = b;
  17273. },
  17274. enumerable: true,
  17275. configurable: true
  17276. });
  17277. return ClickInfo;
  17278. }());
  17279. /**
  17280. * This class is used by the onRenderingGroupObservable
  17281. */
  17282. var RenderingGroupInfo = /** @class */ (function () {
  17283. function RenderingGroupInfo() {
  17284. }
  17285. /**
  17286. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17287. * This stage will be fired no matter what
  17288. */
  17289. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17290. /**
  17291. * Called before opaque object are rendered.
  17292. * This stage will be fired only if there's 3D Opaque content to render
  17293. */
  17294. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17295. /**
  17296. * Called after the opaque objects are rendered and before the transparent ones
  17297. * This stage will be fired only if there's 3D transparent content to render
  17298. */
  17299. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17300. /**
  17301. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17302. * This stage will be fired no matter what
  17303. */
  17304. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17305. return RenderingGroupInfo;
  17306. }());
  17307. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17308. /**
  17309. * Represents a scene to be rendered by the engine.
  17310. * @see http://doc.babylonjs.com/page.php?p=21911
  17311. */
  17312. var Scene = /** @class */ (function () {
  17313. /**
  17314. * @constructor
  17315. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17316. */
  17317. function Scene(engine) {
  17318. // Members
  17319. this.autoClear = true;
  17320. this.autoClearDepthAndStencil = true;
  17321. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17322. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17323. this.forceWireframe = false;
  17324. this._forcePointsCloud = false;
  17325. this.forceShowBoundingBoxes = false;
  17326. this.animationsEnabled = true;
  17327. this.constantlyUpdateMeshUnderPointer = false;
  17328. this.hoverCursor = "pointer";
  17329. this.defaultCursor = "";
  17330. /**
  17331. * This is used to call preventDefault() on pointer down
  17332. * in order to block unwanted artifacts like system double clicks
  17333. */
  17334. this.preventDefaultOnPointerDown = true;
  17335. // Metadata
  17336. this.metadata = null;
  17337. /**
  17338. * An event triggered when the scene is disposed.
  17339. * @type {BABYLON.Observable}
  17340. */
  17341. this.onDisposeObservable = new BABYLON.Observable();
  17342. /**
  17343. * An event triggered before rendering the scene (right after animations and physics)
  17344. * @type {BABYLON.Observable}
  17345. */
  17346. this.onBeforeRenderObservable = new BABYLON.Observable();
  17347. /**
  17348. * An event triggered after rendering the scene
  17349. * @type {BABYLON.Observable}
  17350. */
  17351. this.onAfterRenderObservable = new BABYLON.Observable();
  17352. /**
  17353. * An event triggered before animating the scene
  17354. * @type {BABYLON.Observable}
  17355. */
  17356. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17357. /**
  17358. * An event triggered after animations processing
  17359. * @type {BABYLON.Observable}
  17360. */
  17361. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17362. /**
  17363. * An event triggered before draw calls are ready to be sent
  17364. * @type {BABYLON.Observable}
  17365. */
  17366. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17367. /**
  17368. * An event triggered after draw calls have been sent
  17369. * @type {BABYLON.Observable}
  17370. */
  17371. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17372. /**
  17373. * An event triggered when physic simulation is about to be run
  17374. * @type {BABYLON.Observable}
  17375. */
  17376. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17377. /**
  17378. * An event triggered when physic simulation has been done
  17379. * @type {BABYLON.Observable}
  17380. */
  17381. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17382. /**
  17383. * An event triggered when the scene is ready
  17384. * @type {BABYLON.Observable}
  17385. */
  17386. this.onReadyObservable = new BABYLON.Observable();
  17387. /**
  17388. * An event triggered before rendering a camera
  17389. * @type {BABYLON.Observable}
  17390. */
  17391. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17392. /**
  17393. * An event triggered after rendering a camera
  17394. * @type {BABYLON.Observable}
  17395. */
  17396. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17397. /**
  17398. * An event triggered when active meshes evaluation is about to start
  17399. * @type {BABYLON.Observable}
  17400. */
  17401. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17402. /**
  17403. * An event triggered when active meshes evaluation is done
  17404. * @type {BABYLON.Observable}
  17405. */
  17406. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17407. /**
  17408. * An event triggered when particles rendering is about to start
  17409. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17410. * @type {BABYLON.Observable}
  17411. */
  17412. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17413. /**
  17414. * An event triggered when particles rendering is done
  17415. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17416. * @type {BABYLON.Observable}
  17417. */
  17418. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17419. /**
  17420. * An event triggered when sprites rendering is about to start
  17421. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17422. * @type {BABYLON.Observable}
  17423. */
  17424. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17425. /**
  17426. * An event triggered when sprites rendering is done
  17427. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17428. * @type {BABYLON.Observable}
  17429. */
  17430. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17431. /**
  17432. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  17433. * @type {BABYLON.Observable}
  17434. */
  17435. this.onDataLoadedObservable = new BABYLON.Observable();
  17436. /**
  17437. * An event triggered when a camera is created
  17438. * @type {BABYLON.Observable}
  17439. */
  17440. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17441. /**
  17442. * An event triggered when a camera is removed
  17443. * @type {BABYLON.Observable}
  17444. */
  17445. this.onCameraRemovedObservable = new BABYLON.Observable();
  17446. /**
  17447. * An event triggered when a light is created
  17448. * @type {BABYLON.Observable}
  17449. */
  17450. this.onNewLightAddedObservable = new BABYLON.Observable();
  17451. /**
  17452. * An event triggered when a light is removed
  17453. * @type {BABYLON.Observable}
  17454. */
  17455. this.onLightRemovedObservable = new BABYLON.Observable();
  17456. /**
  17457. * An event triggered when a geometry is created
  17458. * @type {BABYLON.Observable}
  17459. */
  17460. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17461. /**
  17462. * An event triggered when a geometry is removed
  17463. * @type {BABYLON.Observable}
  17464. */
  17465. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17466. /**
  17467. * An event triggered when a mesh is created
  17468. * @type {BABYLON.Observable}
  17469. */
  17470. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17471. /**
  17472. * An event triggered when a mesh is removed
  17473. * @type {BABYLON.Observable}
  17474. */
  17475. this.onMeshRemovedObservable = new BABYLON.Observable();
  17476. /**
  17477. * An event triggered when render targets are about to be rendered
  17478. * Can happen multiple times per frame.
  17479. * @type {BABYLON.Observable}
  17480. */
  17481. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17482. /**
  17483. * An event triggered when render targets were rendered.
  17484. * Can happen multiple times per frame.
  17485. * @type {BABYLON.Observable}
  17486. */
  17487. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17488. /**
  17489. * An event triggered before calculating deterministic simulation step
  17490. * @type {BABYLON.Observable}
  17491. */
  17492. this.onBeforeStepObservable = new BABYLON.Observable();
  17493. /**
  17494. * An event triggered after calculating deterministic simulation step
  17495. * @type {BABYLON.Observable}
  17496. */
  17497. this.onAfterStepObservable = new BABYLON.Observable();
  17498. /**
  17499. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17500. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17501. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  17502. */
  17503. this.onRenderingGroupObservable = new BABYLON.Observable();
  17504. // Animations
  17505. this.animations = [];
  17506. /**
  17507. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  17508. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17509. */
  17510. this.onPrePointerObservable = new BABYLON.Observable();
  17511. /**
  17512. * Observable event triggered each time an input event is received from the rendering canvas
  17513. */
  17514. this.onPointerObservable = new BABYLON.Observable();
  17515. this._meshPickProceed = false;
  17516. this._previousHasSwiped = false;
  17517. this._currentPickResult = null;
  17518. this._previousPickResult = null;
  17519. this._totalPointersPressed = 0;
  17520. this._doubleClickOccured = false;
  17521. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17522. this.cameraToUseForPointers = null;
  17523. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17524. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17525. this._startingPointerTime = 0;
  17526. this._previousStartingPointerTime = 0;
  17527. // Deterministic lockstep
  17528. this._timeAccumulator = 0;
  17529. this._currentStepId = 0;
  17530. this._currentInternalStep = 0;
  17531. // Keyboard
  17532. /**
  17533. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17534. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17535. */
  17536. this.onPreKeyboardObservable = new BABYLON.Observable();
  17537. /**
  17538. * Observable event triggered each time an keyboard event is received from the hosting window
  17539. */
  17540. this.onKeyboardObservable = new BABYLON.Observable();
  17541. // Coordinate system
  17542. /**
  17543. * use right-handed coordinate system on this scene.
  17544. * @type {boolean}
  17545. */
  17546. this._useRightHandedSystem = false;
  17547. // Fog
  17548. this._fogEnabled = true;
  17549. this._fogMode = Scene.FOGMODE_NONE;
  17550. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17551. this.fogDensity = 0.1;
  17552. this.fogStart = 0;
  17553. this.fogEnd = 1000.0;
  17554. // Lights
  17555. /**
  17556. * is shadow enabled on this scene.
  17557. * @type {boolean}
  17558. */
  17559. this._shadowsEnabled = true;
  17560. /**
  17561. * is light enabled on this scene.
  17562. * @type {boolean}
  17563. */
  17564. this._lightsEnabled = true;
  17565. /**
  17566. * All of the lights added to this scene.
  17567. * @see BABYLON.Light
  17568. * @type {BABYLON.Light[]}
  17569. */
  17570. this.lights = new Array();
  17571. // Cameras
  17572. /** All of the cameras added to this scene. */
  17573. this.cameras = new Array();
  17574. /** All of the active cameras added to this scene. */
  17575. this.activeCameras = new Array();
  17576. // Meshes
  17577. /**
  17578. * All of the (abstract) meshes added to this scene.
  17579. * @see BABYLON.AbstractMesh
  17580. * @type {BABYLON.AbstractMesh[]}
  17581. */
  17582. this.meshes = new Array();
  17583. // Geometries
  17584. this._geometries = new Array();
  17585. this.materials = new Array();
  17586. this.multiMaterials = new Array();
  17587. // Textures
  17588. this._texturesEnabled = true;
  17589. this.textures = new Array();
  17590. // Particles
  17591. this.particlesEnabled = true;
  17592. this.particleSystems = new Array();
  17593. // Sprites
  17594. this.spritesEnabled = true;
  17595. this.spriteManagers = new Array();
  17596. // Layers
  17597. this.layers = new Array();
  17598. this.highlightLayers = new Array();
  17599. // Skeletons
  17600. this._skeletonsEnabled = true;
  17601. this.skeletons = new Array();
  17602. // Morph targets
  17603. this.morphTargetManagers = new Array();
  17604. // Lens flares
  17605. this.lensFlaresEnabled = true;
  17606. this.lensFlareSystems = new Array();
  17607. // Collisions
  17608. this.collisionsEnabled = true;
  17609. /** Defines the gravity applied to this scene */
  17610. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17611. // Postprocesses
  17612. this.postProcesses = new Array();
  17613. this.postProcessesEnabled = true;
  17614. // Customs render targets
  17615. this.renderTargetsEnabled = true;
  17616. this.dumpNextRenderTargets = false;
  17617. this.customRenderTargets = new Array();
  17618. // Imported meshes
  17619. this.importedMeshesFiles = new Array();
  17620. // Probes
  17621. this.probesEnabled = true;
  17622. this.reflectionProbes = new Array();
  17623. this._actionManagers = new Array();
  17624. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  17625. // Procedural textures
  17626. this.proceduralTexturesEnabled = true;
  17627. this._proceduralTextures = new Array();
  17628. this.soundTracks = new Array();
  17629. this._audioEnabled = true;
  17630. this._headphone = false;
  17631. // Performance counters
  17632. this._totalVertices = new BABYLON.PerfCounter();
  17633. this._activeIndices = new BABYLON.PerfCounter();
  17634. this._activeParticles = new BABYLON.PerfCounter();
  17635. this._activeBones = new BABYLON.PerfCounter();
  17636. this._animationTime = 0;
  17637. this.animationTimeScale = 1;
  17638. this._renderId = 0;
  17639. this._executeWhenReadyTimeoutId = -1;
  17640. this._intermediateRendering = false;
  17641. this._viewUpdateFlag = -1;
  17642. this._projectionUpdateFlag = -1;
  17643. this._alternateViewUpdateFlag = -1;
  17644. this._alternateProjectionUpdateFlag = -1;
  17645. this._toBeDisposed = new BABYLON.SmartArray(256);
  17646. this._pendingData = new Array();
  17647. this._isDisposed = false;
  17648. this._activeMeshes = new BABYLON.SmartArray(256);
  17649. this._processedMaterials = new BABYLON.SmartArray(256);
  17650. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  17651. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17652. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  17653. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  17654. this._activeAnimatables = new Array();
  17655. this._transformMatrix = BABYLON.Matrix.Zero();
  17656. this._useAlternateCameraConfiguration = false;
  17657. this._alternateRendering = false;
  17658. this.requireLightSorting = false;
  17659. this._activeMeshesFrozen = false;
  17660. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17661. this._engine.scenes.push(this);
  17662. this._uid = null;
  17663. this._renderingManager = new BABYLON.RenderingManager(this);
  17664. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17665. if (BABYLON.OutlineRenderer) {
  17666. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17667. }
  17668. if (BABYLON.Tools.IsWindowObjectExist()) {
  17669. this.attachControl();
  17670. }
  17671. //simplification queue
  17672. if (BABYLON.SimplificationQueue) {
  17673. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17674. }
  17675. //collision coordinator initialization. For now legacy per default.
  17676. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17677. // Uniform Buffer
  17678. this._createUbo();
  17679. // Default Image processing definition.
  17680. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17681. }
  17682. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17683. /** The fog is deactivated */
  17684. get: function () {
  17685. return Scene._FOGMODE_NONE;
  17686. },
  17687. enumerable: true,
  17688. configurable: true
  17689. });
  17690. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17691. /** The fog density is following an exponential function */
  17692. get: function () {
  17693. return Scene._FOGMODE_EXP;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17699. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17700. get: function () {
  17701. return Scene._FOGMODE_EXP2;
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17707. /** The fog density is following a linear function. */
  17708. get: function () {
  17709. return Scene._FOGMODE_LINEAR;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17715. /**
  17716. * Texture used in all pbr material as the reflection texture.
  17717. * As in the majority of the scene they are the same (exception for multi room and so on),
  17718. * this is easier to reference from here than from all the materials.
  17719. */
  17720. get: function () {
  17721. return this._environmentTexture;
  17722. },
  17723. /**
  17724. * Texture used in all pbr material as the reflection texture.
  17725. * As in the majority of the scene they are the same (exception for multi room and so on),
  17726. * this is easier to set here than in all the materials.
  17727. */
  17728. set: function (value) {
  17729. if (this._environmentTexture === value) {
  17730. return;
  17731. }
  17732. this._environmentTexture = value;
  17733. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17734. },
  17735. enumerable: true,
  17736. configurable: true
  17737. });
  17738. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17739. /**
  17740. * Default image processing configuration used either in the rendering
  17741. * Forward main pass or through the imageProcessingPostProcess if present.
  17742. * As in the majority of the scene they are the same (exception for multi camera),
  17743. * this is easier to reference from here than from all the materials and post process.
  17744. *
  17745. * No setter as we it is a shared configuration, you can set the values instead.
  17746. */
  17747. get: function () {
  17748. return this._imageProcessingConfiguration;
  17749. },
  17750. enumerable: true,
  17751. configurable: true
  17752. });
  17753. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17754. get: function () {
  17755. return this._forcePointsCloud;
  17756. },
  17757. set: function (value) {
  17758. if (this._forcePointsCloud === value) {
  17759. return;
  17760. }
  17761. this._forcePointsCloud = value;
  17762. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(Scene.prototype, "onDispose", {
  17768. /** A function to be executed when this scene is disposed. */
  17769. set: function (callback) {
  17770. if (this._onDisposeObserver) {
  17771. this.onDisposeObservable.remove(this._onDisposeObserver);
  17772. }
  17773. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17774. },
  17775. enumerable: true,
  17776. configurable: true
  17777. });
  17778. Object.defineProperty(Scene.prototype, "beforeRender", {
  17779. /** A function to be executed before rendering this scene */
  17780. set: function (callback) {
  17781. if (this._onBeforeRenderObserver) {
  17782. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17783. }
  17784. if (callback) {
  17785. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17786. }
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. Object.defineProperty(Scene.prototype, "afterRender", {
  17792. /** A function to be executed after rendering this scene */
  17793. set: function (callback) {
  17794. if (this._onAfterRenderObserver) {
  17795. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17796. }
  17797. if (callback) {
  17798. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17799. }
  17800. },
  17801. enumerable: true,
  17802. configurable: true
  17803. });
  17804. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17805. set: function (callback) {
  17806. if (this._onBeforeCameraRenderObserver) {
  17807. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17808. }
  17809. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17810. },
  17811. enumerable: true,
  17812. configurable: true
  17813. });
  17814. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17815. set: function (callback) {
  17816. if (this._onAfterCameraRenderObserver) {
  17817. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17818. }
  17819. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17820. },
  17821. enumerable: true,
  17822. configurable: true
  17823. });
  17824. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17825. get: function () {
  17826. if (!this._gamepadManager) {
  17827. this._gamepadManager = new BABYLON.GamepadManager();
  17828. }
  17829. return this._gamepadManager;
  17830. },
  17831. enumerable: true,
  17832. configurable: true
  17833. });
  17834. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17835. get: function () {
  17836. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17842. get: function () {
  17843. return this._useRightHandedSystem;
  17844. },
  17845. set: function (value) {
  17846. if (this._useRightHandedSystem === value) {
  17847. return;
  17848. }
  17849. this._useRightHandedSystem = value;
  17850. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17851. },
  17852. enumerable: true,
  17853. configurable: true
  17854. });
  17855. Scene.prototype.setStepId = function (newStepId) {
  17856. this._currentStepId = newStepId;
  17857. };
  17858. ;
  17859. Scene.prototype.getStepId = function () {
  17860. return this._currentStepId;
  17861. };
  17862. ;
  17863. Scene.prototype.getInternalStep = function () {
  17864. return this._currentInternalStep;
  17865. };
  17866. ;
  17867. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17868. get: function () {
  17869. return this._fogEnabled;
  17870. },
  17871. /**
  17872. * is fog enabled on this scene.
  17873. */
  17874. set: function (value) {
  17875. if (this._fogEnabled === value) {
  17876. return;
  17877. }
  17878. this._fogEnabled = value;
  17879. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17880. },
  17881. enumerable: true,
  17882. configurable: true
  17883. });
  17884. Object.defineProperty(Scene.prototype, "fogMode", {
  17885. get: function () {
  17886. return this._fogMode;
  17887. },
  17888. set: function (value) {
  17889. if (this._fogMode === value) {
  17890. return;
  17891. }
  17892. this._fogMode = value;
  17893. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17894. },
  17895. enumerable: true,
  17896. configurable: true
  17897. });
  17898. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17899. get: function () {
  17900. return this._shadowsEnabled;
  17901. },
  17902. set: function (value) {
  17903. if (this._shadowsEnabled === value) {
  17904. return;
  17905. }
  17906. this._shadowsEnabled = value;
  17907. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17908. },
  17909. enumerable: true,
  17910. configurable: true
  17911. });
  17912. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17913. get: function () {
  17914. return this._lightsEnabled;
  17915. },
  17916. set: function (value) {
  17917. if (this._lightsEnabled === value) {
  17918. return;
  17919. }
  17920. this._lightsEnabled = value;
  17921. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17927. /** The default material used on meshes when no material is affected */
  17928. get: function () {
  17929. if (!this._defaultMaterial) {
  17930. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17931. }
  17932. return this._defaultMaterial;
  17933. },
  17934. /** The default material used on meshes when no material is affected */
  17935. set: function (value) {
  17936. this._defaultMaterial = value;
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17942. get: function () {
  17943. return this._texturesEnabled;
  17944. },
  17945. set: function (value) {
  17946. if (this._texturesEnabled === value) {
  17947. return;
  17948. }
  17949. this._texturesEnabled = value;
  17950. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17951. },
  17952. enumerable: true,
  17953. configurable: true
  17954. });
  17955. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17956. get: function () {
  17957. return this._skeletonsEnabled;
  17958. },
  17959. set: function (value) {
  17960. if (this._skeletonsEnabled === value) {
  17961. return;
  17962. }
  17963. this._skeletonsEnabled = value;
  17964. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17965. },
  17966. enumerable: true,
  17967. configurable: true
  17968. });
  17969. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17970. get: function () {
  17971. if (!this._postProcessRenderPipelineManager) {
  17972. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17973. }
  17974. return this._postProcessRenderPipelineManager;
  17975. },
  17976. enumerable: true,
  17977. configurable: true
  17978. });
  17979. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17980. get: function () {
  17981. if (!this._mainSoundTrack) {
  17982. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17983. }
  17984. return this._mainSoundTrack;
  17985. },
  17986. enumerable: true,
  17987. configurable: true
  17988. });
  17989. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17990. get: function () {
  17991. return this._alternateRendering;
  17992. },
  17993. enumerable: true,
  17994. configurable: true
  17995. });
  17996. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17997. get: function () {
  17998. return this._frustumPlanes;
  17999. },
  18000. enumerable: true,
  18001. configurable: true
  18002. });
  18003. Object.defineProperty(Scene.prototype, "debugLayer", {
  18004. // Properties
  18005. get: function () {
  18006. if (!this._debugLayer) {
  18007. this._debugLayer = new BABYLON.DebugLayer(this);
  18008. }
  18009. return this._debugLayer;
  18010. },
  18011. enumerable: true,
  18012. configurable: true
  18013. });
  18014. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18015. get: function () {
  18016. return this._workerCollisions;
  18017. },
  18018. set: function (enabled) {
  18019. if (!BABYLON.CollisionCoordinatorLegacy) {
  18020. return;
  18021. }
  18022. enabled = (enabled && !!Worker);
  18023. this._workerCollisions = enabled;
  18024. if (this.collisionCoordinator) {
  18025. this.collisionCoordinator.destroy();
  18026. }
  18027. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18028. this.collisionCoordinator.init(this);
  18029. },
  18030. enumerable: true,
  18031. configurable: true
  18032. });
  18033. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18034. get: function () {
  18035. return this._selectionOctree;
  18036. },
  18037. enumerable: true,
  18038. configurable: true
  18039. });
  18040. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18041. /**
  18042. * The mesh that is currently under the pointer.
  18043. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18044. */
  18045. get: function () {
  18046. return this._pointerOverMesh;
  18047. },
  18048. enumerable: true,
  18049. configurable: true
  18050. });
  18051. Object.defineProperty(Scene.prototype, "pointerX", {
  18052. /**
  18053. * Current on-screen X position of the pointer
  18054. * @return {number} X position of the pointer
  18055. */
  18056. get: function () {
  18057. return this._pointerX;
  18058. },
  18059. enumerable: true,
  18060. configurable: true
  18061. });
  18062. Object.defineProperty(Scene.prototype, "pointerY", {
  18063. /**
  18064. * Current on-screen Y position of the pointer
  18065. * @return {number} Y position of the pointer
  18066. */
  18067. get: function () {
  18068. return this._pointerY;
  18069. },
  18070. enumerable: true,
  18071. configurable: true
  18072. });
  18073. Scene.prototype.getCachedMaterial = function () {
  18074. return this._cachedMaterial;
  18075. };
  18076. Scene.prototype.getCachedEffect = function () {
  18077. return this._cachedEffect;
  18078. };
  18079. Scene.prototype.getCachedVisibility = function () {
  18080. return this._cachedVisibility;
  18081. };
  18082. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18083. if (visibility === void 0) { visibility = 1; }
  18084. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18085. };
  18086. Scene.prototype.getBoundingBoxRenderer = function () {
  18087. if (!this._boundingBoxRenderer) {
  18088. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18089. }
  18090. return this._boundingBoxRenderer;
  18091. };
  18092. Scene.prototype.getOutlineRenderer = function () {
  18093. return this._outlineRenderer;
  18094. };
  18095. Scene.prototype.getEngine = function () {
  18096. return this._engine;
  18097. };
  18098. Scene.prototype.getTotalVertices = function () {
  18099. return this._totalVertices.current;
  18100. };
  18101. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18102. get: function () {
  18103. return this._totalVertices;
  18104. },
  18105. enumerable: true,
  18106. configurable: true
  18107. });
  18108. Scene.prototype.getActiveIndices = function () {
  18109. return this._activeIndices.current;
  18110. };
  18111. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18112. get: function () {
  18113. return this._activeIndices;
  18114. },
  18115. enumerable: true,
  18116. configurable: true
  18117. });
  18118. Scene.prototype.getActiveParticles = function () {
  18119. return this._activeParticles.current;
  18120. };
  18121. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18122. get: function () {
  18123. return this._activeParticles;
  18124. },
  18125. enumerable: true,
  18126. configurable: true
  18127. });
  18128. Scene.prototype.getActiveBones = function () {
  18129. return this._activeBones.current;
  18130. };
  18131. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18132. get: function () {
  18133. return this._activeBones;
  18134. },
  18135. enumerable: true,
  18136. configurable: true
  18137. });
  18138. // Stats
  18139. Scene.prototype.getInterFramePerfCounter = function () {
  18140. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18141. return 0;
  18142. };
  18143. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18144. get: function () {
  18145. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18146. return null;
  18147. },
  18148. enumerable: true,
  18149. configurable: true
  18150. });
  18151. Scene.prototype.getLastFrameDuration = function () {
  18152. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18153. return 0;
  18154. };
  18155. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18156. get: function () {
  18157. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18158. return null;
  18159. },
  18160. enumerable: true,
  18161. configurable: true
  18162. });
  18163. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18164. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18165. return 0;
  18166. };
  18167. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18168. get: function () {
  18169. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18170. return null;
  18171. },
  18172. enumerable: true,
  18173. configurable: true
  18174. });
  18175. Scene.prototype.getActiveMeshes = function () {
  18176. return this._activeMeshes;
  18177. };
  18178. Scene.prototype.getRenderTargetsDuration = function () {
  18179. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18180. return 0;
  18181. };
  18182. Scene.prototype.getRenderDuration = function () {
  18183. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18184. return 0;
  18185. };
  18186. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18187. get: function () {
  18188. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18189. return null;
  18190. },
  18191. enumerable: true,
  18192. configurable: true
  18193. });
  18194. Scene.prototype.getParticlesDuration = function () {
  18195. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18196. return 0;
  18197. };
  18198. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18199. get: function () {
  18200. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18201. return null;
  18202. },
  18203. enumerable: true,
  18204. configurable: true
  18205. });
  18206. Scene.prototype.getSpritesDuration = function () {
  18207. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18208. return 0;
  18209. };
  18210. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18211. get: function () {
  18212. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18213. return null;
  18214. },
  18215. enumerable: true,
  18216. configurable: true
  18217. });
  18218. Scene.prototype.getAnimationRatio = function () {
  18219. return this._animationRatio;
  18220. };
  18221. Scene.prototype.getRenderId = function () {
  18222. return this._renderId;
  18223. };
  18224. Scene.prototype.incrementRenderId = function () {
  18225. this._renderId++;
  18226. };
  18227. Scene.prototype._updatePointerPosition = function (evt) {
  18228. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18229. if (!canvasRect) {
  18230. return;
  18231. }
  18232. this._pointerX = evt.clientX - canvasRect.left;
  18233. this._pointerY = evt.clientY - canvasRect.top;
  18234. this._unTranslatedPointerX = this._pointerX;
  18235. this._unTranslatedPointerY = this._pointerY;
  18236. };
  18237. Scene.prototype._createUbo = function () {
  18238. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18239. this._sceneUbo.addUniform("viewProjection", 16);
  18240. this._sceneUbo.addUniform("view", 16);
  18241. };
  18242. Scene.prototype._createAlternateUbo = function () {
  18243. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18244. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18245. this._alternateSceneUbo.addUniform("view", 16);
  18246. };
  18247. // Pointers handling
  18248. /**
  18249. * Use this method to simulate a pointer move on a mesh
  18250. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18251. */
  18252. Scene.prototype.simulatePointerMove = function (pickResult) {
  18253. var evt = new PointerEvent("pointermove");
  18254. return this._processPointerMove(pickResult, evt);
  18255. };
  18256. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18257. var canvas = this._engine.getRenderingCanvas();
  18258. if (!canvas) {
  18259. return this;
  18260. }
  18261. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18262. this.setPointerOverSprite(null);
  18263. this.setPointerOverMesh(pickResult.pickedMesh);
  18264. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18265. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18266. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18267. }
  18268. else {
  18269. canvas.style.cursor = this.hoverCursor;
  18270. }
  18271. }
  18272. else {
  18273. canvas.style.cursor = this.defaultCursor;
  18274. }
  18275. }
  18276. else {
  18277. this.setPointerOverMesh(null);
  18278. // Sprites
  18279. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18280. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18281. this.setPointerOverSprite(pickResult.pickedSprite);
  18282. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18283. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18284. }
  18285. else {
  18286. canvas.style.cursor = this.hoverCursor;
  18287. }
  18288. }
  18289. else {
  18290. this.setPointerOverSprite(null);
  18291. // Restore pointer
  18292. canvas.style.cursor = this.defaultCursor;
  18293. }
  18294. }
  18295. if (pickResult) {
  18296. if (this.onPointerMove) {
  18297. this.onPointerMove(evt, pickResult);
  18298. }
  18299. if (this.onPointerObservable.hasObservers()) {
  18300. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18301. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18302. this.onPointerObservable.notifyObservers(pi, type);
  18303. }
  18304. }
  18305. return this;
  18306. };
  18307. /**
  18308. * Use this method to simulate a pointer down on a mesh
  18309. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18310. */
  18311. Scene.prototype.simulatePointerDown = function (pickResult) {
  18312. var evt = new PointerEvent("pointerdown");
  18313. return this._processPointerDown(pickResult, evt);
  18314. };
  18315. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18316. var _this = this;
  18317. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18318. this._pickedDownMesh = pickResult.pickedMesh;
  18319. var actionManager = pickResult.pickedMesh.actionManager;
  18320. if (actionManager) {
  18321. if (actionManager.hasPickTriggers) {
  18322. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18323. switch (evt.button) {
  18324. case 0:
  18325. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18326. break;
  18327. case 1:
  18328. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18329. break;
  18330. case 2:
  18331. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18332. break;
  18333. }
  18334. }
  18335. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18336. window.setTimeout(function () {
  18337. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);
  18338. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18339. if (_this._totalPointersPressed !== 0 &&
  18340. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18341. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18342. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18343. _this._startingPointerTime = 0;
  18344. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18345. }
  18346. }
  18347. }, Scene.LongPressDelay);
  18348. }
  18349. }
  18350. }
  18351. if (pickResult) {
  18352. if (this.onPointerDown) {
  18353. this.onPointerDown(evt, pickResult);
  18354. }
  18355. if (this.onPointerObservable.hasObservers()) {
  18356. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18357. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18358. this.onPointerObservable.notifyObservers(pi, type);
  18359. }
  18360. }
  18361. return this;
  18362. };
  18363. /**
  18364. * Use this method to simulate a pointer up on a mesh
  18365. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18366. */
  18367. Scene.prototype.simulatePointerUp = function (pickResult) {
  18368. var evt = new PointerEvent("pointerup");
  18369. var clickInfo = new ClickInfo();
  18370. clickInfo.singleClick = true;
  18371. return this._processPointerUp(pickResult, evt, clickInfo);
  18372. };
  18373. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18374. if (pickResult && pickResult && pickResult.pickedMesh) {
  18375. this._pickedUpMesh = pickResult.pickedMesh;
  18376. if (this._pickedDownMesh === this._pickedUpMesh) {
  18377. if (this.onPointerPick) {
  18378. this.onPointerPick(evt, pickResult);
  18379. }
  18380. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18381. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18382. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18383. this.onPointerObservable.notifyObservers(pi, type);
  18384. }
  18385. }
  18386. if (pickResult.pickedMesh.actionManager) {
  18387. if (clickInfo.ignore) {
  18388. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18389. }
  18390. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18391. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18392. }
  18393. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18394. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18395. }
  18396. }
  18397. }
  18398. if (this._pickedDownMesh &&
  18399. this._pickedDownMesh.actionManager &&
  18400. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18401. this._pickedDownMesh !== this._pickedUpMesh) {
  18402. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18403. }
  18404. if (this.onPointerUp) {
  18405. this.onPointerUp(evt, pickResult);
  18406. }
  18407. if (this.onPointerObservable.hasObservers()) {
  18408. if (!clickInfo.ignore) {
  18409. if (!clickInfo.hasSwiped) {
  18410. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18411. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18412. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18413. this.onPointerObservable.notifyObservers(pi, type);
  18414. }
  18415. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18416. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18417. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18418. this.onPointerObservable.notifyObservers(pi, type);
  18419. }
  18420. }
  18421. }
  18422. else {
  18423. var type = BABYLON.PointerEventTypes.POINTERUP;
  18424. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18425. this.onPointerObservable.notifyObservers(pi, type);
  18426. }
  18427. }
  18428. return this;
  18429. };
  18430. /**
  18431. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18432. * @param attachUp defines if you want to attach events to pointerup
  18433. * @param attachDown defines if you want to attach events to pointerdown
  18434. * @param attachMove defines if you want to attach events to pointermove
  18435. */
  18436. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18437. var _this = this;
  18438. if (attachUp === void 0) { attachUp = true; }
  18439. if (attachDown === void 0) { attachDown = true; }
  18440. if (attachMove === void 0) { attachMove = true; }
  18441. this._initActionManager = function (act, clickInfo) {
  18442. if (!_this._meshPickProceed) {
  18443. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18444. _this._currentPickResult = pickResult;
  18445. if (pickResult) {
  18446. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18447. }
  18448. _this._meshPickProceed = true;
  18449. }
  18450. return act;
  18451. };
  18452. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18453. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18454. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18455. btn !== _this._previousButtonPressed) {
  18456. _this._doubleClickOccured = false;
  18457. clickInfo.singleClick = true;
  18458. clickInfo.ignore = false;
  18459. cb(clickInfo, _this._currentPickResult);
  18460. }
  18461. };
  18462. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18463. var clickInfo = new ClickInfo();
  18464. _this._currentPickResult = null;
  18465. var act = null;
  18466. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18467. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18468. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18469. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18470. act = _this._initActionManager(act, clickInfo);
  18471. if (act)
  18472. checkPicking = act.hasPickTriggers;
  18473. }
  18474. if (checkPicking) {
  18475. var btn = evt.button;
  18476. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18477. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18478. if (!clickInfo.hasSwiped) {
  18479. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18480. if (!checkSingleClickImmediately) {
  18481. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18482. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18483. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18484. act = _this._initActionManager(act, clickInfo);
  18485. if (act)
  18486. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18487. }
  18488. }
  18489. if (checkSingleClickImmediately) {
  18490. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18491. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18492. btn !== _this._previousButtonPressed) {
  18493. clickInfo.singleClick = true;
  18494. cb(clickInfo, _this._currentPickResult);
  18495. }
  18496. }
  18497. else {
  18498. // wait that no double click has been raised during the double click delay
  18499. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18500. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18501. }
  18502. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18503. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18504. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18505. act = _this._initActionManager(act, clickInfo);
  18506. if (act)
  18507. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18508. }
  18509. if (checkDoubleClick) {
  18510. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18511. if (btn === _this._previousButtonPressed &&
  18512. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18513. !_this._doubleClickOccured) {
  18514. // pointer has not moved for 2 clicks, it's a double click
  18515. if (!clickInfo.hasSwiped &&
  18516. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18517. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18518. _this._previousStartingPointerTime = 0;
  18519. _this._doubleClickOccured = true;
  18520. clickInfo.doubleClick = true;
  18521. clickInfo.ignore = false;
  18522. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18523. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18524. }
  18525. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18526. cb(clickInfo, _this._currentPickResult);
  18527. }
  18528. else {
  18529. _this._doubleClickOccured = false;
  18530. _this._previousStartingPointerTime = _this._startingPointerTime;
  18531. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18532. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18533. _this._previousButtonPressed = btn;
  18534. _this._previousHasSwiped = clickInfo.hasSwiped;
  18535. if (Scene.ExclusiveDoubleClickMode) {
  18536. if (_this._previousDelayedSimpleClickTimeout) {
  18537. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18538. }
  18539. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18540. cb(clickInfo, _this._previousPickResult);
  18541. }
  18542. else {
  18543. cb(clickInfo, _this._currentPickResult);
  18544. }
  18545. }
  18546. }
  18547. else {
  18548. _this._doubleClickOccured = false;
  18549. _this._previousStartingPointerTime = _this._startingPointerTime;
  18550. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18551. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18552. _this._previousButtonPressed = btn;
  18553. _this._previousHasSwiped = clickInfo.hasSwiped;
  18554. }
  18555. }
  18556. }
  18557. }
  18558. clickInfo.ignore = true;
  18559. cb(clickInfo, _this._currentPickResult);
  18560. };
  18561. this._spritePredicate = function (sprite) {
  18562. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18563. };
  18564. this._onPointerMove = function (evt) {
  18565. _this._updatePointerPosition(evt);
  18566. // PreObservable support
  18567. if (_this.onPrePointerObservable.hasObservers()) {
  18568. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18569. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18570. _this.onPrePointerObservable.notifyObservers(pi, type);
  18571. if (pi.skipOnPointerObservable) {
  18572. return;
  18573. }
  18574. }
  18575. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18576. return;
  18577. }
  18578. if (!_this.pointerMovePredicate) {
  18579. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18580. }
  18581. // Meshes
  18582. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18583. _this._processPointerMove(pickResult, evt);
  18584. };
  18585. this._onPointerDown = function (evt) {
  18586. _this._totalPointersPressed++;
  18587. _this._pickedDownMesh = null;
  18588. _this._meshPickProceed = false;
  18589. _this._updatePointerPosition(evt);
  18590. if (_this.preventDefaultOnPointerDown && canvas) {
  18591. evt.preventDefault();
  18592. canvas.focus();
  18593. }
  18594. // PreObservable support
  18595. if (_this.onPrePointerObservable.hasObservers()) {
  18596. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18597. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18598. _this.onPrePointerObservable.notifyObservers(pi, type);
  18599. if (pi.skipOnPointerObservable) {
  18600. return;
  18601. }
  18602. }
  18603. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18604. return;
  18605. }
  18606. _this._startingPointerPosition.x = _this._pointerX;
  18607. _this._startingPointerPosition.y = _this._pointerY;
  18608. _this._startingPointerTime = new Date().getTime();
  18609. if (!_this.pointerDownPredicate) {
  18610. _this.pointerDownPredicate = function (mesh) {
  18611. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18612. };
  18613. }
  18614. // Meshes
  18615. _this._pickedDownMesh = null;
  18616. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18617. _this._processPointerDown(pickResult, evt);
  18618. // Sprites
  18619. _this._pickedDownSprite = null;
  18620. if (_this.spriteManagers.length > 0) {
  18621. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18622. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18623. if (pickResult.pickedSprite.actionManager) {
  18624. _this._pickedDownSprite = pickResult.pickedSprite;
  18625. switch (evt.button) {
  18626. case 0:
  18627. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18628. break;
  18629. case 1:
  18630. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18631. break;
  18632. case 2:
  18633. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18634. break;
  18635. }
  18636. if (pickResult.pickedSprite.actionManager) {
  18637. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18638. }
  18639. }
  18640. }
  18641. }
  18642. };
  18643. this._onPointerUp = function (evt) {
  18644. if (_this._totalPointersPressed === 0) {
  18645. return; // So we need to test it the pointer down was pressed before.
  18646. }
  18647. _this._totalPointersPressed--;
  18648. _this._pickedUpMesh = null;
  18649. _this._meshPickProceed = false;
  18650. _this._updatePointerPosition(evt);
  18651. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18652. // PreObservable support
  18653. if (_this.onPrePointerObservable.hasObservers()) {
  18654. if (!clickInfo.ignore) {
  18655. if (!clickInfo.hasSwiped) {
  18656. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18657. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18658. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18659. _this.onPrePointerObservable.notifyObservers(pi, type);
  18660. if (pi.skipOnPointerObservable) {
  18661. return;
  18662. }
  18663. }
  18664. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18665. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18666. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18667. _this.onPrePointerObservable.notifyObservers(pi, type);
  18668. if (pi.skipOnPointerObservable) {
  18669. return;
  18670. }
  18671. }
  18672. }
  18673. }
  18674. else {
  18675. var type = BABYLON.PointerEventTypes.POINTERUP;
  18676. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18677. _this.onPrePointerObservable.notifyObservers(pi, type);
  18678. if (pi.skipOnPointerObservable) {
  18679. return;
  18680. }
  18681. }
  18682. }
  18683. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18684. return;
  18685. }
  18686. if (!_this.pointerUpPredicate) {
  18687. _this.pointerUpPredicate = function (mesh) {
  18688. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18689. };
  18690. }
  18691. // Meshes
  18692. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18693. _this._initActionManager(null, clickInfo);
  18694. }
  18695. if (!pickResult) {
  18696. pickResult = _this._currentPickResult;
  18697. }
  18698. _this._processPointerUp(pickResult, evt, clickInfo);
  18699. // Sprites
  18700. if (_this.spriteManagers.length > 0) {
  18701. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18702. if (spritePickResult) {
  18703. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18704. if (spritePickResult.pickedSprite.actionManager) {
  18705. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18706. if (spritePickResult.pickedSprite.actionManager) {
  18707. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18708. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18709. }
  18710. }
  18711. }
  18712. }
  18713. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18714. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18715. }
  18716. }
  18717. }
  18718. _this._previousPickResult = _this._currentPickResult;
  18719. });
  18720. };
  18721. this._onKeyDown = function (evt) {
  18722. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18723. if (_this.onPreKeyboardObservable.hasObservers()) {
  18724. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18725. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18726. if (pi.skipOnPointerObservable) {
  18727. return;
  18728. }
  18729. }
  18730. if (_this.onKeyboardObservable.hasObservers()) {
  18731. var pi = new BABYLON.KeyboardInfo(type, evt);
  18732. _this.onKeyboardObservable.notifyObservers(pi, type);
  18733. }
  18734. if (_this.actionManager) {
  18735. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18736. }
  18737. };
  18738. this._onKeyUp = function (evt) {
  18739. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18740. if (_this.onPreKeyboardObservable.hasObservers()) {
  18741. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18742. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18743. if (pi.skipOnPointerObservable) {
  18744. return;
  18745. }
  18746. }
  18747. if (_this.onKeyboardObservable.hasObservers()) {
  18748. var pi = new BABYLON.KeyboardInfo(type, evt);
  18749. _this.onKeyboardObservable.notifyObservers(pi, type);
  18750. }
  18751. if (_this.actionManager) {
  18752. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18753. }
  18754. };
  18755. var engine = this.getEngine();
  18756. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18757. if (!canvas) {
  18758. return;
  18759. }
  18760. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18761. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18762. });
  18763. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18764. if (!canvas) {
  18765. return;
  18766. }
  18767. canvas.removeEventListener("keydown", _this._onKeyDown);
  18768. canvas.removeEventListener("keyup", _this._onKeyUp);
  18769. });
  18770. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18771. var canvas = this._engine.getRenderingCanvas();
  18772. if (!canvas) {
  18773. return;
  18774. }
  18775. if (attachMove) {
  18776. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18777. // Wheel
  18778. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18779. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18780. }
  18781. if (attachDown) {
  18782. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18783. }
  18784. if (attachUp) {
  18785. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18786. }
  18787. canvas.tabIndex = 1;
  18788. };
  18789. Scene.prototype.detachControl = function () {
  18790. var engine = this.getEngine();
  18791. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18792. var canvas = engine.getRenderingCanvas();
  18793. if (!canvas) {
  18794. return;
  18795. }
  18796. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18797. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18798. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18799. if (this._onCanvasBlurObserver) {
  18800. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18801. }
  18802. if (this._onCanvasFocusObserver) {
  18803. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18804. }
  18805. // Wheel
  18806. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18807. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18808. // Keyboard
  18809. canvas.removeEventListener("keydown", this._onKeyDown);
  18810. canvas.removeEventListener("keyup", this._onKeyUp);
  18811. // Observables
  18812. this.onKeyboardObservable.clear();
  18813. this.onPreKeyboardObservable.clear();
  18814. this.onPointerObservable.clear();
  18815. this.onPrePointerObservable.clear();
  18816. };
  18817. // Ready
  18818. Scene.prototype.isReady = function () {
  18819. if (this._isDisposed) {
  18820. return false;
  18821. }
  18822. if (this._pendingData.length > 0) {
  18823. return false;
  18824. }
  18825. var index;
  18826. // Geometries
  18827. for (index = 0; index < this._geometries.length; index++) {
  18828. var geometry = this._geometries[index];
  18829. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18830. return false;
  18831. }
  18832. }
  18833. // Meshes
  18834. for (index = 0; index < this.meshes.length; index++) {
  18835. var mesh = this.meshes[index];
  18836. if (!mesh.isEnabled()) {
  18837. continue;
  18838. }
  18839. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18840. continue;
  18841. }
  18842. if (!mesh.isReady()) {
  18843. return false;
  18844. }
  18845. var mat = mesh.material;
  18846. if (mat) {
  18847. if (!mat.isReady(mesh)) {
  18848. return false;
  18849. }
  18850. }
  18851. }
  18852. return true;
  18853. };
  18854. Scene.prototype.resetCachedMaterial = function () {
  18855. this._cachedMaterial = null;
  18856. this._cachedEffect = null;
  18857. this._cachedVisibility = null;
  18858. };
  18859. Scene.prototype.registerBeforeRender = function (func) {
  18860. this.onBeforeRenderObservable.add(func);
  18861. };
  18862. Scene.prototype.unregisterBeforeRender = function (func) {
  18863. this.onBeforeRenderObservable.removeCallback(func);
  18864. };
  18865. Scene.prototype.registerAfterRender = function (func) {
  18866. this.onAfterRenderObservable.add(func);
  18867. };
  18868. Scene.prototype.unregisterAfterRender = function (func) {
  18869. this.onAfterRenderObservable.removeCallback(func);
  18870. };
  18871. Scene.prototype._addPendingData = function (data) {
  18872. this._pendingData.push(data);
  18873. };
  18874. Scene.prototype._removePendingData = function (data) {
  18875. var wasLoading = this.isLoading;
  18876. var index = this._pendingData.indexOf(data);
  18877. if (index !== -1) {
  18878. this._pendingData.splice(index, 1);
  18879. }
  18880. if (wasLoading && !this.isLoading) {
  18881. this.onDataLoadedObservable.notifyObservers(this);
  18882. }
  18883. };
  18884. Scene.prototype.getWaitingItemsCount = function () {
  18885. return this._pendingData.length;
  18886. };
  18887. Object.defineProperty(Scene.prototype, "isLoading", {
  18888. get: function () {
  18889. return this._pendingData.length > 0;
  18890. },
  18891. enumerable: true,
  18892. configurable: true
  18893. });
  18894. /**
  18895. * Registers a function to be executed when the scene is ready.
  18896. * @param {Function} func - the function to be executed.
  18897. */
  18898. Scene.prototype.executeWhenReady = function (func) {
  18899. var _this = this;
  18900. this.onReadyObservable.add(func);
  18901. if (this._executeWhenReadyTimeoutId !== -1) {
  18902. return;
  18903. }
  18904. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18905. _this._checkIsReady();
  18906. }, 150);
  18907. };
  18908. Scene.prototype._checkIsReady = function () {
  18909. var _this = this;
  18910. if (this.isReady()) {
  18911. this.onReadyObservable.notifyObservers(this);
  18912. this.onReadyObservable.clear();
  18913. this._executeWhenReadyTimeoutId = -1;
  18914. return;
  18915. }
  18916. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18917. _this._checkIsReady();
  18918. }, 150);
  18919. };
  18920. // Animations
  18921. /**
  18922. * Will start the animation sequence of a given target
  18923. * @param target - the target
  18924. * @param {number} from - from which frame should animation start
  18925. * @param {number} to - till which frame should animation run.
  18926. * @param {boolean} [loop] - should the animation loop
  18927. * @param {number} [speedRatio] - the speed in which to run the animation
  18928. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18929. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18930. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18931. * See BABYLON.Animatable
  18932. */
  18933. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18934. if (speedRatio === void 0) { speedRatio = 1.0; }
  18935. if (from > to && speedRatio > 0) {
  18936. speedRatio *= -1;
  18937. }
  18938. this.stopAnimation(target);
  18939. if (!animatable) {
  18940. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18941. }
  18942. // Local animations
  18943. if (target.animations) {
  18944. animatable.appendAnimations(target, target.animations);
  18945. }
  18946. // Children animations
  18947. if (target.getAnimatables) {
  18948. var animatables = target.getAnimatables();
  18949. for (var index = 0; index < animatables.length; index++) {
  18950. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18951. }
  18952. }
  18953. animatable.reset();
  18954. return animatable;
  18955. };
  18956. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18957. if (speedRatio === undefined) {
  18958. speedRatio = 1.0;
  18959. }
  18960. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18961. return animatable;
  18962. };
  18963. Scene.prototype.getAnimatableByTarget = function (target) {
  18964. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18965. if (this._activeAnimatables[index].target === target) {
  18966. return this._activeAnimatables[index];
  18967. }
  18968. }
  18969. return null;
  18970. };
  18971. Object.defineProperty(Scene.prototype, "Animatables", {
  18972. get: function () {
  18973. return this._activeAnimatables;
  18974. },
  18975. enumerable: true,
  18976. configurable: true
  18977. });
  18978. /**
  18979. * Will stop the animation of the given target
  18980. * @param target - the target
  18981. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18982. * @see beginAnimation
  18983. */
  18984. Scene.prototype.stopAnimation = function (target, animationName) {
  18985. var animatable = this.getAnimatableByTarget(target);
  18986. if (animatable) {
  18987. animatable.stop(animationName);
  18988. }
  18989. };
  18990. Scene.prototype._animate = function () {
  18991. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18992. return;
  18993. }
  18994. // Getting time
  18995. var now = BABYLON.Tools.Now;
  18996. if (!this._animationTimeLast) {
  18997. if (this._pendingData.length > 0) {
  18998. return;
  18999. }
  19000. this._animationTimeLast = now;
  19001. }
  19002. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  19003. this._animationTime += deltaTime;
  19004. this._animationTimeLast = now;
  19005. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19006. this._activeAnimatables[index]._animate(this._animationTime);
  19007. }
  19008. };
  19009. // Matrix
  19010. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19011. this._useAlternateCameraConfiguration = active;
  19012. };
  19013. Scene.prototype.getViewMatrix = function () {
  19014. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19015. };
  19016. Scene.prototype.getProjectionMatrix = function () {
  19017. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19018. };
  19019. Scene.prototype.getTransformMatrix = function () {
  19020. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19021. };
  19022. Scene.prototype.setTransformMatrix = function (view, projection) {
  19023. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19024. return;
  19025. }
  19026. this._viewUpdateFlag = view.updateFlag;
  19027. this._projectionUpdateFlag = projection.updateFlag;
  19028. this._viewMatrix = view;
  19029. this._projectionMatrix = projection;
  19030. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19031. // Update frustum
  19032. if (!this._frustumPlanes) {
  19033. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19034. }
  19035. else {
  19036. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19037. }
  19038. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19039. var otherCamera = this.activeCamera._alternateCamera;
  19040. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19041. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19042. }
  19043. if (this._sceneUbo.useUbo) {
  19044. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19045. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19046. this._sceneUbo.update();
  19047. }
  19048. };
  19049. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19050. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19051. return;
  19052. }
  19053. this._alternateViewUpdateFlag = view.updateFlag;
  19054. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19055. this._alternateViewMatrix = view;
  19056. this._alternateProjectionMatrix = projection;
  19057. if (!this._alternateTransformMatrix) {
  19058. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19059. }
  19060. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19061. if (!this._alternateSceneUbo) {
  19062. this._createAlternateUbo();
  19063. }
  19064. if (this._alternateSceneUbo.useUbo) {
  19065. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19066. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19067. this._alternateSceneUbo.update();
  19068. }
  19069. };
  19070. Scene.prototype.getSceneUniformBuffer = function () {
  19071. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19072. };
  19073. // Methods
  19074. Scene.prototype.getUniqueId = function () {
  19075. var result = Scene._uniqueIdCounter;
  19076. Scene._uniqueIdCounter++;
  19077. return result;
  19078. };
  19079. Scene.prototype.addMesh = function (newMesh) {
  19080. this.meshes.push(newMesh);
  19081. //notify the collision coordinator
  19082. if (this.collisionCoordinator) {
  19083. this.collisionCoordinator.onMeshAdded(newMesh);
  19084. }
  19085. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19086. };
  19087. Scene.prototype.removeMesh = function (toRemove) {
  19088. var index = this.meshes.indexOf(toRemove);
  19089. if (index !== -1) {
  19090. // Remove from the scene if mesh found
  19091. this.meshes.splice(index, 1);
  19092. }
  19093. //notify the collision coordinator
  19094. if (this.collisionCoordinator) {
  19095. this.collisionCoordinator.onMeshRemoved(toRemove);
  19096. }
  19097. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19098. return index;
  19099. };
  19100. Scene.prototype.removeSkeleton = function (toRemove) {
  19101. var index = this.skeletons.indexOf(toRemove);
  19102. if (index !== -1) {
  19103. // Remove from the scene if found
  19104. this.skeletons.splice(index, 1);
  19105. }
  19106. return index;
  19107. };
  19108. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19109. var index = this.morphTargetManagers.indexOf(toRemove);
  19110. if (index !== -1) {
  19111. // Remove from the scene if found
  19112. this.morphTargetManagers.splice(index, 1);
  19113. }
  19114. return index;
  19115. };
  19116. Scene.prototype.removeLight = function (toRemove) {
  19117. var index = this.lights.indexOf(toRemove);
  19118. if (index !== -1) {
  19119. // Remove from the scene if mesh found
  19120. this.lights.splice(index, 1);
  19121. this.sortLightsByPriority();
  19122. }
  19123. this.onLightRemovedObservable.notifyObservers(toRemove);
  19124. return index;
  19125. };
  19126. Scene.prototype.removeCamera = function (toRemove) {
  19127. var index = this.cameras.indexOf(toRemove);
  19128. if (index !== -1) {
  19129. // Remove from the scene if mesh found
  19130. this.cameras.splice(index, 1);
  19131. }
  19132. // Remove from activeCameras
  19133. var index2 = this.activeCameras.indexOf(toRemove);
  19134. if (index2 !== -1) {
  19135. // Remove from the scene if mesh found
  19136. this.activeCameras.splice(index2, 1);
  19137. }
  19138. // Reset the activeCamera
  19139. if (this.activeCamera === toRemove) {
  19140. if (this.cameras.length > 0) {
  19141. this.activeCamera = this.cameras[0];
  19142. }
  19143. else {
  19144. this.activeCamera = null;
  19145. }
  19146. }
  19147. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19148. return index;
  19149. };
  19150. Scene.prototype.addLight = function (newLight) {
  19151. this.lights.push(newLight);
  19152. this.sortLightsByPriority();
  19153. this.onNewLightAddedObservable.notifyObservers(newLight);
  19154. };
  19155. Scene.prototype.sortLightsByPriority = function () {
  19156. if (this.requireLightSorting) {
  19157. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19158. }
  19159. };
  19160. Scene.prototype.addCamera = function (newCamera) {
  19161. this.cameras.push(newCamera);
  19162. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19163. };
  19164. /**
  19165. * Switch active camera
  19166. * @param {Camera} newCamera - new active camera
  19167. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19168. */
  19169. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19170. if (attachControl === void 0) { attachControl = true; }
  19171. var canvas = this._engine.getRenderingCanvas();
  19172. if (!canvas) {
  19173. return;
  19174. }
  19175. if (this.activeCamera) {
  19176. this.activeCamera.detachControl(canvas);
  19177. }
  19178. this.activeCamera = newCamera;
  19179. if (attachControl) {
  19180. newCamera.attachControl(canvas);
  19181. }
  19182. };
  19183. /**
  19184. * sets the active camera of the scene using its ID
  19185. * @param {string} id - the camera's ID
  19186. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19187. * @see activeCamera
  19188. */
  19189. Scene.prototype.setActiveCameraByID = function (id) {
  19190. var camera = this.getCameraByID(id);
  19191. if (camera) {
  19192. this.activeCamera = camera;
  19193. return camera;
  19194. }
  19195. return null;
  19196. };
  19197. /**
  19198. * sets the active camera of the scene using its name
  19199. * @param {string} name - the camera's name
  19200. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19201. * @see activeCamera
  19202. */
  19203. Scene.prototype.setActiveCameraByName = function (name) {
  19204. var camera = this.getCameraByName(name);
  19205. if (camera) {
  19206. this.activeCamera = camera;
  19207. return camera;
  19208. }
  19209. return null;
  19210. };
  19211. /**
  19212. * get a material using its id
  19213. * @param {string} the material's ID
  19214. * @return {BABYLON.Material|null} the material or null if none found.
  19215. */
  19216. Scene.prototype.getMaterialByID = function (id) {
  19217. for (var index = 0; index < this.materials.length; index++) {
  19218. if (this.materials[index].id === id) {
  19219. return this.materials[index];
  19220. }
  19221. }
  19222. return null;
  19223. };
  19224. /**
  19225. * get a material using its name
  19226. * @param {string} the material's name
  19227. * @return {BABYLON.Material|null} the material or null if none found.
  19228. */
  19229. Scene.prototype.getMaterialByName = function (name) {
  19230. for (var index = 0; index < this.materials.length; index++) {
  19231. if (this.materials[index].name === name) {
  19232. return this.materials[index];
  19233. }
  19234. }
  19235. return null;
  19236. };
  19237. Scene.prototype.getLensFlareSystemByName = function (name) {
  19238. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19239. if (this.lensFlareSystems[index].name === name) {
  19240. return this.lensFlareSystems[index];
  19241. }
  19242. }
  19243. return null;
  19244. };
  19245. Scene.prototype.getLensFlareSystemByID = function (id) {
  19246. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19247. if (this.lensFlareSystems[index].id === id) {
  19248. return this.lensFlareSystems[index];
  19249. }
  19250. }
  19251. return null;
  19252. };
  19253. Scene.prototype.getCameraByID = function (id) {
  19254. for (var index = 0; index < this.cameras.length; index++) {
  19255. if (this.cameras[index].id === id) {
  19256. return this.cameras[index];
  19257. }
  19258. }
  19259. return null;
  19260. };
  19261. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19262. for (var index = 0; index < this.cameras.length; index++) {
  19263. if (this.cameras[index].uniqueId === uniqueId) {
  19264. return this.cameras[index];
  19265. }
  19266. }
  19267. return null;
  19268. };
  19269. /**
  19270. * get a camera using its name
  19271. * @param {string} the camera's name
  19272. * @return {BABYLON.Camera|null} the camera or null if none found.
  19273. */
  19274. Scene.prototype.getCameraByName = function (name) {
  19275. for (var index = 0; index < this.cameras.length; index++) {
  19276. if (this.cameras[index].name === name) {
  19277. return this.cameras[index];
  19278. }
  19279. }
  19280. return null;
  19281. };
  19282. /**
  19283. * get a bone using its id
  19284. * @param {string} the bone's id
  19285. * @return {BABYLON.Bone|null} the bone or null if not found
  19286. */
  19287. Scene.prototype.getBoneByID = function (id) {
  19288. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19289. var skeleton = this.skeletons[skeletonIndex];
  19290. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19291. if (skeleton.bones[boneIndex].id === id) {
  19292. return skeleton.bones[boneIndex];
  19293. }
  19294. }
  19295. }
  19296. return null;
  19297. };
  19298. /**
  19299. * get a bone using its id
  19300. * @param {string} the bone's name
  19301. * @return {BABYLON.Bone|null} the bone or null if not found
  19302. */
  19303. Scene.prototype.getBoneByName = function (name) {
  19304. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19305. var skeleton = this.skeletons[skeletonIndex];
  19306. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19307. if (skeleton.bones[boneIndex].name === name) {
  19308. return skeleton.bones[boneIndex];
  19309. }
  19310. }
  19311. }
  19312. return null;
  19313. };
  19314. /**
  19315. * get a light node using its name
  19316. * @param {string} the light's name
  19317. * @return {BABYLON.Light|null} the light or null if none found.
  19318. */
  19319. Scene.prototype.getLightByName = function (name) {
  19320. for (var index = 0; index < this.lights.length; index++) {
  19321. if (this.lights[index].name === name) {
  19322. return this.lights[index];
  19323. }
  19324. }
  19325. return null;
  19326. };
  19327. /**
  19328. * get a light node using its ID
  19329. * @param {string} the light's id
  19330. * @return {BABYLON.Light|null} the light or null if none found.
  19331. */
  19332. Scene.prototype.getLightByID = function (id) {
  19333. for (var index = 0; index < this.lights.length; index++) {
  19334. if (this.lights[index].id === id) {
  19335. return this.lights[index];
  19336. }
  19337. }
  19338. return null;
  19339. };
  19340. /**
  19341. * get a light node using its scene-generated unique ID
  19342. * @param {number} the light's unique id
  19343. * @return {BABYLON.Light|null} the light or null if none found.
  19344. */
  19345. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19346. for (var index = 0; index < this.lights.length; index++) {
  19347. if (this.lights[index].uniqueId === uniqueId) {
  19348. return this.lights[index];
  19349. }
  19350. }
  19351. return null;
  19352. };
  19353. /**
  19354. * get a particle system by id
  19355. * @param id {number} the particle system id
  19356. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19357. */
  19358. Scene.prototype.getParticleSystemByID = function (id) {
  19359. for (var index = 0; index < this.particleSystems.length; index++) {
  19360. if (this.particleSystems[index].id === id) {
  19361. return this.particleSystems[index];
  19362. }
  19363. }
  19364. return null;
  19365. };
  19366. /**
  19367. * get a geometry using its ID
  19368. * @param {string} the geometry's id
  19369. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19370. */
  19371. Scene.prototype.getGeometryByID = function (id) {
  19372. for (var index = 0; index < this._geometries.length; index++) {
  19373. if (this._geometries[index].id === id) {
  19374. return this._geometries[index];
  19375. }
  19376. }
  19377. return null;
  19378. };
  19379. /**
  19380. * add a new geometry to this scene.
  19381. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19382. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19383. * @return {boolean} was the geometry added or not
  19384. */
  19385. Scene.prototype.pushGeometry = function (geometry, force) {
  19386. if (!force && this.getGeometryByID(geometry.id)) {
  19387. return false;
  19388. }
  19389. this._geometries.push(geometry);
  19390. //notify the collision coordinator
  19391. if (this.collisionCoordinator) {
  19392. this.collisionCoordinator.onGeometryAdded(geometry);
  19393. }
  19394. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19395. return true;
  19396. };
  19397. /**
  19398. * Removes an existing geometry
  19399. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19400. * @return {boolean} was the geometry removed or not
  19401. */
  19402. Scene.prototype.removeGeometry = function (geometry) {
  19403. var index = this._geometries.indexOf(geometry);
  19404. if (index > -1) {
  19405. this._geometries.splice(index, 1);
  19406. //notify the collision coordinator
  19407. if (this.collisionCoordinator) {
  19408. this.collisionCoordinator.onGeometryDeleted(geometry);
  19409. }
  19410. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19411. return true;
  19412. }
  19413. return false;
  19414. };
  19415. Scene.prototype.getGeometries = function () {
  19416. return this._geometries;
  19417. };
  19418. /**
  19419. * Get the first added mesh found of a given ID
  19420. * @param {string} id - the id to search for
  19421. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19422. */
  19423. Scene.prototype.getMeshByID = function (id) {
  19424. for (var index = 0; index < this.meshes.length; index++) {
  19425. if (this.meshes[index].id === id) {
  19426. return this.meshes[index];
  19427. }
  19428. }
  19429. return null;
  19430. };
  19431. Scene.prototype.getMeshesByID = function (id) {
  19432. return this.meshes.filter(function (m) {
  19433. return m.id === id;
  19434. });
  19435. };
  19436. /**
  19437. * Get a mesh with its auto-generated unique id
  19438. * @param {number} uniqueId - the unique id to search for
  19439. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19440. */
  19441. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19442. for (var index = 0; index < this.meshes.length; index++) {
  19443. if (this.meshes[index].uniqueId === uniqueId) {
  19444. return this.meshes[index];
  19445. }
  19446. }
  19447. return null;
  19448. };
  19449. /**
  19450. * Get a the last added mesh found of a given ID
  19451. * @param {string} id - the id to search for
  19452. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19453. */
  19454. Scene.prototype.getLastMeshByID = function (id) {
  19455. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19456. if (this.meshes[index].id === id) {
  19457. return this.meshes[index];
  19458. }
  19459. }
  19460. return null;
  19461. };
  19462. /**
  19463. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19464. * @param {string} id - the id to search for
  19465. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19466. */
  19467. Scene.prototype.getLastEntryByID = function (id) {
  19468. var index;
  19469. for (index = this.meshes.length - 1; index >= 0; index--) {
  19470. if (this.meshes[index].id === id) {
  19471. return this.meshes[index];
  19472. }
  19473. }
  19474. for (index = this.cameras.length - 1; index >= 0; index--) {
  19475. if (this.cameras[index].id === id) {
  19476. return this.cameras[index];
  19477. }
  19478. }
  19479. for (index = this.lights.length - 1; index >= 0; index--) {
  19480. if (this.lights[index].id === id) {
  19481. return this.lights[index];
  19482. }
  19483. }
  19484. return null;
  19485. };
  19486. Scene.prototype.getNodeByID = function (id) {
  19487. var mesh = this.getMeshByID(id);
  19488. if (mesh) {
  19489. return mesh;
  19490. }
  19491. var light = this.getLightByID(id);
  19492. if (light) {
  19493. return light;
  19494. }
  19495. var camera = this.getCameraByID(id);
  19496. if (camera) {
  19497. return camera;
  19498. }
  19499. var bone = this.getBoneByID(id);
  19500. return bone;
  19501. };
  19502. Scene.prototype.getNodeByName = function (name) {
  19503. var mesh = this.getMeshByName(name);
  19504. if (mesh) {
  19505. return mesh;
  19506. }
  19507. var light = this.getLightByName(name);
  19508. if (light) {
  19509. return light;
  19510. }
  19511. var camera = this.getCameraByName(name);
  19512. if (camera) {
  19513. return camera;
  19514. }
  19515. var bone = this.getBoneByName(name);
  19516. return bone;
  19517. };
  19518. Scene.prototype.getMeshByName = function (name) {
  19519. for (var index = 0; index < this.meshes.length; index++) {
  19520. if (this.meshes[index].name === name) {
  19521. return this.meshes[index];
  19522. }
  19523. }
  19524. return null;
  19525. };
  19526. Scene.prototype.getSoundByName = function (name) {
  19527. var index;
  19528. if (BABYLON.AudioEngine) {
  19529. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19530. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19531. return this.mainSoundTrack.soundCollection[index];
  19532. }
  19533. }
  19534. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19535. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19536. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19537. return this.soundTracks[sdIndex].soundCollection[index];
  19538. }
  19539. }
  19540. }
  19541. }
  19542. return null;
  19543. };
  19544. Scene.prototype.getLastSkeletonByID = function (id) {
  19545. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19546. if (this.skeletons[index].id === id) {
  19547. return this.skeletons[index];
  19548. }
  19549. }
  19550. return null;
  19551. };
  19552. Scene.prototype.getSkeletonById = function (id) {
  19553. for (var index = 0; index < this.skeletons.length; index++) {
  19554. if (this.skeletons[index].id === id) {
  19555. return this.skeletons[index];
  19556. }
  19557. }
  19558. return null;
  19559. };
  19560. Scene.prototype.getSkeletonByName = function (name) {
  19561. for (var index = 0; index < this.skeletons.length; index++) {
  19562. if (this.skeletons[index].name === name) {
  19563. return this.skeletons[index];
  19564. }
  19565. }
  19566. return null;
  19567. };
  19568. Scene.prototype.getMorphTargetManagerById = function (id) {
  19569. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19570. if (this.morphTargetManagers[index].uniqueId === id) {
  19571. return this.morphTargetManagers[index];
  19572. }
  19573. }
  19574. return null;
  19575. };
  19576. Scene.prototype.isActiveMesh = function (mesh) {
  19577. return (this._activeMeshes.indexOf(mesh) !== -1);
  19578. };
  19579. /**
  19580. * Return a the first highlight layer of the scene with a given name.
  19581. * @param name The name of the highlight layer to look for.
  19582. * @return The highlight layer if found otherwise null.
  19583. */
  19584. Scene.prototype.getHighlightLayerByName = function (name) {
  19585. for (var index = 0; index < this.highlightLayers.length; index++) {
  19586. if (this.highlightLayers[index].name === name) {
  19587. return this.highlightLayers[index];
  19588. }
  19589. }
  19590. return null;
  19591. };
  19592. Object.defineProperty(Scene.prototype, "uid", {
  19593. /**
  19594. * Return a unique id as a string which can serve as an identifier for the scene
  19595. */
  19596. get: function () {
  19597. if (!this._uid) {
  19598. this._uid = BABYLON.Tools.RandomId();
  19599. }
  19600. return this._uid;
  19601. },
  19602. enumerable: true,
  19603. configurable: true
  19604. });
  19605. /**
  19606. * Add an externaly attached data from its key.
  19607. * This method call will fail and return false, if such key already exists.
  19608. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19609. * @param key the unique key that identifies the data
  19610. * @param data the data object to associate to the key for this Engine instance
  19611. * @return true if no such key were already present and the data was added successfully, false otherwise
  19612. */
  19613. Scene.prototype.addExternalData = function (key, data) {
  19614. if (!this._externalData) {
  19615. this._externalData = new BABYLON.StringDictionary();
  19616. }
  19617. return this._externalData.add(key, data);
  19618. };
  19619. /**
  19620. * Get an externaly attached data from its key
  19621. * @param key the unique key that identifies the data
  19622. * @return the associated data, if present (can be null), or undefined if not present
  19623. */
  19624. Scene.prototype.getExternalData = function (key) {
  19625. if (!this._externalData) {
  19626. return null;
  19627. }
  19628. return this._externalData.get(key);
  19629. };
  19630. /**
  19631. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19632. * @param key the unique key that identifies the data
  19633. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19634. * @return the associated data, can be null if the factory returned null.
  19635. */
  19636. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19637. if (!this._externalData) {
  19638. this._externalData = new BABYLON.StringDictionary();
  19639. }
  19640. return this._externalData.getOrAddWithFactory(key, factory);
  19641. };
  19642. /**
  19643. * Remove an externaly attached data from the Engine instance
  19644. * @param key the unique key that identifies the data
  19645. * @return true if the data was successfully removed, false if it doesn't exist
  19646. */
  19647. Scene.prototype.removeExternalData = function (key) {
  19648. return this._externalData.remove(key);
  19649. };
  19650. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19651. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19652. var material = subMesh.getMaterial();
  19653. if (mesh.showSubMeshesBoundingBox) {
  19654. var boundingInfo = subMesh.getBoundingInfo();
  19655. if (boundingInfo) {
  19656. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19657. }
  19658. }
  19659. if (material) {
  19660. // Render targets
  19661. if (material.getRenderTargetTextures) {
  19662. if (this._processedMaterials.indexOf(material) === -1) {
  19663. this._processedMaterials.push(material);
  19664. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19665. }
  19666. }
  19667. // Dispatch
  19668. this._activeIndices.addCount(subMesh.indexCount, false);
  19669. this._renderingManager.dispatch(subMesh);
  19670. }
  19671. }
  19672. };
  19673. Scene.prototype._isInIntermediateRendering = function () {
  19674. return this._intermediateRendering;
  19675. };
  19676. /**
  19677. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19678. */
  19679. Scene.prototype.freezeActiveMeshes = function () {
  19680. this._evaluateActiveMeshes();
  19681. this._activeMeshesFrozen = true;
  19682. return this;
  19683. };
  19684. /**
  19685. * Use this function to restart evaluating active meshes on every frame
  19686. */
  19687. Scene.prototype.unfreezeActiveMeshes = function () {
  19688. this._activeMeshesFrozen = false;
  19689. return this;
  19690. };
  19691. Scene.prototype._evaluateActiveMeshes = function () {
  19692. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19693. return;
  19694. }
  19695. if (!this.activeCamera) {
  19696. return;
  19697. }
  19698. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19699. this.activeCamera._activeMeshes.reset();
  19700. this._activeMeshes.reset();
  19701. this._renderingManager.reset();
  19702. this._processedMaterials.reset();
  19703. this._activeParticleSystems.reset();
  19704. this._activeSkeletons.reset();
  19705. this._softwareSkinnedMeshes.reset();
  19706. if (this._boundingBoxRenderer) {
  19707. this._boundingBoxRenderer.reset();
  19708. }
  19709. // Meshes
  19710. var meshes;
  19711. var len;
  19712. if (this._selectionOctree) {
  19713. var selection = this._selectionOctree.select(this._frustumPlanes);
  19714. meshes = selection.data;
  19715. len = selection.length;
  19716. }
  19717. else {
  19718. len = this.meshes.length;
  19719. meshes = this.meshes;
  19720. }
  19721. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19722. var mesh = meshes[meshIndex];
  19723. if (mesh.isBlocked) {
  19724. continue;
  19725. }
  19726. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19727. if (!mesh.isReady() || !mesh.isEnabled()) {
  19728. continue;
  19729. }
  19730. mesh.computeWorldMatrix();
  19731. // Intersections
  19732. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19733. this._meshesForIntersections.pushNoDuplicate(mesh);
  19734. }
  19735. // Switch to current LOD
  19736. var meshLOD = mesh.getLOD(this.activeCamera);
  19737. if (!meshLOD) {
  19738. continue;
  19739. }
  19740. mesh._preActivate();
  19741. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19742. this._activeMeshes.push(mesh);
  19743. this.activeCamera._activeMeshes.push(mesh);
  19744. mesh._activate(this._renderId);
  19745. if (meshLOD !== mesh) {
  19746. meshLOD._activate(this._renderId);
  19747. }
  19748. this._activeMesh(mesh, meshLOD);
  19749. }
  19750. }
  19751. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19752. // Particle systems
  19753. if (this.particlesEnabled) {
  19754. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  19755. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19756. var particleSystem = this.particleSystems[particleIndex];
  19757. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19758. continue;
  19759. }
  19760. var emitter = particleSystem.emitter;
  19761. if (!emitter.position || emitter.isEnabled()) {
  19762. this._activeParticleSystems.push(particleSystem);
  19763. particleSystem.animate();
  19764. this._renderingManager.dispatchParticles(particleSystem);
  19765. }
  19766. }
  19767. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  19768. }
  19769. };
  19770. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19771. if (mesh.skeleton && this.skeletonsEnabled) {
  19772. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19773. mesh.skeleton.prepare();
  19774. }
  19775. if (!mesh.computeBonesUsingShaders) {
  19776. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19777. }
  19778. }
  19779. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19780. var boundingInfo = sourceMesh.getBoundingInfo();
  19781. if (boundingInfo) {
  19782. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19783. }
  19784. }
  19785. if (mesh && mesh.subMeshes) {
  19786. // Submeshes Octrees
  19787. var len;
  19788. var subMeshes;
  19789. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19790. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19791. len = intersections.length;
  19792. subMeshes = intersections.data;
  19793. }
  19794. else {
  19795. subMeshes = mesh.subMeshes;
  19796. len = subMeshes.length;
  19797. }
  19798. for (var subIndex = 0; subIndex < len; subIndex++) {
  19799. var subMesh = subMeshes[subIndex];
  19800. this._evaluateSubMesh(subMesh, mesh);
  19801. }
  19802. }
  19803. };
  19804. Scene.prototype.updateTransformMatrix = function (force) {
  19805. if (!this.activeCamera) {
  19806. return;
  19807. }
  19808. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19809. };
  19810. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19811. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19812. };
  19813. Scene.prototype._renderForCamera = function (camera) {
  19814. if (camera && camera._skipRendering) {
  19815. return;
  19816. }
  19817. var engine = this._engine;
  19818. this.activeCamera = camera;
  19819. if (!this.activeCamera)
  19820. throw new Error("Active camera not set");
  19821. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19822. // Viewport
  19823. engine.setViewport(this.activeCamera.viewport);
  19824. // Camera
  19825. this.resetCachedMaterial();
  19826. this._renderId++;
  19827. this.activeCamera.update();
  19828. this.updateTransformMatrix();
  19829. if (camera._alternateCamera) {
  19830. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19831. this._alternateRendering = true;
  19832. }
  19833. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19834. // Meshes
  19835. this._evaluateActiveMeshes();
  19836. // Software skinning
  19837. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19838. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19839. mesh.applySkeleton(mesh.skeleton);
  19840. }
  19841. // Render targets
  19842. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19843. var needsRestoreFrameBuffer = false;
  19844. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19845. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19846. }
  19847. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19848. this._intermediateRendering = true;
  19849. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19850. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19851. var renderTarget = this._renderTargets.data[renderIndex];
  19852. if (renderTarget._shouldRender()) {
  19853. this._renderId++;
  19854. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19855. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19856. }
  19857. }
  19858. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19859. this._intermediateRendering = false;
  19860. this._renderId++;
  19861. needsRestoreFrameBuffer = true; // Restore back buffer
  19862. }
  19863. // Render HighlightLayer Texture
  19864. var stencilState = this._engine.getStencilBuffer();
  19865. var renderhighlights = false;
  19866. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19867. this._intermediateRendering = true;
  19868. for (var i = 0; i < this.highlightLayers.length; i++) {
  19869. var highlightLayer = this.highlightLayers[i];
  19870. if (highlightLayer.shouldRender() &&
  19871. (!highlightLayer.camera ||
  19872. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19873. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19874. renderhighlights = true;
  19875. var renderTarget = highlightLayer._mainTexture;
  19876. if (renderTarget._shouldRender()) {
  19877. this._renderId++;
  19878. renderTarget.render(false, false);
  19879. needsRestoreFrameBuffer = true;
  19880. }
  19881. }
  19882. }
  19883. this._intermediateRendering = false;
  19884. this._renderId++;
  19885. }
  19886. if (needsRestoreFrameBuffer) {
  19887. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19888. }
  19889. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19890. // Prepare Frame
  19891. this.postProcessManager._prepareFrame();
  19892. // Backgrounds
  19893. var layerIndex;
  19894. var layer;
  19895. if (this.layers.length) {
  19896. engine.setDepthBuffer(false);
  19897. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19898. layer = this.layers[layerIndex];
  19899. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19900. layer.render();
  19901. }
  19902. }
  19903. engine.setDepthBuffer(true);
  19904. }
  19905. // Activate HighlightLayer stencil
  19906. if (renderhighlights) {
  19907. this._engine.setStencilBuffer(true);
  19908. }
  19909. // Render
  19910. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  19911. this._renderingManager.render(null, null, true, true);
  19912. this.onAfterDrawPhaseObservable.notifyObservers(this);
  19913. // Restore HighlightLayer stencil
  19914. if (renderhighlights) {
  19915. this._engine.setStencilBuffer(stencilState);
  19916. }
  19917. // Bounding boxes
  19918. if (this._boundingBoxRenderer) {
  19919. this._boundingBoxRenderer.render();
  19920. }
  19921. // Lens flares
  19922. if (this.lensFlaresEnabled) {
  19923. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19924. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19925. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19926. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19927. lensFlareSystem.render();
  19928. }
  19929. }
  19930. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19931. }
  19932. // Foregrounds
  19933. if (this.layers.length) {
  19934. engine.setDepthBuffer(false);
  19935. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19936. layer = this.layers[layerIndex];
  19937. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19938. layer.render();
  19939. }
  19940. }
  19941. engine.setDepthBuffer(true);
  19942. }
  19943. // Highlight Layer
  19944. if (renderhighlights) {
  19945. engine.setDepthBuffer(false);
  19946. for (var i = 0; i < this.highlightLayers.length; i++) {
  19947. if (this.highlightLayers[i].shouldRender()) {
  19948. this.highlightLayers[i].render();
  19949. }
  19950. }
  19951. engine.setDepthBuffer(true);
  19952. }
  19953. // Finalize frame
  19954. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19955. // Reset some special arrays
  19956. this._renderTargets.reset();
  19957. this._alternateRendering = false;
  19958. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19959. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19960. };
  19961. Scene.prototype._processSubCameras = function (camera) {
  19962. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19963. this._renderForCamera(camera);
  19964. return;
  19965. }
  19966. // Update camera
  19967. if (this.activeCamera) {
  19968. this.activeCamera.update();
  19969. }
  19970. // rig cameras
  19971. for (var index = 0; index < camera._rigCameras.length; index++) {
  19972. this._renderForCamera(camera._rigCameras[index]);
  19973. }
  19974. this.activeCamera = camera;
  19975. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19976. };
  19977. Scene.prototype._checkIntersections = function () {
  19978. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19979. var sourceMesh = this._meshesForIntersections.data[index];
  19980. if (!sourceMesh.actionManager) {
  19981. continue;
  19982. }
  19983. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19984. var action = sourceMesh.actionManager.actions[actionIndex];
  19985. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19986. var parameters = action.getTriggerParameter();
  19987. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19988. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19989. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19990. if (areIntersecting && currentIntersectionInProgress === -1) {
  19991. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19992. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19993. sourceMesh._intersectionsInProgress.push(otherMesh);
  19994. }
  19995. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19996. sourceMesh._intersectionsInProgress.push(otherMesh);
  19997. }
  19998. }
  19999. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20000. //They intersected, and now they don't.
  20001. //is this trigger an exit trigger? execute an event.
  20002. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20003. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20004. }
  20005. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20006. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20007. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20008. }
  20009. }
  20010. }
  20011. }
  20012. }
  20013. };
  20014. Scene.prototype.render = function () {
  20015. if (this.isDisposed) {
  20016. return;
  20017. }
  20018. this._activeParticles.fetchNewFrame();
  20019. this._totalVertices.fetchNewFrame();
  20020. this._activeIndices.fetchNewFrame();
  20021. this._activeBones.fetchNewFrame();
  20022. this._meshesForIntersections.reset();
  20023. this.resetCachedMaterial();
  20024. this.onBeforeAnimationsObservable.notifyObservers(this);
  20025. // Actions
  20026. if (this.actionManager) {
  20027. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20028. }
  20029. //Simplification Queue
  20030. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20031. this.simplificationQueue.executeNext();
  20032. }
  20033. if (this._engine.isDeterministicLockStep()) {
  20034. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  20035. var defaultTimeStep = (60.0 / 1000.0);
  20036. if (this._physicsEngine) {
  20037. defaultTimeStep = this._physicsEngine.getTimeStep();
  20038. }
  20039. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20040. this._timeAccumulator += deltaTime;
  20041. // compute the amount of fixed steps we should have taken since the last step
  20042. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  20043. internalSteps = Math.min(internalSteps, maxSubSteps);
  20044. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  20045. this.onBeforeStepObservable.notifyObservers(this);
  20046. // Animations
  20047. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  20048. this._animate();
  20049. this.onAfterAnimationsObservable.notifyObservers(this);
  20050. // Physics
  20051. if (this._physicsEngine) {
  20052. this.onBeforePhysicsObservable.notifyObservers(this);
  20053. this._physicsEngine._step(defaultTimeStep);
  20054. this.onAfterPhysicsObservable.notifyObservers(this);
  20055. }
  20056. this._timeAccumulator -= defaultTimeStep;
  20057. this.onAfterStepObservable.notifyObservers(this);
  20058. this._currentStepId++;
  20059. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  20060. this._evaluateActiveMeshes();
  20061. }
  20062. }
  20063. }
  20064. else {
  20065. // Animations
  20066. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20067. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20068. this._animate();
  20069. this.onAfterAnimationsObservable.notifyObservers(this);
  20070. // Physics
  20071. if (this._physicsEngine) {
  20072. this.onBeforePhysicsObservable.notifyObservers(this);
  20073. this._physicsEngine._step(deltaTime / 1000.0);
  20074. this.onAfterPhysicsObservable.notifyObservers(this);
  20075. }
  20076. }
  20077. // Before render
  20078. this.onBeforeRenderObservable.notifyObservers(this);
  20079. // Customs render targets
  20080. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20081. var engine = this.getEngine();
  20082. var currentActiveCamera = this.activeCamera;
  20083. if (this.renderTargetsEnabled) {
  20084. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20085. this._intermediateRendering = true;
  20086. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20087. var renderTarget = this.customRenderTargets[customIndex];
  20088. if (renderTarget._shouldRender()) {
  20089. this._renderId++;
  20090. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20091. if (!this.activeCamera)
  20092. throw new Error("Active camera not set");
  20093. // Viewport
  20094. engine.setViewport(this.activeCamera.viewport);
  20095. // Camera
  20096. this.updateTransformMatrix();
  20097. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20098. }
  20099. }
  20100. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20101. this._intermediateRendering = false;
  20102. this._renderId++;
  20103. }
  20104. // Restore back buffer
  20105. if (this.customRenderTargets.length > 0) {
  20106. engine.restoreDefaultFramebuffer();
  20107. }
  20108. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20109. this.activeCamera = currentActiveCamera;
  20110. // Procedural textures
  20111. if (this.proceduralTexturesEnabled) {
  20112. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20113. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20114. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20115. if (proceduralTexture._shouldRender()) {
  20116. proceduralTexture.render();
  20117. }
  20118. }
  20119. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20120. }
  20121. // Clear
  20122. if (this.autoClearDepthAndStencil || this.autoClear) {
  20123. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20124. }
  20125. // Shadows
  20126. if (this.shadowsEnabled) {
  20127. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20128. var light = this.lights[lightIndex];
  20129. var shadowGenerator = light.getShadowGenerator();
  20130. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20131. var shadowMap = (shadowGenerator.getShadowMap());
  20132. if (this.textures.indexOf(shadowMap) !== -1) {
  20133. this._renderTargets.push(shadowMap);
  20134. }
  20135. }
  20136. }
  20137. }
  20138. // Depth renderer
  20139. if (this._depthRenderer) {
  20140. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20141. }
  20142. // Geometry renderer
  20143. if (this._geometryBufferRenderer) {
  20144. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20145. }
  20146. // RenderPipeline
  20147. if (this._postProcessRenderPipelineManager) {
  20148. this._postProcessRenderPipelineManager.update();
  20149. }
  20150. // Multi-cameras?
  20151. if (this.activeCameras.length > 0) {
  20152. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20153. if (cameraIndex > 0) {
  20154. this._engine.clear(null, false, true, true);
  20155. }
  20156. this._processSubCameras(this.activeCameras[cameraIndex]);
  20157. }
  20158. }
  20159. else {
  20160. if (!this.activeCamera) {
  20161. throw new Error("No camera defined");
  20162. }
  20163. this._processSubCameras(this.activeCamera);
  20164. }
  20165. // Intersection checks
  20166. this._checkIntersections();
  20167. // Update the audio listener attached to the camera
  20168. if (BABYLON.AudioEngine) {
  20169. this._updateAudioParameters();
  20170. }
  20171. // After render
  20172. if (this.afterRender) {
  20173. this.afterRender();
  20174. }
  20175. this.onAfterRenderObservable.notifyObservers(this);
  20176. // Cleaning
  20177. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20178. var data = this._toBeDisposed.data[index];
  20179. if (data) {
  20180. data.dispose();
  20181. }
  20182. this._toBeDisposed[index] = null;
  20183. }
  20184. this._toBeDisposed.reset();
  20185. if (this.dumpNextRenderTargets) {
  20186. this.dumpNextRenderTargets = false;
  20187. }
  20188. this._activeBones.addCount(0, true);
  20189. this._activeIndices.addCount(0, true);
  20190. this._activeParticles.addCount(0, true);
  20191. };
  20192. Scene.prototype._updateAudioParameters = function () {
  20193. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20194. return;
  20195. }
  20196. var listeningCamera;
  20197. var audioEngine = BABYLON.Engine.audioEngine;
  20198. if (this.activeCameras.length > 0) {
  20199. listeningCamera = this.activeCameras[0];
  20200. }
  20201. else {
  20202. listeningCamera = this.activeCamera;
  20203. }
  20204. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20205. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20206. // for VR cameras
  20207. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20208. listeningCamera = listeningCamera.rigCameras[0];
  20209. }
  20210. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20211. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20212. cameraDirection.normalize();
  20213. // To avoid some errors on GearVR
  20214. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20215. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20216. }
  20217. var i;
  20218. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20219. var sound = this.mainSoundTrack.soundCollection[i];
  20220. if (sound.useCustomAttenuation) {
  20221. sound.updateDistanceFromListener();
  20222. }
  20223. }
  20224. for (i = 0; i < this.soundTracks.length; i++) {
  20225. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20226. sound = this.soundTracks[i].soundCollection[j];
  20227. if (sound.useCustomAttenuation) {
  20228. sound.updateDistanceFromListener();
  20229. }
  20230. }
  20231. }
  20232. }
  20233. };
  20234. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20235. // Audio
  20236. get: function () {
  20237. return this._audioEnabled;
  20238. },
  20239. set: function (value) {
  20240. this._audioEnabled = value;
  20241. if (BABYLON.AudioEngine) {
  20242. if (this._audioEnabled) {
  20243. this._enableAudio();
  20244. }
  20245. else {
  20246. this._disableAudio();
  20247. }
  20248. }
  20249. },
  20250. enumerable: true,
  20251. configurable: true
  20252. });
  20253. Scene.prototype._disableAudio = function () {
  20254. var i;
  20255. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20256. this.mainSoundTrack.soundCollection[i].pause();
  20257. }
  20258. for (i = 0; i < this.soundTracks.length; i++) {
  20259. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20260. this.soundTracks[i].soundCollection[j].pause();
  20261. }
  20262. }
  20263. };
  20264. Scene.prototype._enableAudio = function () {
  20265. var i;
  20266. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20267. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20268. this.mainSoundTrack.soundCollection[i].play();
  20269. }
  20270. }
  20271. for (i = 0; i < this.soundTracks.length; i++) {
  20272. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20273. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20274. this.soundTracks[i].soundCollection[j].play();
  20275. }
  20276. }
  20277. }
  20278. };
  20279. Object.defineProperty(Scene.prototype, "headphone", {
  20280. get: function () {
  20281. return this._headphone;
  20282. },
  20283. set: function (value) {
  20284. this._headphone = value;
  20285. if (BABYLON.AudioEngine) {
  20286. if (this._headphone) {
  20287. this._switchAudioModeForHeadphones();
  20288. }
  20289. else {
  20290. this._switchAudioModeForNormalSpeakers();
  20291. }
  20292. }
  20293. },
  20294. enumerable: true,
  20295. configurable: true
  20296. });
  20297. Scene.prototype._switchAudioModeForHeadphones = function () {
  20298. this.mainSoundTrack.switchPanningModelToHRTF();
  20299. for (var i = 0; i < this.soundTracks.length; i++) {
  20300. this.soundTracks[i].switchPanningModelToHRTF();
  20301. }
  20302. };
  20303. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20304. this.mainSoundTrack.switchPanningModelToEqualPower();
  20305. for (var i = 0; i < this.soundTracks.length; i++) {
  20306. this.soundTracks[i].switchPanningModelToEqualPower();
  20307. }
  20308. };
  20309. Scene.prototype.enableDepthRenderer = function () {
  20310. if (this._depthRenderer) {
  20311. return this._depthRenderer;
  20312. }
  20313. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20314. return this._depthRenderer;
  20315. };
  20316. Scene.prototype.disableDepthRenderer = function () {
  20317. if (!this._depthRenderer) {
  20318. return;
  20319. }
  20320. this._depthRenderer.dispose();
  20321. this._depthRenderer = null;
  20322. };
  20323. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20324. if (ratio === void 0) { ratio = 1; }
  20325. if (this._geometryBufferRenderer) {
  20326. return this._geometryBufferRenderer;
  20327. }
  20328. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20329. if (!this._geometryBufferRenderer.isSupported) {
  20330. this._geometryBufferRenderer = null;
  20331. }
  20332. return this._geometryBufferRenderer;
  20333. };
  20334. Scene.prototype.disableGeometryBufferRenderer = function () {
  20335. if (!this._geometryBufferRenderer) {
  20336. return;
  20337. }
  20338. this._geometryBufferRenderer.dispose();
  20339. this._geometryBufferRenderer = null;
  20340. };
  20341. Scene.prototype.freezeMaterials = function () {
  20342. for (var i = 0; i < this.materials.length; i++) {
  20343. this.materials[i].freeze();
  20344. }
  20345. };
  20346. Scene.prototype.unfreezeMaterials = function () {
  20347. for (var i = 0; i < this.materials.length; i++) {
  20348. this.materials[i].unfreeze();
  20349. }
  20350. };
  20351. Scene.prototype.dispose = function () {
  20352. this.beforeRender = null;
  20353. this.afterRender = null;
  20354. this.skeletons = [];
  20355. this.morphTargetManagers = [];
  20356. this.importedMeshesFiles = new Array();
  20357. this.resetCachedMaterial();
  20358. if (this._depthRenderer) {
  20359. this._depthRenderer.dispose();
  20360. }
  20361. if (this._gamepadManager) {
  20362. this._gamepadManager.dispose();
  20363. this._gamepadManager = null;
  20364. }
  20365. // Smart arrays
  20366. if (this.activeCamera) {
  20367. this.activeCamera._activeMeshes.dispose();
  20368. this.activeCamera = null;
  20369. }
  20370. this._activeMeshes.dispose();
  20371. this._renderingManager.dispose();
  20372. this._processedMaterials.dispose();
  20373. this._activeParticleSystems.dispose();
  20374. this._activeSkeletons.dispose();
  20375. this._softwareSkinnedMeshes.dispose();
  20376. this._renderTargets.dispose();
  20377. if (this._boundingBoxRenderer) {
  20378. this._boundingBoxRenderer.dispose();
  20379. }
  20380. this._meshesForIntersections.dispose();
  20381. this._toBeDisposed.dispose();
  20382. // Debug layer
  20383. if (this._debugLayer) {
  20384. this._debugLayer.hide();
  20385. }
  20386. // Events
  20387. this.onDisposeObservable.notifyObservers(this);
  20388. this.onDisposeObservable.clear();
  20389. this.onBeforeRenderObservable.clear();
  20390. this.onAfterRenderObservable.clear();
  20391. this.OnBeforeRenderTargetsRenderObservable.clear();
  20392. this.OnAfterRenderTargetsRenderObservable.clear();
  20393. this.onAfterStepObservable.clear();
  20394. this.onBeforeStepObservable.clear();
  20395. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20396. this.onAfterActiveMeshesEvaluationObservable.clear();
  20397. this.onBeforeParticlesRenderingObservable.clear();
  20398. this.onAfterParticlesRenderingObservable.clear();
  20399. this.onBeforeSpritesRenderingObservable.clear();
  20400. this.onAfterSpritesRenderingObservable.clear();
  20401. this.onBeforeDrawPhaseObservable.clear();
  20402. this.onAfterDrawPhaseObservable.clear();
  20403. this.onBeforePhysicsObservable.clear();
  20404. this.onAfterPhysicsObservable.clear();
  20405. this.onBeforeAnimationsObservable.clear();
  20406. this.onAfterAnimationsObservable.clear();
  20407. this.onDataLoadedObservable.clear();
  20408. this.detachControl();
  20409. // Release sounds & sounds tracks
  20410. if (BABYLON.AudioEngine) {
  20411. this.disposeSounds();
  20412. }
  20413. // VR Helper
  20414. if (this.VRHelper) {
  20415. this.VRHelper.dispose();
  20416. }
  20417. // Detach cameras
  20418. var canvas = this._engine.getRenderingCanvas();
  20419. if (canvas) {
  20420. var index;
  20421. for (index = 0; index < this.cameras.length; index++) {
  20422. this.cameras[index].detachControl(canvas);
  20423. }
  20424. }
  20425. // Release lights
  20426. while (this.lights.length) {
  20427. this.lights[0].dispose();
  20428. }
  20429. // Release meshes
  20430. while (this.meshes.length) {
  20431. this.meshes[0].dispose(true);
  20432. }
  20433. // Release cameras
  20434. while (this.cameras.length) {
  20435. this.cameras[0].dispose();
  20436. }
  20437. // Release materials
  20438. if (this.defaultMaterial) {
  20439. this.defaultMaterial.dispose();
  20440. }
  20441. while (this.multiMaterials.length) {
  20442. this.multiMaterials[0].dispose();
  20443. }
  20444. while (this.materials.length) {
  20445. this.materials[0].dispose();
  20446. }
  20447. // Release particles
  20448. while (this.particleSystems.length) {
  20449. this.particleSystems[0].dispose();
  20450. }
  20451. // Release sprites
  20452. while (this.spriteManagers.length) {
  20453. this.spriteManagers[0].dispose();
  20454. }
  20455. // Release postProcesses
  20456. while (this.postProcesses.length) {
  20457. this.postProcesses[0].dispose();
  20458. }
  20459. // Release layers
  20460. while (this.layers.length) {
  20461. this.layers[0].dispose();
  20462. }
  20463. while (this.highlightLayers.length) {
  20464. this.highlightLayers[0].dispose();
  20465. }
  20466. // Release textures
  20467. while (this.textures.length) {
  20468. this.textures[0].dispose();
  20469. }
  20470. // Release UBO
  20471. this._sceneUbo.dispose();
  20472. if (this._alternateSceneUbo) {
  20473. this._alternateSceneUbo.dispose();
  20474. }
  20475. // Post-processes
  20476. this.postProcessManager.dispose();
  20477. if (this._postProcessRenderPipelineManager) {
  20478. this._postProcessRenderPipelineManager.dispose();
  20479. }
  20480. // Physics
  20481. if (this._physicsEngine) {
  20482. this.disablePhysicsEngine();
  20483. }
  20484. // Remove from engine
  20485. index = this._engine.scenes.indexOf(this);
  20486. if (index > -1) {
  20487. this._engine.scenes.splice(index, 1);
  20488. }
  20489. this._engine.wipeCaches();
  20490. this._isDisposed = true;
  20491. };
  20492. Object.defineProperty(Scene.prototype, "isDisposed", {
  20493. get: function () {
  20494. return this._isDisposed;
  20495. },
  20496. enumerable: true,
  20497. configurable: true
  20498. });
  20499. // Release sounds & sounds tracks
  20500. Scene.prototype.disposeSounds = function () {
  20501. if (!this._mainSoundTrack) {
  20502. return;
  20503. }
  20504. this.mainSoundTrack.dispose();
  20505. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20506. this.soundTracks[scIndex].dispose();
  20507. }
  20508. };
  20509. // Octrees
  20510. Scene.prototype.getWorldExtends = function () {
  20511. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20512. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20513. for (var index = 0; index < this.meshes.length; index++) {
  20514. var mesh = this.meshes[index];
  20515. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20516. continue;
  20517. }
  20518. mesh.computeWorldMatrix(true);
  20519. var boundingInfo = mesh.getBoundingInfo();
  20520. if (boundingInfo) {
  20521. var minBox = boundingInfo.boundingBox.minimumWorld;
  20522. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20523. BABYLON.Tools.CheckExtends(minBox, min, max);
  20524. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20525. }
  20526. }
  20527. return {
  20528. min: min,
  20529. max: max
  20530. };
  20531. };
  20532. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20533. if (maxCapacity === void 0) { maxCapacity = 64; }
  20534. if (maxDepth === void 0) { maxDepth = 2; }
  20535. if (!this._selectionOctree) {
  20536. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20537. }
  20538. var worldExtends = this.getWorldExtends();
  20539. // Update octree
  20540. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20541. return this._selectionOctree;
  20542. };
  20543. // Picking
  20544. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20545. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20546. var engine = this._engine;
  20547. if (!camera) {
  20548. if (!this.activeCamera)
  20549. throw new Error("Active camera not set");
  20550. camera = this.activeCamera;
  20551. }
  20552. var cameraViewport = camera.viewport;
  20553. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20554. // Moving coordinates to local viewport world
  20555. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20556. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20557. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20558. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20559. };
  20560. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20561. if (!BABYLON.PickingInfo) {
  20562. return null;
  20563. }
  20564. var engine = this._engine;
  20565. if (!camera) {
  20566. if (!this.activeCamera)
  20567. throw new Error("Active camera not set");
  20568. camera = this.activeCamera;
  20569. }
  20570. var cameraViewport = camera.viewport;
  20571. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20572. var identity = BABYLON.Matrix.Identity();
  20573. // Moving coordinates to local viewport world
  20574. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20575. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20576. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20577. };
  20578. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20579. if (!BABYLON.PickingInfo) {
  20580. return null;
  20581. }
  20582. var pickingInfo = null;
  20583. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20584. var mesh = this.meshes[meshIndex];
  20585. if (predicate) {
  20586. if (!predicate(mesh)) {
  20587. continue;
  20588. }
  20589. }
  20590. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20591. continue;
  20592. }
  20593. var world = mesh.getWorldMatrix();
  20594. var ray = rayFunction(world);
  20595. var result = mesh.intersects(ray, fastCheck);
  20596. if (!result || !result.hit)
  20597. continue;
  20598. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20599. continue;
  20600. pickingInfo = result;
  20601. if (fastCheck) {
  20602. break;
  20603. }
  20604. }
  20605. return pickingInfo || new BABYLON.PickingInfo();
  20606. };
  20607. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20608. if (!BABYLON.PickingInfo) {
  20609. return null;
  20610. }
  20611. var pickingInfos = new Array();
  20612. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20613. var mesh = this.meshes[meshIndex];
  20614. if (predicate) {
  20615. if (!predicate(mesh)) {
  20616. continue;
  20617. }
  20618. }
  20619. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20620. continue;
  20621. }
  20622. var world = mesh.getWorldMatrix();
  20623. var ray = rayFunction(world);
  20624. var result = mesh.intersects(ray, false);
  20625. if (!result || !result.hit)
  20626. continue;
  20627. pickingInfos.push(result);
  20628. }
  20629. return pickingInfos;
  20630. };
  20631. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20632. if (!BABYLON.PickingInfo) {
  20633. return null;
  20634. }
  20635. var pickingInfo = null;
  20636. if (!camera) {
  20637. if (!this.activeCamera) {
  20638. return null;
  20639. }
  20640. camera = this.activeCamera;
  20641. }
  20642. if (this.spriteManagers.length > 0) {
  20643. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20644. var spriteManager = this.spriteManagers[spriteIndex];
  20645. if (!spriteManager.isPickable) {
  20646. continue;
  20647. }
  20648. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20649. if (!result || !result.hit)
  20650. continue;
  20651. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20652. continue;
  20653. pickingInfo = result;
  20654. if (fastCheck) {
  20655. break;
  20656. }
  20657. }
  20658. }
  20659. return pickingInfo || new BABYLON.PickingInfo();
  20660. };
  20661. /** Launch a ray to try to pick a mesh in the scene
  20662. * @param x position on screen
  20663. * @param y position on screen
  20664. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  20665. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20666. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20667. */
  20668. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20669. var _this = this;
  20670. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20671. };
  20672. /** Launch a ray to try to pick a sprite in the scene
  20673. * @param x position on screen
  20674. * @param y position on screen
  20675. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  20676. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20677. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20678. */
  20679. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20680. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20681. if (!ray) {
  20682. return null;
  20683. }
  20684. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20685. };
  20686. /** Use the given ray to pick a mesh in the scene
  20687. * @param ray The ray to use to pick meshes
  20688. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  20689. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20690. */
  20691. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20692. var _this = this;
  20693. return this._internalPick(function (world) {
  20694. if (!_this._pickWithRayInverseMatrix) {
  20695. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20696. }
  20697. world.invertToRef(_this._pickWithRayInverseMatrix);
  20698. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20699. }, predicate, fastCheck);
  20700. };
  20701. /**
  20702. * Launch a ray to try to pick a mesh in the scene
  20703. * @param x X position on screen
  20704. * @param y Y position on screen
  20705. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  20706. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20707. */
  20708. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20709. var _this = this;
  20710. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20711. };
  20712. /**
  20713. * Launch a ray to try to pick a mesh in the scene
  20714. * @param ray Ray to use
  20715. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  20716. */
  20717. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20718. var _this = this;
  20719. return this._internalMultiPick(function (world) {
  20720. if (!_this._pickWithRayInverseMatrix) {
  20721. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20722. }
  20723. world.invertToRef(_this._pickWithRayInverseMatrix);
  20724. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20725. }, predicate);
  20726. };
  20727. Scene.prototype.setPointerOverMesh = function (mesh) {
  20728. if (this._pointerOverMesh === mesh) {
  20729. return;
  20730. }
  20731. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20732. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20733. }
  20734. this._pointerOverMesh = mesh;
  20735. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20736. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20737. }
  20738. };
  20739. Scene.prototype.getPointerOverMesh = function () {
  20740. return this._pointerOverMesh;
  20741. };
  20742. Scene.prototype.setPointerOverSprite = function (sprite) {
  20743. if (this._pointerOverSprite === sprite) {
  20744. return;
  20745. }
  20746. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20747. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20748. }
  20749. this._pointerOverSprite = sprite;
  20750. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20751. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20752. }
  20753. };
  20754. Scene.prototype.getPointerOverSprite = function () {
  20755. return this._pointerOverSprite;
  20756. };
  20757. // Physics
  20758. Scene.prototype.getPhysicsEngine = function () {
  20759. return this._physicsEngine;
  20760. };
  20761. /**
  20762. * Enables physics to the current scene
  20763. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20764. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20765. * @return {boolean} was the physics engine initialized
  20766. */
  20767. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20768. if (gravity === void 0) { gravity = null; }
  20769. if (this._physicsEngine) {
  20770. return true;
  20771. }
  20772. try {
  20773. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20774. return true;
  20775. }
  20776. catch (e) {
  20777. BABYLON.Tools.Error(e.message);
  20778. return false;
  20779. }
  20780. };
  20781. Scene.prototype.disablePhysicsEngine = function () {
  20782. if (!this._physicsEngine) {
  20783. return;
  20784. }
  20785. this._physicsEngine.dispose();
  20786. this._physicsEngine = null;
  20787. };
  20788. Scene.prototype.isPhysicsEnabled = function () {
  20789. return this._physicsEngine !== undefined;
  20790. };
  20791. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20792. var mesh = compound.parts[0].mesh;
  20793. if (mesh.physicsImpostor) {
  20794. mesh.physicsImpostor.dispose();
  20795. mesh.physicsImpostor = null;
  20796. }
  20797. };
  20798. // Misc.
  20799. Scene.prototype._rebuildGeometries = function () {
  20800. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20801. var geometry = _a[_i];
  20802. geometry._rebuild();
  20803. }
  20804. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20805. var mesh = _c[_b];
  20806. mesh._rebuild();
  20807. }
  20808. if (this.postProcessManager) {
  20809. this.postProcessManager._rebuild();
  20810. }
  20811. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20812. var layer = _e[_d];
  20813. layer._rebuild();
  20814. }
  20815. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20816. var highlightLayer = _g[_f];
  20817. highlightLayer._rebuild();
  20818. }
  20819. if (this._boundingBoxRenderer) {
  20820. this._boundingBoxRenderer._rebuild();
  20821. }
  20822. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20823. var system = _j[_h];
  20824. system.rebuild();
  20825. }
  20826. if (this._postProcessRenderPipelineManager) {
  20827. this._postProcessRenderPipelineManager._rebuild();
  20828. }
  20829. };
  20830. Scene.prototype._rebuildTextures = function () {
  20831. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20832. var texture = _a[_i];
  20833. texture._rebuild();
  20834. }
  20835. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20836. };
  20837. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20838. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20839. if (replace === void 0) { replace = false; }
  20840. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20841. // Dispose existing camera or light in replace mode.
  20842. if (replace) {
  20843. if (this.activeCamera) {
  20844. this.activeCamera.dispose();
  20845. this.activeCamera = null;
  20846. }
  20847. if (this.lights) {
  20848. for (var i = 0; i < this.lights.length; i++) {
  20849. this.lights[i].dispose();
  20850. }
  20851. }
  20852. }
  20853. // Light
  20854. if (this.lights.length === 0) {
  20855. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20856. }
  20857. // Camera
  20858. if (!this.activeCamera) {
  20859. var worldExtends = this.getWorldExtends();
  20860. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20861. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20862. var camera;
  20863. var radius = worldSize.length() * 1.5;
  20864. if (createArcRotateCamera) {
  20865. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20866. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20867. arcRotateCamera.wheelPrecision = 100 / radius;
  20868. camera = arcRotateCamera;
  20869. }
  20870. else {
  20871. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20872. freeCamera.setTarget(worldCenter);
  20873. camera = freeCamera;
  20874. }
  20875. camera.minZ = radius * 0.01;
  20876. camera.maxZ = radius * 100;
  20877. camera.speed = radius * 0.2;
  20878. this.activeCamera = camera;
  20879. var canvas = this.getEngine().getRenderingCanvas();
  20880. if (attachCameraControls && canvas) {
  20881. camera.attachControl(canvas);
  20882. }
  20883. }
  20884. };
  20885. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20886. if (pbr === void 0) { pbr = false; }
  20887. if (scale === void 0) { scale = 1000; }
  20888. if (blur === void 0) { blur = 0; }
  20889. if (environmentTexture) {
  20890. this.environmentTexture = environmentTexture;
  20891. }
  20892. if (!this.environmentTexture) {
  20893. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20894. return null;
  20895. }
  20896. // Skybox
  20897. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20898. if (pbr) {
  20899. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20900. hdrSkyboxMaterial.backFaceCulling = false;
  20901. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20902. if (hdrSkyboxMaterial.reflectionTexture) {
  20903. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20904. }
  20905. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20906. hdrSkyboxMaterial.disableLighting = true;
  20907. hdrSkyboxMaterial.twoSidedLighting = true;
  20908. hdrSkybox.infiniteDistance = true;
  20909. hdrSkybox.material = hdrSkyboxMaterial;
  20910. }
  20911. else {
  20912. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20913. skyboxMaterial.backFaceCulling = false;
  20914. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20915. if (skyboxMaterial.reflectionTexture) {
  20916. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20917. }
  20918. skyboxMaterial.disableLighting = true;
  20919. hdrSkybox.infiniteDistance = true;
  20920. hdrSkybox.material = skyboxMaterial;
  20921. }
  20922. return hdrSkybox;
  20923. };
  20924. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20925. if (webVROptions === void 0) { webVROptions = {}; }
  20926. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20927. };
  20928. // Tags
  20929. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20930. if (tagsQuery === undefined) {
  20931. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20932. return list;
  20933. }
  20934. var listByTags = [];
  20935. forEach = forEach || (function (item) { return; });
  20936. for (var i in list) {
  20937. var item = list[i];
  20938. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20939. listByTags.push(item);
  20940. forEach(item);
  20941. }
  20942. }
  20943. return listByTags;
  20944. };
  20945. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20946. return this._getByTags(this.meshes, tagsQuery, forEach);
  20947. };
  20948. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20949. return this._getByTags(this.cameras, tagsQuery, forEach);
  20950. };
  20951. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20952. return this._getByTags(this.lights, tagsQuery, forEach);
  20953. };
  20954. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20955. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20956. };
  20957. /**
  20958. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20959. * This allowed control for front to back rendering or reversly depending of the special needs.
  20960. *
  20961. * @param renderingGroupId The rendering group id corresponding to its index
  20962. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20963. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20964. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20965. */
  20966. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20967. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20968. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20969. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20970. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20971. };
  20972. /**
  20973. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20974. *
  20975. * @param renderingGroupId The rendering group id corresponding to its index
  20976. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20977. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20978. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20979. */
  20980. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20981. if (depth === void 0) { depth = true; }
  20982. if (stencil === void 0) { stencil = true; }
  20983. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20984. };
  20985. /**
  20986. * Will flag all materials as dirty to trigger new shader compilation
  20987. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20988. */
  20989. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20990. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20991. var material = _a[_i];
  20992. if (predicate && !predicate(material)) {
  20993. continue;
  20994. }
  20995. material.markAsDirty(flag);
  20996. }
  20997. };
  20998. // Statics
  20999. Scene._FOGMODE_NONE = 0;
  21000. Scene._FOGMODE_EXP = 1;
  21001. Scene._FOGMODE_EXP2 = 2;
  21002. Scene._FOGMODE_LINEAR = 3;
  21003. Scene._uniqueIdCounter = 0;
  21004. Scene.MinDeltaTime = 1.0;
  21005. Scene.MaxDeltaTime = 1000.0;
  21006. /** The distance in pixel that you have to move to prevent some events */
  21007. Scene.DragMovementThreshold = 10; // in pixels
  21008. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21009. Scene.LongPressDelay = 500; // in milliseconds
  21010. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21011. Scene.DoubleClickDelay = 300; // in milliseconds
  21012. /** If you need to check double click without raising a single click at first click, enable this flag */
  21013. Scene.ExclusiveDoubleClickMode = false;
  21014. return Scene;
  21015. }());
  21016. BABYLON.Scene = Scene;
  21017. })(BABYLON || (BABYLON = {}));
  21018. //# sourceMappingURL=babylon.scene.js.map
  21019. var BABYLON;
  21020. (function (BABYLON) {
  21021. var Buffer = /** @class */ (function () {
  21022. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21023. if (instanced === void 0) { instanced = false; }
  21024. if (engine instanceof BABYLON.Mesh) {
  21025. this._engine = engine.getScene().getEngine();
  21026. }
  21027. else {
  21028. this._engine = engine;
  21029. }
  21030. this._updatable = updatable;
  21031. this._data = data;
  21032. this._strideSize = stride;
  21033. if (!postponeInternalCreation) {
  21034. this.create();
  21035. }
  21036. this._instanced = instanced;
  21037. this._instanceDivisor = instanced ? 1 : 0;
  21038. }
  21039. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21040. // a lot of these parameters are ignored as they are overriden by the buffer
  21041. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21042. };
  21043. // Properties
  21044. Buffer.prototype.isUpdatable = function () {
  21045. return this._updatable;
  21046. };
  21047. Buffer.prototype.getData = function () {
  21048. return this._data;
  21049. };
  21050. Buffer.prototype.getBuffer = function () {
  21051. return this._buffer;
  21052. };
  21053. Buffer.prototype.getStrideSize = function () {
  21054. return this._strideSize;
  21055. };
  21056. Buffer.prototype.getIsInstanced = function () {
  21057. return this._instanced;
  21058. };
  21059. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21060. get: function () {
  21061. return this._instanceDivisor;
  21062. },
  21063. set: function (value) {
  21064. this._instanceDivisor = value;
  21065. if (value == 0) {
  21066. this._instanced = false;
  21067. }
  21068. else {
  21069. this._instanced = true;
  21070. }
  21071. },
  21072. enumerable: true,
  21073. configurable: true
  21074. });
  21075. // Methods
  21076. Buffer.prototype.create = function (data) {
  21077. if (data === void 0) { data = null; }
  21078. if (!data && this._buffer) {
  21079. return; // nothing to do
  21080. }
  21081. data = data || this._data;
  21082. if (!data) {
  21083. return;
  21084. }
  21085. if (!this._buffer) {
  21086. if (this._updatable) {
  21087. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21088. this._data = data;
  21089. }
  21090. else {
  21091. this._buffer = this._engine.createVertexBuffer(data);
  21092. }
  21093. }
  21094. else if (this._updatable) {
  21095. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21096. this._data = data;
  21097. }
  21098. };
  21099. Buffer.prototype._rebuild = function () {
  21100. this._buffer = null;
  21101. this.create(this._data);
  21102. };
  21103. Buffer.prototype.update = function (data) {
  21104. this.create(data);
  21105. };
  21106. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21107. if (!this._buffer) {
  21108. return;
  21109. }
  21110. if (this._updatable) {
  21111. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21112. this._data = null;
  21113. }
  21114. };
  21115. Buffer.prototype.dispose = function () {
  21116. if (!this._buffer) {
  21117. return;
  21118. }
  21119. if (this._engine._releaseBuffer(this._buffer)) {
  21120. this._buffer = null;
  21121. }
  21122. };
  21123. return Buffer;
  21124. }());
  21125. BABYLON.Buffer = Buffer;
  21126. })(BABYLON || (BABYLON = {}));
  21127. //# sourceMappingURL=babylon.buffer.js.map
  21128. var BABYLON;
  21129. (function (BABYLON) {
  21130. var VertexBuffer = /** @class */ (function () {
  21131. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21132. if (!stride) {
  21133. // Deduce stride from kind
  21134. switch (kind) {
  21135. case VertexBuffer.PositionKind:
  21136. stride = 3;
  21137. break;
  21138. case VertexBuffer.NormalKind:
  21139. stride = 3;
  21140. break;
  21141. case VertexBuffer.UVKind:
  21142. case VertexBuffer.UV2Kind:
  21143. case VertexBuffer.UV3Kind:
  21144. case VertexBuffer.UV4Kind:
  21145. case VertexBuffer.UV5Kind:
  21146. case VertexBuffer.UV6Kind:
  21147. stride = 2;
  21148. break;
  21149. case VertexBuffer.TangentKind:
  21150. case VertexBuffer.ColorKind:
  21151. stride = 4;
  21152. break;
  21153. case VertexBuffer.MatricesIndicesKind:
  21154. case VertexBuffer.MatricesIndicesExtraKind:
  21155. stride = 4;
  21156. break;
  21157. case VertexBuffer.MatricesWeightsKind:
  21158. case VertexBuffer.MatricesWeightsExtraKind:
  21159. default:
  21160. stride = 4;
  21161. break;
  21162. }
  21163. }
  21164. if (data instanceof BABYLON.Buffer) {
  21165. if (!stride) {
  21166. stride = data.getStrideSize();
  21167. }
  21168. this._buffer = data;
  21169. this._ownsBuffer = false;
  21170. }
  21171. else {
  21172. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21173. this._ownsBuffer = true;
  21174. }
  21175. this._stride = stride;
  21176. this._offset = offset ? offset : 0;
  21177. this._size = size ? size : stride;
  21178. this._kind = kind;
  21179. }
  21180. VertexBuffer.prototype._rebuild = function () {
  21181. if (!this._buffer) {
  21182. return;
  21183. }
  21184. this._buffer._rebuild();
  21185. };
  21186. /**
  21187. * Returns the kind of the VertexBuffer (string).
  21188. */
  21189. VertexBuffer.prototype.getKind = function () {
  21190. return this._kind;
  21191. };
  21192. // Properties
  21193. /**
  21194. * Boolean : is the VertexBuffer updatable ?
  21195. */
  21196. VertexBuffer.prototype.isUpdatable = function () {
  21197. return this._buffer.isUpdatable();
  21198. };
  21199. /**
  21200. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21201. */
  21202. VertexBuffer.prototype.getData = function () {
  21203. return this._buffer.getData();
  21204. };
  21205. /**
  21206. * Returns the WebGLBuffer associated to the VertexBuffer.
  21207. */
  21208. VertexBuffer.prototype.getBuffer = function () {
  21209. return this._buffer.getBuffer();
  21210. };
  21211. /**
  21212. * Returns the stride of the VertexBuffer (integer).
  21213. */
  21214. VertexBuffer.prototype.getStrideSize = function () {
  21215. return this._stride;
  21216. };
  21217. /**
  21218. * Returns the offset (integer).
  21219. */
  21220. VertexBuffer.prototype.getOffset = function () {
  21221. return this._offset;
  21222. };
  21223. /**
  21224. * Returns the VertexBuffer total size (integer).
  21225. */
  21226. VertexBuffer.prototype.getSize = function () {
  21227. return this._size;
  21228. };
  21229. /**
  21230. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21231. */
  21232. VertexBuffer.prototype.getIsInstanced = function () {
  21233. return this._buffer.getIsInstanced();
  21234. };
  21235. /**
  21236. * Returns the instancing divisor, zero for non-instanced (integer).
  21237. */
  21238. VertexBuffer.prototype.getInstanceDivisor = function () {
  21239. return this._buffer.instanceDivisor;
  21240. };
  21241. // Methods
  21242. /**
  21243. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21244. * Returns the created WebGLBuffer.
  21245. */
  21246. VertexBuffer.prototype.create = function (data) {
  21247. return this._buffer.create(data);
  21248. };
  21249. /**
  21250. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21251. * Returns the updated WebGLBuffer.
  21252. */
  21253. VertexBuffer.prototype.update = function (data) {
  21254. return this._buffer.update(data);
  21255. };
  21256. /**
  21257. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21258. * Returns the directly updated WebGLBuffer.
  21259. */
  21260. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21261. return this._buffer.updateDirectly(data, offset);
  21262. };
  21263. /**
  21264. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21265. */
  21266. VertexBuffer.prototype.dispose = function () {
  21267. if (this._ownsBuffer) {
  21268. this._buffer.dispose();
  21269. }
  21270. };
  21271. Object.defineProperty(VertexBuffer, "PositionKind", {
  21272. get: function () {
  21273. return VertexBuffer._PositionKind;
  21274. },
  21275. enumerable: true,
  21276. configurable: true
  21277. });
  21278. Object.defineProperty(VertexBuffer, "NormalKind", {
  21279. get: function () {
  21280. return VertexBuffer._NormalKind;
  21281. },
  21282. enumerable: true,
  21283. configurable: true
  21284. });
  21285. Object.defineProperty(VertexBuffer, "TangentKind", {
  21286. get: function () {
  21287. return VertexBuffer._TangentKind;
  21288. },
  21289. enumerable: true,
  21290. configurable: true
  21291. });
  21292. Object.defineProperty(VertexBuffer, "UVKind", {
  21293. get: function () {
  21294. return VertexBuffer._UVKind;
  21295. },
  21296. enumerable: true,
  21297. configurable: true
  21298. });
  21299. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21300. get: function () {
  21301. return VertexBuffer._UV2Kind;
  21302. },
  21303. enumerable: true,
  21304. configurable: true
  21305. });
  21306. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21307. get: function () {
  21308. return VertexBuffer._UV3Kind;
  21309. },
  21310. enumerable: true,
  21311. configurable: true
  21312. });
  21313. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21314. get: function () {
  21315. return VertexBuffer._UV4Kind;
  21316. },
  21317. enumerable: true,
  21318. configurable: true
  21319. });
  21320. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21321. get: function () {
  21322. return VertexBuffer._UV5Kind;
  21323. },
  21324. enumerable: true,
  21325. configurable: true
  21326. });
  21327. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21328. get: function () {
  21329. return VertexBuffer._UV6Kind;
  21330. },
  21331. enumerable: true,
  21332. configurable: true
  21333. });
  21334. Object.defineProperty(VertexBuffer, "ColorKind", {
  21335. get: function () {
  21336. return VertexBuffer._ColorKind;
  21337. },
  21338. enumerable: true,
  21339. configurable: true
  21340. });
  21341. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21342. get: function () {
  21343. return VertexBuffer._MatricesIndicesKind;
  21344. },
  21345. enumerable: true,
  21346. configurable: true
  21347. });
  21348. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21349. get: function () {
  21350. return VertexBuffer._MatricesWeightsKind;
  21351. },
  21352. enumerable: true,
  21353. configurable: true
  21354. });
  21355. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21356. get: function () {
  21357. return VertexBuffer._MatricesIndicesExtraKind;
  21358. },
  21359. enumerable: true,
  21360. configurable: true
  21361. });
  21362. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21363. get: function () {
  21364. return VertexBuffer._MatricesWeightsExtraKind;
  21365. },
  21366. enumerable: true,
  21367. configurable: true
  21368. });
  21369. // Enums
  21370. VertexBuffer._PositionKind = "position";
  21371. VertexBuffer._NormalKind = "normal";
  21372. VertexBuffer._TangentKind = "tangent";
  21373. VertexBuffer._UVKind = "uv";
  21374. VertexBuffer._UV2Kind = "uv2";
  21375. VertexBuffer._UV3Kind = "uv3";
  21376. VertexBuffer._UV4Kind = "uv4";
  21377. VertexBuffer._UV5Kind = "uv5";
  21378. VertexBuffer._UV6Kind = "uv6";
  21379. VertexBuffer._ColorKind = "color";
  21380. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21381. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21382. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21383. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21384. return VertexBuffer;
  21385. }());
  21386. BABYLON.VertexBuffer = VertexBuffer;
  21387. })(BABYLON || (BABYLON = {}));
  21388. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21389. var BABYLON;
  21390. (function (BABYLON) {
  21391. var InternalTexture = /** @class */ (function () {
  21392. function InternalTexture(engine, dataSource) {
  21393. this.onLoadedObservable = new BABYLON.Observable();
  21394. // Private
  21395. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21396. this._references = 1;
  21397. this._engine = engine;
  21398. this._dataSource = dataSource;
  21399. this._webGLTexture = engine._createTexture();
  21400. }
  21401. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21402. get: function () {
  21403. return this._dataSource;
  21404. },
  21405. enumerable: true,
  21406. configurable: true
  21407. });
  21408. InternalTexture.prototype.incrementReferences = function () {
  21409. this._references++;
  21410. };
  21411. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21412. if (depth === void 0) { depth = 1; }
  21413. this.width = width;
  21414. this.height = height;
  21415. this.depth = depth;
  21416. this.baseWidth = width;
  21417. this.baseHeight = height;
  21418. this.baseDepth = depth;
  21419. this._size = width * height * depth;
  21420. };
  21421. InternalTexture.prototype._rebuild = function () {
  21422. var _this = this;
  21423. var proxy;
  21424. this.isReady = false;
  21425. this._cachedCoordinatesMode = null;
  21426. this._cachedWrapU = null;
  21427. this._cachedWrapV = null;
  21428. this._cachedAnisotropicFilteringLevel = null;
  21429. switch (this._dataSource) {
  21430. case InternalTexture.DATASOURCE_TEMP:
  21431. return;
  21432. case InternalTexture.DATASOURCE_URL:
  21433. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21434. _this.isReady = true;
  21435. }, null, this._buffer, undefined, this.format);
  21436. proxy._swapAndDie(this);
  21437. return;
  21438. case InternalTexture.DATASOURCE_RAW:
  21439. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21440. proxy._swapAndDie(this);
  21441. this.isReady = true;
  21442. return;
  21443. case InternalTexture.DATASOURCE_RAW3D:
  21444. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21445. proxy._swapAndDie(this);
  21446. this.isReady = true;
  21447. return;
  21448. case InternalTexture.DATASOURCE_DYNAMIC:
  21449. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21450. proxy._swapAndDie(this);
  21451. // The engine will make sure to update content so no need to flag it as isReady = true
  21452. return;
  21453. case InternalTexture.DATASOURCE_RENDERTARGET:
  21454. var options = new BABYLON.RenderTargetCreationOptions();
  21455. options.generateDepthBuffer = this._generateDepthBuffer;
  21456. options.generateMipMaps = this.generateMipMaps;
  21457. options.generateStencilBuffer = this._generateStencilBuffer;
  21458. options.samplingMode = this.samplingMode;
  21459. options.type = this.type;
  21460. if (this.isCube) {
  21461. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21462. }
  21463. else {
  21464. var size = {
  21465. width: this.width,
  21466. height: this.height
  21467. };
  21468. proxy = this._engine.createRenderTargetTexture(size, options);
  21469. }
  21470. proxy._swapAndDie(this);
  21471. this.isReady = true;
  21472. return;
  21473. case InternalTexture.DATASOURCE_CUBE:
  21474. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21475. _this.isReady = true;
  21476. }, null, this.format, this._extension);
  21477. proxy._swapAndDie(this);
  21478. return;
  21479. case InternalTexture.DATASOURCE_CUBERAW:
  21480. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21481. proxy._swapAndDie(this);
  21482. this.isReady = true;
  21483. return;
  21484. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21485. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21486. if (proxy) {
  21487. proxy._swapAndDie(_this);
  21488. }
  21489. _this.isReady = true;
  21490. }, null, this.format, this._extension);
  21491. return;
  21492. }
  21493. };
  21494. InternalTexture.prototype._swapAndDie = function (target) {
  21495. target._webGLTexture = this._webGLTexture;
  21496. if (this._framebuffer) {
  21497. target._framebuffer = this._framebuffer;
  21498. }
  21499. if (this._depthStencilBuffer) {
  21500. target._depthStencilBuffer = this._depthStencilBuffer;
  21501. }
  21502. if (this._lodTextureHigh) {
  21503. if (target._lodTextureHigh) {
  21504. target._lodTextureHigh.dispose();
  21505. }
  21506. target._lodTextureHigh = this._lodTextureHigh;
  21507. }
  21508. if (this._lodTextureMid) {
  21509. if (target._lodTextureMid) {
  21510. target._lodTextureMid.dispose();
  21511. }
  21512. target._lodTextureMid = this._lodTextureMid;
  21513. }
  21514. if (this._lodTextureLow) {
  21515. if (target._lodTextureLow) {
  21516. target._lodTextureLow.dispose();
  21517. }
  21518. target._lodTextureLow = this._lodTextureLow;
  21519. }
  21520. var cache = this._engine.getLoadedTexturesCache();
  21521. var index = cache.indexOf(this);
  21522. if (index !== -1) {
  21523. cache.splice(index, 1);
  21524. }
  21525. };
  21526. InternalTexture.prototype.dispose = function () {
  21527. if (!this._webGLTexture) {
  21528. return;
  21529. }
  21530. this._references--;
  21531. if (this._references === 0) {
  21532. this._engine._releaseTexture(this);
  21533. this._webGLTexture = null;
  21534. }
  21535. };
  21536. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21537. InternalTexture.DATASOURCE_URL = 1;
  21538. InternalTexture.DATASOURCE_TEMP = 2;
  21539. InternalTexture.DATASOURCE_RAW = 3;
  21540. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21541. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21542. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21543. InternalTexture.DATASOURCE_CUBE = 7;
  21544. InternalTexture.DATASOURCE_CUBERAW = 8;
  21545. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21546. InternalTexture.DATASOURCE_RAW3D = 10;
  21547. return InternalTexture;
  21548. }());
  21549. BABYLON.InternalTexture = InternalTexture;
  21550. })(BABYLON || (BABYLON = {}));
  21551. //# sourceMappingURL=babylon.internalTexture.js.map
  21552. var BABYLON;
  21553. (function (BABYLON) {
  21554. var BaseTexture = /** @class */ (function () {
  21555. function BaseTexture(scene) {
  21556. this._hasAlpha = false;
  21557. this.getAlphaFromRGB = false;
  21558. this.level = 1;
  21559. this.coordinatesIndex = 0;
  21560. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21561. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21562. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21563. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21564. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21565. this.isCube = false;
  21566. this.is3D = false;
  21567. this.gammaSpace = true;
  21568. this.invertZ = false;
  21569. this.lodLevelInAlpha = false;
  21570. this.lodGenerationOffset = 0.0;
  21571. this.lodGenerationScale = 0.8;
  21572. this.isRenderTarget = false;
  21573. this.animations = new Array();
  21574. /**
  21575. * An event triggered when the texture is disposed.
  21576. * @type {BABYLON.Observable}
  21577. */
  21578. this.onDisposeObservable = new BABYLON.Observable();
  21579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21580. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21581. if (this._scene) {
  21582. this._scene.textures.push(this);
  21583. }
  21584. this._uid = null;
  21585. }
  21586. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21587. get: function () {
  21588. return this._hasAlpha;
  21589. },
  21590. set: function (value) {
  21591. if (this._hasAlpha === value) {
  21592. return;
  21593. }
  21594. this._hasAlpha = value;
  21595. if (this._scene) {
  21596. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21597. }
  21598. },
  21599. enumerable: true,
  21600. configurable: true
  21601. });
  21602. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21603. get: function () {
  21604. return this._coordinatesMode;
  21605. },
  21606. set: function (value) {
  21607. if (this._coordinatesMode === value) {
  21608. return;
  21609. }
  21610. this._coordinatesMode = value;
  21611. if (this._scene) {
  21612. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21613. }
  21614. },
  21615. enumerable: true,
  21616. configurable: true
  21617. });
  21618. Object.defineProperty(BaseTexture.prototype, "uid", {
  21619. get: function () {
  21620. if (!this._uid) {
  21621. this._uid = BABYLON.Tools.RandomId();
  21622. }
  21623. return this._uid;
  21624. },
  21625. enumerable: true,
  21626. configurable: true
  21627. });
  21628. BaseTexture.prototype.toString = function () {
  21629. return this.name;
  21630. };
  21631. BaseTexture.prototype.getClassName = function () {
  21632. return "BaseTexture";
  21633. };
  21634. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21635. set: function (callback) {
  21636. if (this._onDisposeObserver) {
  21637. this.onDisposeObservable.remove(this._onDisposeObserver);
  21638. }
  21639. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21640. },
  21641. enumerable: true,
  21642. configurable: true
  21643. });
  21644. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21645. get: function () {
  21646. return true;
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. BaseTexture.prototype.getScene = function () {
  21652. return this._scene;
  21653. };
  21654. BaseTexture.prototype.getTextureMatrix = function () {
  21655. return BABYLON.Matrix.IdentityReadOnly;
  21656. };
  21657. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21658. return BABYLON.Matrix.IdentityReadOnly;
  21659. };
  21660. BaseTexture.prototype.getInternalTexture = function () {
  21661. return this._texture;
  21662. };
  21663. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21664. return !this.isBlocking || this.isReady();
  21665. };
  21666. BaseTexture.prototype.isReady = function () {
  21667. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21668. this.delayLoad();
  21669. return false;
  21670. }
  21671. if (this._texture) {
  21672. return this._texture.isReady;
  21673. }
  21674. return false;
  21675. };
  21676. BaseTexture.prototype.getSize = function () {
  21677. if (this._texture && this._texture.width) {
  21678. return new BABYLON.Size(this._texture.width, this._texture.height);
  21679. }
  21680. if (this._texture && this._texture._size) {
  21681. return new BABYLON.Size(this._texture._size, this._texture._size);
  21682. }
  21683. return BABYLON.Size.Zero();
  21684. };
  21685. BaseTexture.prototype.getBaseSize = function () {
  21686. if (!this.isReady() || !this._texture)
  21687. return BABYLON.Size.Zero();
  21688. if (this._texture._size) {
  21689. return new BABYLON.Size(this._texture._size, this._texture._size);
  21690. }
  21691. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21692. };
  21693. BaseTexture.prototype.scale = function (ratio) {
  21694. };
  21695. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21696. get: function () {
  21697. return false;
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21703. if (!this._scene) {
  21704. return null;
  21705. }
  21706. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21707. for (var index = 0; index < texturesCache.length; index++) {
  21708. var texturesCacheEntry = texturesCache[index];
  21709. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21710. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21711. texturesCacheEntry.incrementReferences();
  21712. return texturesCacheEntry;
  21713. }
  21714. }
  21715. }
  21716. return null;
  21717. };
  21718. BaseTexture.prototype._rebuild = function () {
  21719. };
  21720. BaseTexture.prototype.delayLoad = function () {
  21721. };
  21722. BaseTexture.prototype.clone = function () {
  21723. return null;
  21724. };
  21725. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21726. get: function () {
  21727. if (!this._texture) {
  21728. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21729. }
  21730. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21731. },
  21732. enumerable: true,
  21733. configurable: true
  21734. });
  21735. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21736. get: function () {
  21737. if (!this._texture) {
  21738. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21739. }
  21740. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. BaseTexture.prototype.readPixels = function (faceIndex) {
  21746. if (faceIndex === void 0) { faceIndex = 0; }
  21747. if (!this._texture) {
  21748. return null;
  21749. }
  21750. var size = this.getSize();
  21751. var scene = this.getScene();
  21752. if (!scene) {
  21753. return null;
  21754. }
  21755. var engine = scene.getEngine();
  21756. if (this._texture.isCube) {
  21757. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21758. }
  21759. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21760. };
  21761. BaseTexture.prototype.releaseInternalTexture = function () {
  21762. if (this._texture) {
  21763. this._texture.dispose();
  21764. this._texture = null;
  21765. }
  21766. };
  21767. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21768. get: function () {
  21769. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21770. return null;
  21771. }
  21772. if (!this._texture._sphericalPolynomial) {
  21773. this._texture._sphericalPolynomial =
  21774. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21775. }
  21776. return this._texture._sphericalPolynomial;
  21777. },
  21778. set: function (value) {
  21779. if (this._texture) {
  21780. this._texture._sphericalPolynomial = value;
  21781. }
  21782. },
  21783. enumerable: true,
  21784. configurable: true
  21785. });
  21786. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21787. get: function () {
  21788. if (this._texture) {
  21789. return this._texture._lodTextureHigh;
  21790. }
  21791. return null;
  21792. },
  21793. enumerable: true,
  21794. configurable: true
  21795. });
  21796. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21797. get: function () {
  21798. if (this._texture) {
  21799. return this._texture._lodTextureMid;
  21800. }
  21801. return null;
  21802. },
  21803. enumerable: true,
  21804. configurable: true
  21805. });
  21806. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21807. get: function () {
  21808. if (this._texture) {
  21809. return this._texture._lodTextureLow;
  21810. }
  21811. return null;
  21812. },
  21813. enumerable: true,
  21814. configurable: true
  21815. });
  21816. BaseTexture.prototype.dispose = function () {
  21817. if (!this._scene) {
  21818. return;
  21819. }
  21820. // Animations
  21821. this._scene.stopAnimation(this);
  21822. // Remove from scene
  21823. this._scene._removePendingData(this);
  21824. var index = this._scene.textures.indexOf(this);
  21825. if (index >= 0) {
  21826. this._scene.textures.splice(index, 1);
  21827. }
  21828. if (this._texture === undefined) {
  21829. return;
  21830. }
  21831. // Release
  21832. this.releaseInternalTexture();
  21833. // Callback
  21834. this.onDisposeObservable.notifyObservers(this);
  21835. this.onDisposeObservable.clear();
  21836. };
  21837. BaseTexture.prototype.serialize = function () {
  21838. if (!this.name) {
  21839. return null;
  21840. }
  21841. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21842. // Animations
  21843. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21844. return serializationObject;
  21845. };
  21846. BaseTexture.WhenAllReady = function (textures, callback) {
  21847. var numRemaining = textures.length;
  21848. if (numRemaining === 0) {
  21849. callback();
  21850. return;
  21851. }
  21852. var _loop_1 = function () {
  21853. texture = textures[i];
  21854. if (texture.isReady()) {
  21855. if (--numRemaining === 0) {
  21856. callback();
  21857. }
  21858. }
  21859. else {
  21860. onLoadObservable = texture.onLoadObservable;
  21861. var onLoadCallback_1 = function () {
  21862. onLoadObservable.removeCallback(onLoadCallback_1);
  21863. if (--numRemaining === 0) {
  21864. callback();
  21865. }
  21866. };
  21867. onLoadObservable.add(onLoadCallback_1);
  21868. }
  21869. };
  21870. var texture, onLoadObservable;
  21871. for (var i = 0; i < textures.length; i++) {
  21872. _loop_1();
  21873. }
  21874. };
  21875. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21876. __decorate([
  21877. BABYLON.serialize()
  21878. ], BaseTexture.prototype, "name", void 0);
  21879. __decorate([
  21880. BABYLON.serialize("hasAlpha")
  21881. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21882. __decorate([
  21883. BABYLON.serialize()
  21884. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21885. __decorate([
  21886. BABYLON.serialize()
  21887. ], BaseTexture.prototype, "level", void 0);
  21888. __decorate([
  21889. BABYLON.serialize()
  21890. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21891. __decorate([
  21892. BABYLON.serialize("coordinatesMode")
  21893. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21894. __decorate([
  21895. BABYLON.serialize()
  21896. ], BaseTexture.prototype, "wrapU", void 0);
  21897. __decorate([
  21898. BABYLON.serialize()
  21899. ], BaseTexture.prototype, "wrapV", void 0);
  21900. __decorate([
  21901. BABYLON.serialize()
  21902. ], BaseTexture.prototype, "wrapR", void 0);
  21903. __decorate([
  21904. BABYLON.serialize()
  21905. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21906. __decorate([
  21907. BABYLON.serialize()
  21908. ], BaseTexture.prototype, "isCube", void 0);
  21909. __decorate([
  21910. BABYLON.serialize()
  21911. ], BaseTexture.prototype, "is3D", void 0);
  21912. __decorate([
  21913. BABYLON.serialize()
  21914. ], BaseTexture.prototype, "gammaSpace", void 0);
  21915. __decorate([
  21916. BABYLON.serialize()
  21917. ], BaseTexture.prototype, "invertZ", void 0);
  21918. __decorate([
  21919. BABYLON.serialize()
  21920. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21921. __decorate([
  21922. BABYLON.serialize()
  21923. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21924. __decorate([
  21925. BABYLON.serialize()
  21926. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21927. __decorate([
  21928. BABYLON.serialize()
  21929. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21930. return BaseTexture;
  21931. }());
  21932. BABYLON.BaseTexture = BaseTexture;
  21933. })(BABYLON || (BABYLON = {}));
  21934. //# sourceMappingURL=babylon.baseTexture.js.map
  21935. var BABYLON;
  21936. (function (BABYLON) {
  21937. var Texture = /** @class */ (function (_super) {
  21938. __extends(Texture, _super);
  21939. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21940. if (noMipmap === void 0) { noMipmap = false; }
  21941. if (invertY === void 0) { invertY = true; }
  21942. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21943. if (onLoad === void 0) { onLoad = null; }
  21944. if (onError === void 0) { onError = null; }
  21945. if (buffer === void 0) { buffer = null; }
  21946. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21947. var _this = _super.call(this, scene) || this;
  21948. _this.uOffset = 0;
  21949. _this.vOffset = 0;
  21950. _this.uScale = 1.0;
  21951. _this.vScale = 1.0;
  21952. _this.uAng = 0;
  21953. _this.vAng = 0;
  21954. _this.wAng = 0;
  21955. _this._isBlocking = true;
  21956. _this.name = url || "";
  21957. _this.url = url;
  21958. _this._noMipmap = noMipmap;
  21959. _this._invertY = invertY;
  21960. _this._samplingMode = samplingMode;
  21961. _this._buffer = buffer;
  21962. _this._deleteBuffer = deleteBuffer;
  21963. if (format) {
  21964. _this._format = format;
  21965. }
  21966. scene = _this.getScene();
  21967. if (!scene) {
  21968. return _this;
  21969. }
  21970. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21971. var load = function () {
  21972. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21973. _this.onLoadObservable.notifyObservers(_this);
  21974. }
  21975. if (onLoad) {
  21976. onLoad();
  21977. }
  21978. if (!_this.isBlocking && scene) {
  21979. scene.resetCachedMaterial();
  21980. }
  21981. };
  21982. if (!_this.url) {
  21983. _this._delayedOnLoad = load;
  21984. _this._delayedOnError = onError;
  21985. return _this;
  21986. }
  21987. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21988. if (!_this._texture) {
  21989. if (!scene.useDelayedTextureLoading) {
  21990. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21991. if (deleteBuffer) {
  21992. delete _this._buffer;
  21993. }
  21994. }
  21995. else {
  21996. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21997. _this._delayedOnLoad = load;
  21998. _this._delayedOnError = onError;
  21999. }
  22000. }
  22001. else {
  22002. if (_this._texture.isReady) {
  22003. BABYLON.Tools.SetImmediate(function () { return load(); });
  22004. }
  22005. else {
  22006. _this._texture.onLoadedObservable.add(load);
  22007. }
  22008. }
  22009. return _this;
  22010. }
  22011. Object.defineProperty(Texture.prototype, "noMipmap", {
  22012. get: function () {
  22013. return this._noMipmap;
  22014. },
  22015. enumerable: true,
  22016. configurable: true
  22017. });
  22018. Object.defineProperty(Texture.prototype, "isBlocking", {
  22019. get: function () {
  22020. return this._isBlocking;
  22021. },
  22022. set: function (value) {
  22023. this._isBlocking = value;
  22024. },
  22025. enumerable: true,
  22026. configurable: true
  22027. });
  22028. Object.defineProperty(Texture.prototype, "samplingMode", {
  22029. get: function () {
  22030. return this._samplingMode;
  22031. },
  22032. enumerable: true,
  22033. configurable: true
  22034. });
  22035. Texture.prototype.updateURL = function (url) {
  22036. this.url = url;
  22037. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22038. this.delayLoad();
  22039. };
  22040. Texture.prototype.delayLoad = function () {
  22041. var _this = this;
  22042. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22043. return;
  22044. }
  22045. var scene = this.getScene();
  22046. if (!scene) {
  22047. return;
  22048. }
  22049. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22050. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22051. if (!this._texture) {
  22052. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22053. if (this._deleteBuffer) {
  22054. delete this._buffer;
  22055. }
  22056. }
  22057. else {
  22058. if (this._texture.isReady) {
  22059. BABYLON.Tools.SetImmediate(function () {
  22060. if (!_this._delayedOnLoad) {
  22061. return;
  22062. }
  22063. _this._delayedOnLoad();
  22064. });
  22065. }
  22066. else {
  22067. if (this._delayedOnLoad) {
  22068. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22069. }
  22070. }
  22071. }
  22072. };
  22073. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22074. if (!this._texture) {
  22075. return;
  22076. }
  22077. var scene = this.getScene();
  22078. if (!scene) {
  22079. return;
  22080. }
  22081. this._samplingMode = samplingMode;
  22082. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22083. };
  22084. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22085. x *= this.uScale;
  22086. y *= this.vScale;
  22087. x -= 0.5 * this.uScale;
  22088. y -= 0.5 * this.vScale;
  22089. z -= 0.5;
  22090. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22091. t.x += 0.5 * this.uScale + this.uOffset;
  22092. t.y += 0.5 * this.vScale + this.vOffset;
  22093. t.z += 0.5;
  22094. };
  22095. Texture.prototype.getTextureMatrix = function () {
  22096. var _this = this;
  22097. if (this.uOffset === this._cachedUOffset &&
  22098. this.vOffset === this._cachedVOffset &&
  22099. this.uScale === this._cachedUScale &&
  22100. this.vScale === this._cachedVScale &&
  22101. this.uAng === this._cachedUAng &&
  22102. this.vAng === this._cachedVAng &&
  22103. this.wAng === this._cachedWAng) {
  22104. return this._cachedTextureMatrix;
  22105. }
  22106. this._cachedUOffset = this.uOffset;
  22107. this._cachedVOffset = this.vOffset;
  22108. this._cachedUScale = this.uScale;
  22109. this._cachedVScale = this.vScale;
  22110. this._cachedUAng = this.uAng;
  22111. this._cachedVAng = this.vAng;
  22112. this._cachedWAng = this.wAng;
  22113. if (!this._cachedTextureMatrix) {
  22114. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22115. this._rowGenerationMatrix = new BABYLON.Matrix();
  22116. this._t0 = BABYLON.Vector3.Zero();
  22117. this._t1 = BABYLON.Vector3.Zero();
  22118. this._t2 = BABYLON.Vector3.Zero();
  22119. }
  22120. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22121. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22122. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22123. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22124. this._t1.subtractInPlace(this._t0);
  22125. this._t2.subtractInPlace(this._t0);
  22126. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22127. this._cachedTextureMatrix.m[0] = this._t1.x;
  22128. this._cachedTextureMatrix.m[1] = this._t1.y;
  22129. this._cachedTextureMatrix.m[2] = this._t1.z;
  22130. this._cachedTextureMatrix.m[4] = this._t2.x;
  22131. this._cachedTextureMatrix.m[5] = this._t2.y;
  22132. this._cachedTextureMatrix.m[6] = this._t2.z;
  22133. this._cachedTextureMatrix.m[8] = this._t0.x;
  22134. this._cachedTextureMatrix.m[9] = this._t0.y;
  22135. this._cachedTextureMatrix.m[10] = this._t0.z;
  22136. var scene = this.getScene();
  22137. if (!scene) {
  22138. return this._cachedTextureMatrix;
  22139. }
  22140. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22141. return mat.hasTexture(_this);
  22142. });
  22143. return this._cachedTextureMatrix;
  22144. };
  22145. Texture.prototype.getReflectionTextureMatrix = function () {
  22146. var _this = this;
  22147. var scene = this.getScene();
  22148. if (!scene) {
  22149. return this._cachedTextureMatrix;
  22150. }
  22151. if (this.uOffset === this._cachedUOffset &&
  22152. this.vOffset === this._cachedVOffset &&
  22153. this.uScale === this._cachedUScale &&
  22154. this.vScale === this._cachedVScale &&
  22155. this.coordinatesMode === this._cachedCoordinatesMode) {
  22156. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22157. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22158. return this._cachedTextureMatrix;
  22159. }
  22160. }
  22161. else {
  22162. return this._cachedTextureMatrix;
  22163. }
  22164. }
  22165. if (!this._cachedTextureMatrix) {
  22166. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22167. }
  22168. if (!this._projectionModeMatrix) {
  22169. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22170. }
  22171. this._cachedUOffset = this.uOffset;
  22172. this._cachedVOffset = this.vOffset;
  22173. this._cachedUScale = this.uScale;
  22174. this._cachedVScale = this.vScale;
  22175. this._cachedCoordinatesMode = this.coordinatesMode;
  22176. switch (this.coordinatesMode) {
  22177. case Texture.PLANAR_MODE:
  22178. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22179. this._cachedTextureMatrix[0] = this.uScale;
  22180. this._cachedTextureMatrix[5] = this.vScale;
  22181. this._cachedTextureMatrix[12] = this.uOffset;
  22182. this._cachedTextureMatrix[13] = this.vOffset;
  22183. break;
  22184. case Texture.PROJECTION_MODE:
  22185. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22186. this._projectionModeMatrix.m[0] = 0.5;
  22187. this._projectionModeMatrix.m[5] = -0.5;
  22188. this._projectionModeMatrix.m[10] = 0.0;
  22189. this._projectionModeMatrix.m[12] = 0.5;
  22190. this._projectionModeMatrix.m[13] = 0.5;
  22191. this._projectionModeMatrix.m[14] = 1.0;
  22192. this._projectionModeMatrix.m[15] = 1.0;
  22193. var projectionMatrix = scene.getProjectionMatrix();
  22194. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22195. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22196. break;
  22197. default:
  22198. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22199. break;
  22200. }
  22201. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22202. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22203. });
  22204. return this._cachedTextureMatrix;
  22205. };
  22206. Texture.prototype.clone = function () {
  22207. var _this = this;
  22208. return BABYLON.SerializationHelper.Clone(function () {
  22209. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22210. }, this);
  22211. };
  22212. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22213. get: function () {
  22214. if (!this._onLoadObservable) {
  22215. this._onLoadObservable = new BABYLON.Observable();
  22216. }
  22217. return this._onLoadObservable;
  22218. },
  22219. enumerable: true,
  22220. configurable: true
  22221. });
  22222. Texture.prototype.serialize = function () {
  22223. var serializationObject = _super.prototype.serialize.call(this);
  22224. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22225. serializationObject.base64String = this._buffer;
  22226. serializationObject.name = serializationObject.name.replace("data:", "");
  22227. }
  22228. return serializationObject;
  22229. };
  22230. Texture.prototype.getClassName = function () {
  22231. return "Texture";
  22232. };
  22233. Texture.prototype.dispose = function () {
  22234. _super.prototype.dispose.call(this);
  22235. if (this.onLoadObservable) {
  22236. this.onLoadObservable.clear();
  22237. this._onLoadObservable = null;
  22238. }
  22239. this._delayedOnLoad = null;
  22240. this._delayedOnError = null;
  22241. };
  22242. // Statics
  22243. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22244. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22245. if (onLoad === void 0) { onLoad = null; }
  22246. if (onError === void 0) { onError = null; }
  22247. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22248. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22249. };
  22250. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22251. if (parsedTexture.customType) {
  22252. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22253. // Update Sampling Mode
  22254. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22255. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22256. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22257. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22258. }
  22259. }
  22260. return parsedCustomTexture;
  22261. }
  22262. if (parsedTexture.isCube) {
  22263. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22264. }
  22265. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22266. return null;
  22267. }
  22268. var texture = BABYLON.SerializationHelper.Parse(function () {
  22269. if (parsedTexture.mirrorPlane) {
  22270. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22271. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22272. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22273. return mirrorTexture;
  22274. }
  22275. else if (parsedTexture.isRenderTarget) {
  22276. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22277. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22278. return renderTargetTexture;
  22279. }
  22280. else {
  22281. var texture;
  22282. if (parsedTexture.base64String) {
  22283. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22284. }
  22285. else {
  22286. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22287. }
  22288. return texture;
  22289. }
  22290. }, parsedTexture, scene);
  22291. // Update Sampling Mode
  22292. if (parsedTexture.samplingMode) {
  22293. var sampling = parsedTexture.samplingMode;
  22294. if (texture._samplingMode !== sampling) {
  22295. texture.updateSamplingMode(sampling);
  22296. }
  22297. }
  22298. // Animations
  22299. if (parsedTexture.animations) {
  22300. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22301. var parsedAnimation = parsedTexture.animations[animationIndex];
  22302. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22303. }
  22304. }
  22305. return texture;
  22306. };
  22307. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22308. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22309. if (noMipmap === void 0) { noMipmap = false; }
  22310. if (invertY === void 0) { invertY = true; }
  22311. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22312. if (onLoad === void 0) { onLoad = null; }
  22313. if (onError === void 0) { onError = null; }
  22314. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22315. if (name.substr(0, 5) !== "data:") {
  22316. name = "data:" + name;
  22317. }
  22318. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22319. };
  22320. // Constants
  22321. Texture.NEAREST_SAMPLINGMODE = 1;
  22322. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22323. Texture.BILINEAR_SAMPLINGMODE = 2;
  22324. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22325. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22326. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22327. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22328. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22329. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22330. Texture.NEAREST_LINEAR = 7;
  22331. Texture.NEAREST_NEAREST = 8;
  22332. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22333. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22334. Texture.LINEAR_LINEAR = 11;
  22335. Texture.LINEAR_NEAREST = 12;
  22336. Texture.EXPLICIT_MODE = 0;
  22337. Texture.SPHERICAL_MODE = 1;
  22338. Texture.PLANAR_MODE = 2;
  22339. Texture.CUBIC_MODE = 3;
  22340. Texture.PROJECTION_MODE = 4;
  22341. Texture.SKYBOX_MODE = 5;
  22342. Texture.INVCUBIC_MODE = 6;
  22343. Texture.EQUIRECTANGULAR_MODE = 7;
  22344. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22345. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22346. Texture.CLAMP_ADDRESSMODE = 0;
  22347. Texture.WRAP_ADDRESSMODE = 1;
  22348. Texture.MIRROR_ADDRESSMODE = 2;
  22349. __decorate([
  22350. BABYLON.serialize()
  22351. ], Texture.prototype, "url", void 0);
  22352. __decorate([
  22353. BABYLON.serialize()
  22354. ], Texture.prototype, "uOffset", void 0);
  22355. __decorate([
  22356. BABYLON.serialize()
  22357. ], Texture.prototype, "vOffset", void 0);
  22358. __decorate([
  22359. BABYLON.serialize()
  22360. ], Texture.prototype, "uScale", void 0);
  22361. __decorate([
  22362. BABYLON.serialize()
  22363. ], Texture.prototype, "vScale", void 0);
  22364. __decorate([
  22365. BABYLON.serialize()
  22366. ], Texture.prototype, "uAng", void 0);
  22367. __decorate([
  22368. BABYLON.serialize()
  22369. ], Texture.prototype, "vAng", void 0);
  22370. __decorate([
  22371. BABYLON.serialize()
  22372. ], Texture.prototype, "wAng", void 0);
  22373. __decorate([
  22374. BABYLON.serialize()
  22375. ], Texture.prototype, "isBlocking", null);
  22376. return Texture;
  22377. }(BABYLON.BaseTexture));
  22378. BABYLON.Texture = Texture;
  22379. })(BABYLON || (BABYLON = {}));
  22380. //# sourceMappingURL=babylon.texture.js.map
  22381. var BABYLON;
  22382. (function (BABYLON) {
  22383. var _InstancesBatch = /** @class */ (function () {
  22384. function _InstancesBatch() {
  22385. this.mustReturn = false;
  22386. this.visibleInstances = new Array();
  22387. this.renderSelf = new Array();
  22388. }
  22389. return _InstancesBatch;
  22390. }());
  22391. BABYLON._InstancesBatch = _InstancesBatch;
  22392. var Mesh = /** @class */ (function (_super) {
  22393. __extends(Mesh, _super);
  22394. /**
  22395. * @constructor
  22396. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22397. * @param {Scene} scene The scene to add this mesh to.
  22398. * @param {Node} parent The parent of this mesh, if it has one
  22399. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22400. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22401. * When false, achieved by calling a clone(), also passing False.
  22402. * This will make creation of children, recursive.
  22403. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22404. */
  22405. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22406. if (scene === void 0) { scene = null; }
  22407. if (parent === void 0) { parent = null; }
  22408. if (source === void 0) { source = null; }
  22409. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22410. var _this = _super.call(this, name, scene) || this;
  22411. // Events
  22412. /**
  22413. * An event triggered before rendering the mesh
  22414. * @type {BABYLON.Observable}
  22415. */
  22416. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22417. /**
  22418. * An event triggered after rendering the mesh
  22419. * @type {BABYLON.Observable}
  22420. */
  22421. _this.onAfterRenderObservable = new BABYLON.Observable();
  22422. /**
  22423. * An event triggered before drawing the mesh
  22424. * @type {BABYLON.Observable}
  22425. */
  22426. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22427. // Members
  22428. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22429. _this.instances = new Array();
  22430. _this._LODLevels = new Array();
  22431. _this._visibleInstances = {};
  22432. _this._renderIdForInstances = new Array();
  22433. _this._batchCache = new _InstancesBatch();
  22434. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22435. // Use by builder only to know what orientation were the mesh build in.
  22436. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22437. _this.overrideMaterialSideOrientation = null;
  22438. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22439. // Will be used to save a source mesh reference, If any
  22440. _this._source = null;
  22441. scene = _this.getScene();
  22442. if (source) {
  22443. // Source mesh
  22444. _this._source = source;
  22445. // Geometry
  22446. if (source._geometry) {
  22447. source._geometry.applyToMesh(_this);
  22448. }
  22449. // Deep copy
  22450. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22451. // Tags
  22452. if (BABYLON.Tags.HasTags(source)) {
  22453. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22454. }
  22455. _this.metadata = source.metadata;
  22456. // Parent
  22457. _this.parent = source.parent;
  22458. // Pivot
  22459. _this.setPivotMatrix(source.getPivotMatrix());
  22460. _this.id = name + "." + source.id;
  22461. // Material
  22462. _this.material = source.material;
  22463. var index;
  22464. if (!doNotCloneChildren) {
  22465. // Children
  22466. for (index = 0; index < scene.meshes.length; index++) {
  22467. var mesh = scene.meshes[index];
  22468. if (mesh.parent === source) {
  22469. // doNotCloneChildren is always going to be False
  22470. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22471. }
  22472. }
  22473. }
  22474. // Physics clone
  22475. var physicsEngine = _this.getScene().getPhysicsEngine();
  22476. if (clonePhysicsImpostor && physicsEngine) {
  22477. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22478. if (impostor) {
  22479. _this.physicsImpostor = impostor.clone(_this);
  22480. }
  22481. }
  22482. // Particles
  22483. for (index = 0; index < scene.particleSystems.length; index++) {
  22484. var system = scene.particleSystems[index];
  22485. if (system.emitter === source) {
  22486. system.clone(system.name, _this);
  22487. }
  22488. }
  22489. _this.computeWorldMatrix(true);
  22490. }
  22491. // Parent
  22492. if (parent !== null) {
  22493. _this.parent = parent;
  22494. }
  22495. return _this;
  22496. }
  22497. Object.defineProperty(Mesh, "FRONTSIDE", {
  22498. /**
  22499. * Mesh side orientation : usually the external or front surface
  22500. */
  22501. get: function () {
  22502. return Mesh._FRONTSIDE;
  22503. },
  22504. enumerable: true,
  22505. configurable: true
  22506. });
  22507. Object.defineProperty(Mesh, "BACKSIDE", {
  22508. /**
  22509. * Mesh side orientation : usually the internal or back surface
  22510. */
  22511. get: function () {
  22512. return Mesh._BACKSIDE;
  22513. },
  22514. enumerable: true,
  22515. configurable: true
  22516. });
  22517. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22518. /**
  22519. * Mesh side orientation : both internal and external or front and back surfaces
  22520. */
  22521. get: function () {
  22522. return Mesh._DOUBLESIDE;
  22523. },
  22524. enumerable: true,
  22525. configurable: true
  22526. });
  22527. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22528. /**
  22529. * Mesh side orientation : by default, `FRONTSIDE`
  22530. */
  22531. get: function () {
  22532. return Mesh._DEFAULTSIDE;
  22533. },
  22534. enumerable: true,
  22535. configurable: true
  22536. });
  22537. Object.defineProperty(Mesh, "NO_CAP", {
  22538. /**
  22539. * Mesh cap setting : no cap
  22540. */
  22541. get: function () {
  22542. return Mesh._NO_CAP;
  22543. },
  22544. enumerable: true,
  22545. configurable: true
  22546. });
  22547. Object.defineProperty(Mesh, "CAP_START", {
  22548. /**
  22549. * Mesh cap setting : one cap at the beginning of the mesh
  22550. */
  22551. get: function () {
  22552. return Mesh._CAP_START;
  22553. },
  22554. enumerable: true,
  22555. configurable: true
  22556. });
  22557. Object.defineProperty(Mesh, "CAP_END", {
  22558. /**
  22559. * Mesh cap setting : one cap at the end of the mesh
  22560. */
  22561. get: function () {
  22562. return Mesh._CAP_END;
  22563. },
  22564. enumerable: true,
  22565. configurable: true
  22566. });
  22567. Object.defineProperty(Mesh, "CAP_ALL", {
  22568. /**
  22569. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22570. */
  22571. get: function () {
  22572. return Mesh._CAP_ALL;
  22573. },
  22574. enumerable: true,
  22575. configurable: true
  22576. });
  22577. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22578. set: function (callback) {
  22579. if (this._onBeforeDrawObserver) {
  22580. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22581. }
  22582. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22583. },
  22584. enumerable: true,
  22585. configurable: true
  22586. });
  22587. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22588. get: function () {
  22589. return this._morphTargetManager;
  22590. },
  22591. set: function (value) {
  22592. if (this._morphTargetManager === value) {
  22593. return;
  22594. }
  22595. this._morphTargetManager = value;
  22596. this._syncGeometryWithMorphTargetManager();
  22597. },
  22598. enumerable: true,
  22599. configurable: true
  22600. });
  22601. Object.defineProperty(Mesh.prototype, "source", {
  22602. get: function () {
  22603. return this._source;
  22604. },
  22605. enumerable: true,
  22606. configurable: true
  22607. });
  22608. // Methods
  22609. /**
  22610. * Returns the string "Mesh".
  22611. */
  22612. Mesh.prototype.getClassName = function () {
  22613. return "Mesh";
  22614. };
  22615. /**
  22616. * Returns a string.
  22617. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22618. */
  22619. Mesh.prototype.toString = function (fullDetails) {
  22620. var ret = _super.prototype.toString.call(this, fullDetails);
  22621. ret += ", n vertices: " + this.getTotalVertices();
  22622. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22623. if (this.animations) {
  22624. for (var i = 0; i < this.animations.length; i++) {
  22625. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22626. }
  22627. }
  22628. if (fullDetails) {
  22629. if (this._geometry) {
  22630. var ib = this.getIndices();
  22631. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22632. if (vb && ib) {
  22633. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22634. }
  22635. }
  22636. else {
  22637. ret += ", flat shading: UNKNOWN";
  22638. }
  22639. }
  22640. return ret;
  22641. };
  22642. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22643. /**
  22644. * True if the mesh has some Levels Of Details (LOD).
  22645. * Returns a boolean.
  22646. */
  22647. get: function () {
  22648. return this._LODLevels.length > 0;
  22649. },
  22650. enumerable: true,
  22651. configurable: true
  22652. });
  22653. Mesh.prototype._sortLODLevels = function () {
  22654. this._LODLevels.sort(function (a, b) {
  22655. if (a.distance < b.distance) {
  22656. return 1;
  22657. }
  22658. if (a.distance > b.distance) {
  22659. return -1;
  22660. }
  22661. return 0;
  22662. });
  22663. };
  22664. /**
  22665. * Add a mesh as LOD level triggered at the given distance.
  22666. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22667. * @param {number} distance The distance from the center of the object to show this level
  22668. * @param {Mesh} mesh The mesh to be added as LOD level
  22669. * @return {Mesh} This mesh (for chaining)
  22670. */
  22671. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22672. if (mesh && mesh._masterMesh) {
  22673. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22674. return this;
  22675. }
  22676. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22677. this._LODLevels.push(level);
  22678. if (mesh) {
  22679. mesh._masterMesh = this;
  22680. }
  22681. this._sortLODLevels();
  22682. return this;
  22683. };
  22684. /**
  22685. * Returns the LOD level mesh at the passed distance or null if not found.
  22686. * It is related to the method `addLODLevel(distance, mesh)`.
  22687. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22688. * Returns an object Mesh or `null`.
  22689. */
  22690. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22691. for (var index = 0; index < this._LODLevels.length; index++) {
  22692. var level = this._LODLevels[index];
  22693. if (level.distance === distance) {
  22694. return level.mesh;
  22695. }
  22696. }
  22697. return null;
  22698. };
  22699. /**
  22700. * Remove a mesh from the LOD array
  22701. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22702. * @param {Mesh} mesh The mesh to be removed.
  22703. * @return {Mesh} This mesh (for chaining)
  22704. */
  22705. Mesh.prototype.removeLODLevel = function (mesh) {
  22706. for (var index = 0; index < this._LODLevels.length; index++) {
  22707. if (this._LODLevels[index].mesh === mesh) {
  22708. this._LODLevels.splice(index, 1);
  22709. if (mesh) {
  22710. mesh._masterMesh = null;
  22711. }
  22712. }
  22713. }
  22714. this._sortLODLevels();
  22715. return this;
  22716. };
  22717. /**
  22718. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22719. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22720. */
  22721. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22722. if (!this._LODLevels || this._LODLevels.length === 0) {
  22723. return this;
  22724. }
  22725. var bSphere;
  22726. if (boundingSphere) {
  22727. bSphere = boundingSphere;
  22728. }
  22729. else {
  22730. var boundingInfo = this.getBoundingInfo();
  22731. if (!boundingInfo) {
  22732. return this;
  22733. }
  22734. bSphere = boundingInfo.boundingSphere;
  22735. }
  22736. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22737. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22738. if (this.onLODLevelSelection) {
  22739. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22740. }
  22741. return this;
  22742. }
  22743. for (var index = 0; index < this._LODLevels.length; index++) {
  22744. var level = this._LODLevels[index];
  22745. if (level.distance < distanceToCamera) {
  22746. if (level.mesh) {
  22747. level.mesh._preActivate();
  22748. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22749. }
  22750. if (this.onLODLevelSelection) {
  22751. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22752. }
  22753. return level.mesh;
  22754. }
  22755. }
  22756. if (this.onLODLevelSelection) {
  22757. this.onLODLevelSelection(distanceToCamera, this, this);
  22758. }
  22759. return this;
  22760. };
  22761. Object.defineProperty(Mesh.prototype, "geometry", {
  22762. /**
  22763. * Returns the mesh internal Geometry object.
  22764. */
  22765. get: function () {
  22766. return this._geometry;
  22767. },
  22768. enumerable: true,
  22769. configurable: true
  22770. });
  22771. /**
  22772. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22773. */
  22774. Mesh.prototype.getTotalVertices = function () {
  22775. if (!this._geometry) {
  22776. return 0;
  22777. }
  22778. return this._geometry.getTotalVertices();
  22779. };
  22780. /**
  22781. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22782. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  22783. * You can force the copy with forceCopy === true
  22784. * Returns null if the mesh has no geometry or no vertex buffer.
  22785. * Possible `kind` values :
  22786. * - BABYLON.VertexBuffer.PositionKind
  22787. * - BABYLON.VertexBuffer.UVKind
  22788. * - BABYLON.VertexBuffer.UV2Kind
  22789. * - BABYLON.VertexBuffer.UV3Kind
  22790. * - BABYLON.VertexBuffer.UV4Kind
  22791. * - BABYLON.VertexBuffer.UV5Kind
  22792. * - BABYLON.VertexBuffer.UV6Kind
  22793. * - BABYLON.VertexBuffer.ColorKind
  22794. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22795. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22796. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22797. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22798. */
  22799. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22800. if (!this._geometry) {
  22801. return null;
  22802. }
  22803. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22804. };
  22805. /**
  22806. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22807. * Returns `null` if the mesh has no geometry.
  22808. * Possible `kind` values :
  22809. * - BABYLON.VertexBuffer.PositionKind
  22810. * - BABYLON.VertexBuffer.UVKind
  22811. * - BABYLON.VertexBuffer.UV2Kind
  22812. * - BABYLON.VertexBuffer.UV3Kind
  22813. * - BABYLON.VertexBuffer.UV4Kind
  22814. * - BABYLON.VertexBuffer.UV5Kind
  22815. * - BABYLON.VertexBuffer.UV6Kind
  22816. * - BABYLON.VertexBuffer.ColorKind
  22817. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22818. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22819. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22820. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22821. */
  22822. Mesh.prototype.getVertexBuffer = function (kind) {
  22823. if (!this._geometry) {
  22824. return null;
  22825. }
  22826. return this._geometry.getVertexBuffer(kind);
  22827. };
  22828. /**
  22829. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22830. * Possible `kind` values :
  22831. * - BABYLON.VertexBuffer.PositionKind
  22832. * - BABYLON.VertexBuffer.UVKind
  22833. * - BABYLON.VertexBuffer.UV2Kind
  22834. * - BABYLON.VertexBuffer.UV3Kind
  22835. * - BABYLON.VertexBuffer.UV4Kind
  22836. * - BABYLON.VertexBuffer.UV5Kind
  22837. * - BABYLON.VertexBuffer.UV6Kind
  22838. * - BABYLON.VertexBuffer.ColorKind
  22839. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22840. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22841. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22842. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22843. */
  22844. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22845. if (!this._geometry) {
  22846. if (this._delayInfo) {
  22847. return this._delayInfo.indexOf(kind) !== -1;
  22848. }
  22849. return false;
  22850. }
  22851. return this._geometry.isVerticesDataPresent(kind);
  22852. };
  22853. /**
  22854. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22855. * Possible `kind` values :
  22856. * - BABYLON.VertexBuffer.PositionKind
  22857. * - BABYLON.VertexBuffer.UVKind
  22858. * - BABYLON.VertexBuffer.UV2Kind
  22859. * - BABYLON.VertexBuffer.UV3Kind
  22860. * - BABYLON.VertexBuffer.UV4Kind
  22861. * - BABYLON.VertexBuffer.UV5Kind
  22862. * - BABYLON.VertexBuffer.UV6Kind
  22863. * - BABYLON.VertexBuffer.ColorKind
  22864. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22865. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22866. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22867. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22868. */
  22869. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22870. if (!this._geometry) {
  22871. if (this._delayInfo) {
  22872. return this._delayInfo.indexOf(kind) !== -1;
  22873. }
  22874. return false;
  22875. }
  22876. return this._geometry.isVertexBufferUpdatable(kind);
  22877. };
  22878. /**
  22879. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22880. * Possible `kind` values :
  22881. * - BABYLON.VertexBuffer.PositionKind
  22882. * - BABYLON.VertexBuffer.UVKind
  22883. * - BABYLON.VertexBuffer.UV2Kind
  22884. * - BABYLON.VertexBuffer.UV3Kind
  22885. * - BABYLON.VertexBuffer.UV4Kind
  22886. * - BABYLON.VertexBuffer.UV5Kind
  22887. * - BABYLON.VertexBuffer.UV6Kind
  22888. * - BABYLON.VertexBuffer.ColorKind
  22889. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22890. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22891. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22892. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22893. */
  22894. Mesh.prototype.getVerticesDataKinds = function () {
  22895. if (!this._geometry) {
  22896. var result = new Array();
  22897. if (this._delayInfo) {
  22898. this._delayInfo.forEach(function (kind, index, array) {
  22899. result.push(kind);
  22900. });
  22901. }
  22902. return result;
  22903. }
  22904. return this._geometry.getVerticesDataKinds();
  22905. };
  22906. /**
  22907. * Returns a positive integer : the total number of indices in this mesh geometry.
  22908. * Returns zero if the mesh has no geometry.
  22909. */
  22910. Mesh.prototype.getTotalIndices = function () {
  22911. if (!this._geometry) {
  22912. return 0;
  22913. }
  22914. return this._geometry.getTotalIndices();
  22915. };
  22916. /**
  22917. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22918. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  22919. * Returns an empty array if the mesh has no geometry.
  22920. */
  22921. Mesh.prototype.getIndices = function (copyWhenShared) {
  22922. if (!this._geometry) {
  22923. return [];
  22924. }
  22925. return this._geometry.getIndices(copyWhenShared);
  22926. };
  22927. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22928. get: function () {
  22929. return this._masterMesh !== null && this._masterMesh !== undefined;
  22930. },
  22931. enumerable: true,
  22932. configurable: true
  22933. });
  22934. /**
  22935. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22936. */
  22937. Mesh.prototype.isReady = function () {
  22938. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22939. return false;
  22940. }
  22941. return _super.prototype.isReady.call(this);
  22942. };
  22943. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22944. /**
  22945. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22946. * This property is pertinent only for updatable parametric shapes.
  22947. */
  22948. get: function () {
  22949. return this._areNormalsFrozen;
  22950. },
  22951. enumerable: true,
  22952. configurable: true
  22953. });
  22954. /**
  22955. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22956. * It has no effect at all on other shapes.
  22957. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22958. * Returns the Mesh.
  22959. */
  22960. Mesh.prototype.freezeNormals = function () {
  22961. this._areNormalsFrozen = true;
  22962. return this;
  22963. };
  22964. /**
  22965. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22966. * It has no effect at all on other shapes.
  22967. * It reactivates the mesh normals computation if it was previously frozen.
  22968. * Returns the Mesh.
  22969. */
  22970. Mesh.prototype.unfreezeNormals = function () {
  22971. this._areNormalsFrozen = false;
  22972. return this;
  22973. };
  22974. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22975. /**
  22976. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22977. */
  22978. set: function (count) {
  22979. this._overridenInstanceCount = count;
  22980. },
  22981. enumerable: true,
  22982. configurable: true
  22983. });
  22984. // Methods
  22985. Mesh.prototype._preActivate = function () {
  22986. var sceneRenderId = this.getScene().getRenderId();
  22987. if (this._preActivateId === sceneRenderId) {
  22988. return this;
  22989. }
  22990. this._preActivateId = sceneRenderId;
  22991. this._visibleInstances = null;
  22992. return this;
  22993. };
  22994. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22995. if (this._visibleInstances) {
  22996. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22997. }
  22998. return this;
  22999. };
  23000. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23001. if (!this._visibleInstances) {
  23002. this._visibleInstances = {};
  23003. this._visibleInstances.defaultRenderId = renderId;
  23004. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23005. }
  23006. if (!this._visibleInstances[renderId]) {
  23007. this._visibleInstances[renderId] = new Array();
  23008. }
  23009. this._visibleInstances[renderId].push(instance);
  23010. return this;
  23011. };
  23012. /**
  23013. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23014. * This means the mesh underlying bounding box and sphere are recomputed.
  23015. * Returns the Mesh.
  23016. */
  23017. Mesh.prototype.refreshBoundingInfo = function () {
  23018. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23019. return this;
  23020. }
  23021. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23022. if (data) {
  23023. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23024. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23025. }
  23026. if (this.subMeshes) {
  23027. for (var index = 0; index < this.subMeshes.length; index++) {
  23028. this.subMeshes[index].refreshBoundingInfo();
  23029. }
  23030. }
  23031. this._updateBoundingInfo();
  23032. return this;
  23033. };
  23034. Mesh.prototype._createGlobalSubMesh = function (force) {
  23035. var totalVertices = this.getTotalVertices();
  23036. if (!totalVertices || !this.getIndices()) {
  23037. return null;
  23038. }
  23039. // Check if we need to recreate the submeshes
  23040. if (this.subMeshes && this.subMeshes.length > 0) {
  23041. var ib = this.getIndices();
  23042. if (!ib) {
  23043. return null;
  23044. }
  23045. var totalIndices = ib.length;
  23046. var needToRecreate = false;
  23047. if (force) {
  23048. needToRecreate = true;
  23049. }
  23050. else {
  23051. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23052. var submesh = _a[_i];
  23053. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23054. needToRecreate = true;
  23055. break;
  23056. }
  23057. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23058. needToRecreate = true;
  23059. break;
  23060. }
  23061. }
  23062. }
  23063. if (!needToRecreate) {
  23064. return this.subMeshes[0];
  23065. }
  23066. }
  23067. this.releaseSubMeshes();
  23068. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23069. };
  23070. Mesh.prototype.subdivide = function (count) {
  23071. if (count < 1) {
  23072. return;
  23073. }
  23074. var totalIndices = this.getTotalIndices();
  23075. var subdivisionSize = (totalIndices / count) | 0;
  23076. var offset = 0;
  23077. // Ensure that subdivisionSize is a multiple of 3
  23078. while (subdivisionSize % 3 !== 0) {
  23079. subdivisionSize++;
  23080. }
  23081. this.releaseSubMeshes();
  23082. for (var index = 0; index < count; index++) {
  23083. if (offset >= totalIndices) {
  23084. break;
  23085. }
  23086. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23087. offset += subdivisionSize;
  23088. }
  23089. this.synchronizeInstances();
  23090. };
  23091. /**
  23092. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23093. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23094. * The `data` are either a numeric array either a Float32Array.
  23095. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23096. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  23097. * Note that a new underlying VertexBuffer object is created each call.
  23098. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23099. *
  23100. * Possible `kind` values :
  23101. * - BABYLON.VertexBuffer.PositionKind
  23102. * - BABYLON.VertexBuffer.UVKind
  23103. * - BABYLON.VertexBuffer.UV2Kind
  23104. * - BABYLON.VertexBuffer.UV3Kind
  23105. * - BABYLON.VertexBuffer.UV4Kind
  23106. * - BABYLON.VertexBuffer.UV5Kind
  23107. * - BABYLON.VertexBuffer.UV6Kind
  23108. * - BABYLON.VertexBuffer.ColorKind
  23109. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23110. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23111. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23112. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23113. *
  23114. * Returns the Mesh.
  23115. */
  23116. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23117. if (updatable === void 0) { updatable = false; }
  23118. if (!this._geometry) {
  23119. var vertexData = new BABYLON.VertexData();
  23120. vertexData.set(data, kind);
  23121. var scene = this.getScene();
  23122. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23123. }
  23124. else {
  23125. this._geometry.setVerticesData(kind, data, updatable, stride);
  23126. }
  23127. return this;
  23128. };
  23129. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23130. if (updatable === void 0) { updatable = true; }
  23131. var vb = this.getVertexBuffer(kind);
  23132. if (!vb || vb.isUpdatable() === updatable) {
  23133. return;
  23134. }
  23135. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23136. };
  23137. /**
  23138. * Sets the mesh VertexBuffer.
  23139. * Returns the Mesh.
  23140. */
  23141. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23142. if (!this._geometry) {
  23143. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23144. }
  23145. this._geometry.setVerticesBuffer(buffer);
  23146. return this;
  23147. };
  23148. /**
  23149. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23150. * If the mesh has no geometry, it is simply returned as it is.
  23151. * The `data` are either a numeric array either a Float32Array.
  23152. * No new underlying VertexBuffer object is created.
  23153. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23154. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23155. *
  23156. * Possible `kind` values :
  23157. * - BABYLON.VertexBuffer.PositionKind
  23158. * - BABYLON.VertexBuffer.UVKind
  23159. * - BABYLON.VertexBuffer.UV2Kind
  23160. * - BABYLON.VertexBuffer.UV3Kind
  23161. * - BABYLON.VertexBuffer.UV4Kind
  23162. * - BABYLON.VertexBuffer.UV5Kind
  23163. * - BABYLON.VertexBuffer.UV6Kind
  23164. * - BABYLON.VertexBuffer.ColorKind
  23165. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23166. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23167. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23168. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23169. *
  23170. * Returns the Mesh.
  23171. */
  23172. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23173. if (!this._geometry) {
  23174. return this;
  23175. }
  23176. if (!makeItUnique) {
  23177. this._geometry.updateVerticesData(kind, data, updateExtends);
  23178. }
  23179. else {
  23180. this.makeGeometryUnique();
  23181. this.updateVerticesData(kind, data, updateExtends, false);
  23182. }
  23183. return this;
  23184. };
  23185. /**
  23186. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23187. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23188. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23189. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23190. * Returns the Mesh.
  23191. */
  23192. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23193. if (computeNormals === void 0) { computeNormals = true; }
  23194. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23195. if (!positions) {
  23196. return this;
  23197. }
  23198. positionFunction(positions);
  23199. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23200. if (computeNormals) {
  23201. var indices = this.getIndices();
  23202. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23203. if (!normals) {
  23204. return this;
  23205. }
  23206. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23207. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23208. }
  23209. return this;
  23210. };
  23211. /**
  23212. * Creates a un-shared specific occurence of the geometry for the mesh.
  23213. * Returns the Mesh.
  23214. */
  23215. Mesh.prototype.makeGeometryUnique = function () {
  23216. if (!this._geometry) {
  23217. return this;
  23218. }
  23219. var oldGeometry = this._geometry;
  23220. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23221. oldGeometry.releaseForMesh(this, true);
  23222. geometry.applyToMesh(this);
  23223. return this;
  23224. };
  23225. /**
  23226. * Sets the mesh indices.
  23227. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23228. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23229. * This method creates a new index buffer each call.
  23230. * Returns the Mesh.
  23231. */
  23232. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23233. if (totalVertices === void 0) { totalVertices = null; }
  23234. if (updatable === void 0) { updatable = false; }
  23235. if (!this._geometry) {
  23236. var vertexData = new BABYLON.VertexData();
  23237. vertexData.indices = indices;
  23238. var scene = this.getScene();
  23239. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23240. }
  23241. else {
  23242. this._geometry.setIndices(indices, totalVertices, updatable);
  23243. }
  23244. return this;
  23245. };
  23246. /**
  23247. * Update the current index buffer
  23248. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23249. * Returns the Mesh.
  23250. */
  23251. Mesh.prototype.updateIndices = function (indices, offset) {
  23252. if (!this._geometry) {
  23253. return this;
  23254. }
  23255. this._geometry.updateIndices(indices, offset);
  23256. return this;
  23257. };
  23258. /**
  23259. * Invert the geometry to move from a right handed system to a left handed one.
  23260. * Returns the Mesh.
  23261. */
  23262. Mesh.prototype.toLeftHanded = function () {
  23263. if (!this._geometry) {
  23264. return this;
  23265. }
  23266. this._geometry.toLeftHanded();
  23267. return this;
  23268. };
  23269. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23270. if (!this._geometry) {
  23271. return this;
  23272. }
  23273. var engine = this.getScene().getEngine();
  23274. // Wireframe
  23275. var indexToBind;
  23276. if (this._unIndexed) {
  23277. indexToBind = null;
  23278. }
  23279. else {
  23280. switch (fillMode) {
  23281. case BABYLON.Material.PointFillMode:
  23282. indexToBind = null;
  23283. break;
  23284. case BABYLON.Material.WireFrameFillMode:
  23285. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23286. break;
  23287. default:
  23288. case BABYLON.Material.TriangleFillMode:
  23289. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23290. break;
  23291. }
  23292. }
  23293. // VBOs
  23294. this._geometry._bind(effect, indexToBind);
  23295. return this;
  23296. };
  23297. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23298. if (alternate === void 0) { alternate = false; }
  23299. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23300. return this;
  23301. }
  23302. this.onBeforeDrawObservable.notifyObservers(this);
  23303. var scene = this.getScene();
  23304. var engine = scene.getEngine();
  23305. // Draw order
  23306. switch (fillMode) {
  23307. case BABYLON.Material.PointFillMode:
  23308. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23309. break;
  23310. case BABYLON.Material.WireFrameFillMode:
  23311. if (this._unIndexed) {
  23312. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23313. }
  23314. else {
  23315. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23316. }
  23317. break;
  23318. default:
  23319. if (this._unIndexed) {
  23320. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23321. }
  23322. else {
  23323. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23324. }
  23325. }
  23326. if (scene._isAlternateRenderingEnabled && !alternate) {
  23327. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23328. if (!effect || !scene.activeCamera) {
  23329. return this;
  23330. }
  23331. scene._switchToAlternateCameraConfiguration(true);
  23332. this._effectiveMaterial.bindView(effect);
  23333. this._effectiveMaterial.bindViewProjection(effect);
  23334. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23335. this._draw(subMesh, fillMode, instancesCount, true);
  23336. engine.setViewport(scene.activeCamera.viewport);
  23337. scene._switchToAlternateCameraConfiguration(false);
  23338. this._effectiveMaterial.bindView(effect);
  23339. this._effectiveMaterial.bindViewProjection(effect);
  23340. }
  23341. return this;
  23342. };
  23343. /**
  23344. * Registers for this mesh a javascript function called just before the rendering process.
  23345. * This function is passed the current mesh.
  23346. * Return the Mesh.
  23347. */
  23348. Mesh.prototype.registerBeforeRender = function (func) {
  23349. this.onBeforeRenderObservable.add(func);
  23350. return this;
  23351. };
  23352. /**
  23353. * Disposes a previously registered javascript function called before the rendering.
  23354. * This function is passed the current mesh.
  23355. * Returns the Mesh.
  23356. */
  23357. Mesh.prototype.unregisterBeforeRender = function (func) {
  23358. this.onBeforeRenderObservable.removeCallback(func);
  23359. return this;
  23360. };
  23361. /**
  23362. * Registers for this mesh a javascript function called just after the rendering is complete.
  23363. * This function is passed the current mesh.
  23364. * Returns the Mesh.
  23365. */
  23366. Mesh.prototype.registerAfterRender = function (func) {
  23367. this.onAfterRenderObservable.add(func);
  23368. return this;
  23369. };
  23370. /**
  23371. * Disposes a previously registered javascript function called after the rendering.
  23372. * This function is passed the current mesh.
  23373. * Return the Mesh.
  23374. */
  23375. Mesh.prototype.unregisterAfterRender = function (func) {
  23376. this.onAfterRenderObservable.removeCallback(func);
  23377. return this;
  23378. };
  23379. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23380. var scene = this.getScene();
  23381. this._batchCache.mustReturn = false;
  23382. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23383. this._batchCache.visibleInstances[subMeshId] = null;
  23384. if (this._visibleInstances) {
  23385. var currentRenderId = scene.getRenderId();
  23386. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23387. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23388. var selfRenderId = this._renderId;
  23389. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23390. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23391. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23392. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23393. }
  23394. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23395. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23396. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23397. this._batchCache.mustReturn = true;
  23398. return this._batchCache;
  23399. }
  23400. if (currentRenderId !== selfRenderId) {
  23401. this._batchCache.renderSelf[subMeshId] = false;
  23402. }
  23403. }
  23404. this._renderIdForInstances[subMeshId] = currentRenderId;
  23405. }
  23406. return this._batchCache;
  23407. };
  23408. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23409. var visibleInstances = batch.visibleInstances[subMesh._id];
  23410. if (!visibleInstances) {
  23411. return this;
  23412. }
  23413. var matricesCount = visibleInstances.length + 1;
  23414. var bufferSize = matricesCount * 16 * 4;
  23415. var currentInstancesBufferSize = this._instancesBufferSize;
  23416. var instancesBuffer = this._instancesBuffer;
  23417. while (this._instancesBufferSize < bufferSize) {
  23418. this._instancesBufferSize *= 2;
  23419. }
  23420. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23421. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23422. }
  23423. var offset = 0;
  23424. var instancesCount = 0;
  23425. var world = this.getWorldMatrix();
  23426. if (batch.renderSelf[subMesh._id]) {
  23427. world.copyToArray(this._instancesData, offset);
  23428. offset += 16;
  23429. instancesCount++;
  23430. }
  23431. if (visibleInstances) {
  23432. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23433. var instance = visibleInstances[instanceIndex];
  23434. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23435. offset += 16;
  23436. instancesCount++;
  23437. }
  23438. }
  23439. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23440. if (instancesBuffer) {
  23441. instancesBuffer.dispose();
  23442. }
  23443. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23444. this._instancesBuffer = instancesBuffer;
  23445. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23446. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23447. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23448. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23449. }
  23450. else {
  23451. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23452. }
  23453. this._bind(subMesh, effect, fillMode);
  23454. this._draw(subMesh, fillMode, instancesCount);
  23455. engine.unbindInstanceAttributes();
  23456. return this;
  23457. };
  23458. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23459. var scene = this.getScene();
  23460. var engine = scene.getEngine();
  23461. if (hardwareInstancedRendering) {
  23462. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23463. }
  23464. else {
  23465. if (batch.renderSelf[subMesh._id]) {
  23466. // Draw
  23467. if (onBeforeDraw) {
  23468. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23469. }
  23470. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23471. }
  23472. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23473. if (visibleInstancesForSubMesh) {
  23474. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23475. var instance = visibleInstancesForSubMesh[instanceIndex];
  23476. // World
  23477. var world = instance.getWorldMatrix();
  23478. if (onBeforeDraw) {
  23479. onBeforeDraw(true, world, effectiveMaterial);
  23480. }
  23481. // Draw
  23482. this._draw(subMesh, fillMode);
  23483. }
  23484. }
  23485. }
  23486. return this;
  23487. };
  23488. /**
  23489. * Triggers the draw call for the mesh.
  23490. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23491. * Returns the Mesh.
  23492. */
  23493. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23494. this.checkOcclusionQuery();
  23495. if (this._isOccluded) {
  23496. return this;
  23497. }
  23498. var scene = this.getScene();
  23499. // Managing instances
  23500. var batch = this._getInstancesRenderList(subMesh._id);
  23501. if (batch.mustReturn) {
  23502. return this;
  23503. }
  23504. // Checking geometry state
  23505. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23506. return this;
  23507. }
  23508. this.onBeforeRenderObservable.notifyObservers(this);
  23509. var engine = scene.getEngine();
  23510. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23511. // Material
  23512. var material = subMesh.getMaterial();
  23513. if (!material) {
  23514. return this;
  23515. }
  23516. this._effectiveMaterial = material;
  23517. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23518. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23519. return this;
  23520. }
  23521. }
  23522. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23523. return this;
  23524. }
  23525. // Alpha mode
  23526. if (enableAlphaMode) {
  23527. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23528. }
  23529. // Outline - step 1
  23530. var savedDepthWrite = engine.getDepthWrite();
  23531. if (this.renderOutline) {
  23532. engine.setDepthWrite(false);
  23533. scene.getOutlineRenderer().render(subMesh, batch);
  23534. engine.setDepthWrite(savedDepthWrite);
  23535. }
  23536. var effect;
  23537. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23538. effect = subMesh.effect;
  23539. }
  23540. else {
  23541. effect = this._effectiveMaterial.getEffect();
  23542. }
  23543. if (!effect) {
  23544. return this;
  23545. }
  23546. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23547. if (this._effectiveMaterial.forceDepthWrite) {
  23548. engine.setDepthWrite(true);
  23549. }
  23550. // Bind
  23551. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23552. if (!hardwareInstancedRendering) {
  23553. this._bind(subMesh, effect, fillMode);
  23554. }
  23555. var world = this.getWorldMatrix();
  23556. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23557. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23558. }
  23559. else {
  23560. this._effectiveMaterial.bind(world, this);
  23561. }
  23562. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23563. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23564. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23565. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23566. }
  23567. // Draw
  23568. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23569. // Unbind
  23570. this._effectiveMaterial.unbind();
  23571. // Outline - step 2
  23572. if (this.renderOutline && savedDepthWrite) {
  23573. engine.setDepthWrite(true);
  23574. engine.setColorWrite(false);
  23575. scene.getOutlineRenderer().render(subMesh, batch);
  23576. engine.setColorWrite(true);
  23577. }
  23578. // Overlay
  23579. if (this.renderOverlay) {
  23580. var currentMode = engine.getAlphaMode();
  23581. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23582. scene.getOutlineRenderer().render(subMesh, batch, true);
  23583. engine.setAlphaMode(currentMode);
  23584. }
  23585. this.onAfterRenderObservable.notifyObservers(this);
  23586. return this;
  23587. };
  23588. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23589. if (isInstance) {
  23590. effectiveMaterial.bindOnlyWorldMatrix(world);
  23591. }
  23592. return this;
  23593. };
  23594. /**
  23595. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23596. */
  23597. Mesh.prototype.getEmittedParticleSystems = function () {
  23598. var results = new Array();
  23599. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23600. var particleSystem = this.getScene().particleSystems[index];
  23601. if (particleSystem.emitter === this) {
  23602. results.push(particleSystem);
  23603. }
  23604. }
  23605. return results;
  23606. };
  23607. /**
  23608. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23609. */
  23610. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23611. var results = new Array();
  23612. var descendants = this.getDescendants();
  23613. descendants.push(this);
  23614. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23615. var particleSystem = this.getScene().particleSystems[index];
  23616. var emitter = particleSystem.emitter;
  23617. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23618. results.push(particleSystem);
  23619. }
  23620. }
  23621. return results;
  23622. };
  23623. Mesh.prototype._checkDelayState = function () {
  23624. var scene = this.getScene();
  23625. if (this._geometry) {
  23626. this._geometry.load(scene);
  23627. }
  23628. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23629. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23630. this._queueLoad(this, scene);
  23631. }
  23632. return this;
  23633. };
  23634. Mesh.prototype._queueLoad = function (mesh, scene) {
  23635. var _this = this;
  23636. scene._addPendingData(mesh);
  23637. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23638. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23639. if (data instanceof ArrayBuffer) {
  23640. _this._delayLoadingFunction(data, _this);
  23641. }
  23642. else {
  23643. _this._delayLoadingFunction(JSON.parse(data), _this);
  23644. }
  23645. _this.instances.forEach(function (instance) {
  23646. instance._syncSubMeshes();
  23647. });
  23648. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23649. scene._removePendingData(_this);
  23650. }, function () { }, scene.database, getBinaryData);
  23651. return this;
  23652. };
  23653. /**
  23654. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23655. */
  23656. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23657. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23658. return false;
  23659. }
  23660. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23661. return false;
  23662. }
  23663. this._checkDelayState();
  23664. return true;
  23665. };
  23666. /**
  23667. * Sets the mesh material by the material or multiMaterial `id` property.
  23668. * The material `id` is a string identifying the material or the multiMaterial.
  23669. * This method returns the Mesh.
  23670. */
  23671. Mesh.prototype.setMaterialByID = function (id) {
  23672. var materials = this.getScene().materials;
  23673. var index;
  23674. for (index = materials.length - 1; index > -1; index--) {
  23675. if (materials[index].id === id) {
  23676. this.material = materials[index];
  23677. return this;
  23678. }
  23679. }
  23680. // Multi
  23681. var multiMaterials = this.getScene().multiMaterials;
  23682. for (index = multiMaterials.length - 1; index > -1; index--) {
  23683. if (multiMaterials[index].id === id) {
  23684. this.material = multiMaterials[index];
  23685. return this;
  23686. }
  23687. }
  23688. return this;
  23689. };
  23690. /**
  23691. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23692. */
  23693. Mesh.prototype.getAnimatables = function () {
  23694. var results = new Array();
  23695. if (this.material) {
  23696. results.push(this.material);
  23697. }
  23698. if (this.skeleton) {
  23699. results.push(this.skeleton);
  23700. }
  23701. return results;
  23702. };
  23703. /**
  23704. * Modifies the mesh geometry according to the passed transformation matrix.
  23705. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23706. * The mesh normals are modified accordingly the same transformation.
  23707. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23708. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23709. * Returns the Mesh.
  23710. */
  23711. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23712. // Position
  23713. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23714. return this;
  23715. }
  23716. var submeshes = this.subMeshes.splice(0);
  23717. this._resetPointsArrayCache();
  23718. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23719. var temp = new Array();
  23720. var index;
  23721. for (index = 0; index < data.length; index += 3) {
  23722. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23723. }
  23724. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23725. // Normals
  23726. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23727. return this;
  23728. }
  23729. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23730. temp = [];
  23731. for (index = 0; index < data.length; index += 3) {
  23732. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23733. }
  23734. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23735. // flip faces?
  23736. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23737. this.flipFaces();
  23738. }
  23739. // Restore submeshes
  23740. this.releaseSubMeshes();
  23741. this.subMeshes = submeshes;
  23742. return this;
  23743. };
  23744. /**
  23745. * Modifies the mesh geometry according to its own current World Matrix.
  23746. * The mesh World Matrix is then reset.
  23747. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23748. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23749. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23750. * Returns the Mesh.
  23751. */
  23752. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23753. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23754. this.scaling.copyFromFloats(1, 1, 1);
  23755. this.position.copyFromFloats(0, 0, 0);
  23756. this.rotation.copyFromFloats(0, 0, 0);
  23757. //only if quaternion is already set
  23758. if (this.rotationQuaternion) {
  23759. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23760. }
  23761. this._worldMatrix = BABYLON.Matrix.Identity();
  23762. return this;
  23763. };
  23764. Object.defineProperty(Mesh.prototype, "_positions", {
  23765. // Cache
  23766. get: function () {
  23767. if (this._geometry) {
  23768. return this._geometry._positions;
  23769. }
  23770. return null;
  23771. },
  23772. enumerable: true,
  23773. configurable: true
  23774. });
  23775. Mesh.prototype._resetPointsArrayCache = function () {
  23776. if (this._geometry) {
  23777. this._geometry._resetPointsArrayCache();
  23778. }
  23779. return this;
  23780. };
  23781. Mesh.prototype._generatePointsArray = function () {
  23782. if (this._geometry) {
  23783. return this._geometry._generatePointsArray();
  23784. }
  23785. return false;
  23786. };
  23787. /**
  23788. * Returns a new Mesh object generated from the current mesh properties.
  23789. * This method must not get confused with createInstance().
  23790. * The parameter `name` is a string, the name given to the new mesh.
  23791. * The optional parameter `newParent` can be any Node object (default `null`).
  23792. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23793. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  23794. */
  23795. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23796. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23797. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23798. };
  23799. /**
  23800. * Disposes the mesh.
  23801. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23802. */
  23803. Mesh.prototype.dispose = function (doNotRecurse) {
  23804. var _this = this;
  23805. this.morphTargetManager = null;
  23806. if (this._geometry) {
  23807. this._geometry.releaseForMesh(this, true);
  23808. }
  23809. // Sources
  23810. var meshes = this.getScene().meshes;
  23811. meshes.forEach(function (mesh) {
  23812. if (mesh._source && mesh._source === _this) {
  23813. mesh._source = null;
  23814. }
  23815. });
  23816. this._source = null;
  23817. // Instances
  23818. if (this._instancesBuffer) {
  23819. this._instancesBuffer.dispose();
  23820. this._instancesBuffer = null;
  23821. }
  23822. while (this.instances.length) {
  23823. this.instances[0].dispose();
  23824. }
  23825. // Highlight layers.
  23826. var highlightLayers = this.getScene().highlightLayers;
  23827. for (var i = 0; i < highlightLayers.length; i++) {
  23828. var highlightLayer = highlightLayers[i];
  23829. if (highlightLayer) {
  23830. highlightLayer.removeMesh(this);
  23831. highlightLayer.removeExcludedMesh(this);
  23832. }
  23833. }
  23834. _super.prototype.dispose.call(this, doNotRecurse);
  23835. };
  23836. /**
  23837. * Modifies the mesh geometry according to a displacement map.
  23838. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  23839. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23840. * This method returns nothing.
  23841. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23842. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23843. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  23844. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23845. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23846. *
  23847. * Returns the Mesh.
  23848. */
  23849. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23850. var _this = this;
  23851. var scene = this.getScene();
  23852. var onload = function (img) {
  23853. // Getting height map data
  23854. var canvas = document.createElement("canvas");
  23855. var context = canvas.getContext("2d");
  23856. var heightMapWidth = img.width;
  23857. var heightMapHeight = img.height;
  23858. canvas.width = heightMapWidth;
  23859. canvas.height = heightMapHeight;
  23860. context.drawImage(img, 0, 0);
  23861. // Create VertexData from map data
  23862. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23863. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23864. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23865. //execute success callback, if set
  23866. if (onSuccess) {
  23867. onSuccess(_this);
  23868. }
  23869. };
  23870. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23871. return this;
  23872. };
  23873. /**
  23874. * Modifies the mesh geometry according to a displacementMap buffer.
  23875. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  23876. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23877. * This method returns nothing.
  23878. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  23879. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23880. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23881. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23882. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23883. *
  23884. * Returns the Mesh.
  23885. */
  23886. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23887. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23888. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23889. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23890. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23891. return this;
  23892. }
  23893. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23894. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23895. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23896. var position = BABYLON.Vector3.Zero();
  23897. var normal = BABYLON.Vector3.Zero();
  23898. var uv = BABYLON.Vector2.Zero();
  23899. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23900. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23901. for (var index = 0; index < positions.length; index += 3) {
  23902. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23903. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23904. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23905. // Compute height
  23906. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23907. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23908. var pos = (u + v * heightMapWidth) * 4;
  23909. var r = buffer[pos] / 255.0;
  23910. var g = buffer[pos + 1] / 255.0;
  23911. var b = buffer[pos + 2] / 255.0;
  23912. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23913. normal.normalize();
  23914. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23915. position = position.add(normal);
  23916. position.toArray(positions, index);
  23917. }
  23918. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23919. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23920. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23921. return this;
  23922. };
  23923. /**
  23924. * Modify the mesh to get a flat shading rendering.
  23925. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23926. * This method returns the Mesh.
  23927. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23928. */
  23929. Mesh.prototype.convertToFlatShadedMesh = function () {
  23930. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23931. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23932. var kinds = this.getVerticesDataKinds();
  23933. var vbs = {};
  23934. var data = {};
  23935. var newdata = {};
  23936. var updatableNormals = false;
  23937. var kindIndex;
  23938. var kind;
  23939. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23940. kind = kinds[kindIndex];
  23941. var vertexBuffer = this.getVertexBuffer(kind);
  23942. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23943. updatableNormals = vertexBuffer.isUpdatable();
  23944. kinds.splice(kindIndex, 1);
  23945. kindIndex--;
  23946. continue;
  23947. }
  23948. vbs[kind] = vertexBuffer;
  23949. data[kind] = vbs[kind].getData();
  23950. newdata[kind] = [];
  23951. }
  23952. // Save previous submeshes
  23953. var previousSubmeshes = this.subMeshes.slice(0);
  23954. var indices = this.getIndices();
  23955. var totalIndices = this.getTotalIndices();
  23956. // Generating unique vertices per face
  23957. var index;
  23958. for (index = 0; index < totalIndices; index++) {
  23959. var vertexIndex = indices[index];
  23960. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23961. kind = kinds[kindIndex];
  23962. var stride = vbs[kind].getStrideSize();
  23963. for (var offset = 0; offset < stride; offset++) {
  23964. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23965. }
  23966. }
  23967. }
  23968. // Updating faces & normal
  23969. var normals = [];
  23970. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23971. for (index = 0; index < totalIndices; index += 3) {
  23972. indices[index] = index;
  23973. indices[index + 1] = index + 1;
  23974. indices[index + 2] = index + 2;
  23975. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23976. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23977. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23978. var p1p2 = p1.subtract(p2);
  23979. var p3p2 = p3.subtract(p2);
  23980. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23981. // Store same normals for every vertex
  23982. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23983. normals.push(normal.x);
  23984. normals.push(normal.y);
  23985. normals.push(normal.z);
  23986. }
  23987. }
  23988. this.setIndices(indices);
  23989. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23990. // Updating vertex buffers
  23991. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23992. kind = kinds[kindIndex];
  23993. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23994. }
  23995. // Updating submeshes
  23996. this.releaseSubMeshes();
  23997. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23998. var previousOne = previousSubmeshes[submeshIndex];
  23999. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24000. }
  24001. this.synchronizeInstances();
  24002. return this;
  24003. };
  24004. /**
  24005. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24006. * In other words, more vertices, no more indices and a single bigger VBO.
  24007. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24008. * Returns the Mesh.
  24009. */
  24010. Mesh.prototype.convertToUnIndexedMesh = function () {
  24011. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24012. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24013. var kinds = this.getVerticesDataKinds();
  24014. var vbs = {};
  24015. var data = {};
  24016. var newdata = {};
  24017. var kindIndex;
  24018. var kind;
  24019. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24020. kind = kinds[kindIndex];
  24021. var vertexBuffer = this.getVertexBuffer(kind);
  24022. vbs[kind] = vertexBuffer;
  24023. data[kind] = vbs[kind].getData();
  24024. newdata[kind] = [];
  24025. }
  24026. // Save previous submeshes
  24027. var previousSubmeshes = this.subMeshes.slice(0);
  24028. var indices = this.getIndices();
  24029. var totalIndices = this.getTotalIndices();
  24030. // Generating unique vertices per face
  24031. var index;
  24032. for (index = 0; index < totalIndices; index++) {
  24033. var vertexIndex = indices[index];
  24034. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24035. kind = kinds[kindIndex];
  24036. var stride = vbs[kind].getStrideSize();
  24037. for (var offset = 0; offset < stride; offset++) {
  24038. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24039. }
  24040. }
  24041. }
  24042. // Updating indices
  24043. for (index = 0; index < totalIndices; index += 3) {
  24044. indices[index] = index;
  24045. indices[index + 1] = index + 1;
  24046. indices[index + 2] = index + 2;
  24047. }
  24048. this.setIndices(indices);
  24049. // Updating vertex buffers
  24050. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24051. kind = kinds[kindIndex];
  24052. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24053. }
  24054. // Updating submeshes
  24055. this.releaseSubMeshes();
  24056. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24057. var previousOne = previousSubmeshes[submeshIndex];
  24058. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24059. }
  24060. this._unIndexed = true;
  24061. this.synchronizeInstances();
  24062. return this;
  24063. };
  24064. /**
  24065. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24066. * This method returns the Mesh.
  24067. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24068. */
  24069. Mesh.prototype.flipFaces = function (flipNormals) {
  24070. if (flipNormals === void 0) { flipNormals = false; }
  24071. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24072. var i;
  24073. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24074. for (i = 0; i < vertex_data.normals.length; i++) {
  24075. vertex_data.normals[i] *= -1;
  24076. }
  24077. }
  24078. if (vertex_data.indices) {
  24079. var temp;
  24080. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24081. // reassign indices
  24082. temp = vertex_data.indices[i + 1];
  24083. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24084. vertex_data.indices[i + 2] = temp;
  24085. }
  24086. }
  24087. vertex_data.applyToMesh(this);
  24088. return this;
  24089. };
  24090. // Instances
  24091. /**
  24092. * Creates a new InstancedMesh object from the mesh model.
  24093. * An instance shares the same properties and the same material than its model.
  24094. * Only these properties of each instance can then be set individually :
  24095. * - position
  24096. * - rotation
  24097. * - rotationQuaternion
  24098. * - setPivotMatrix
  24099. * - scaling
  24100. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24101. * Warning : this method is not supported for Line mesh and LineSystem
  24102. */
  24103. Mesh.prototype.createInstance = function (name) {
  24104. return new BABYLON.InstancedMesh(name, this);
  24105. };
  24106. /**
  24107. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24108. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24109. * This method returns the Mesh.
  24110. */
  24111. Mesh.prototype.synchronizeInstances = function () {
  24112. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24113. var instance = this.instances[instanceIndex];
  24114. instance._syncSubMeshes();
  24115. }
  24116. return this;
  24117. };
  24118. /**
  24119. * Simplify the mesh according to the given array of settings.
  24120. * Function will return immediately and will simplify async. It returns the Mesh.
  24121. * @param settings a collection of simplification settings.
  24122. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24123. * @param type the type of simplification to run.
  24124. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24125. */
  24126. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24127. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24128. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24129. this.getScene().simplificationQueue.addTask({
  24130. settings: settings,
  24131. parallelProcessing: parallelProcessing,
  24132. mesh: this,
  24133. simplificationType: simplificationType,
  24134. successCallback: successCallback
  24135. });
  24136. return this;
  24137. };
  24138. /**
  24139. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24140. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24141. * This should be used together with the simplification to avoid disappearing triangles.
  24142. * Returns the Mesh.
  24143. * @param successCallback an optional success callback to be called after the optimization finished.
  24144. */
  24145. Mesh.prototype.optimizeIndices = function (successCallback) {
  24146. var _this = this;
  24147. var indices = this.getIndices();
  24148. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24149. if (!positions || !indices) {
  24150. return this;
  24151. }
  24152. var vectorPositions = new Array();
  24153. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24154. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24155. }
  24156. var dupes = new Array();
  24157. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24158. var realPos = vectorPositions.length - 1 - iteration;
  24159. var testedPosition = vectorPositions[realPos];
  24160. for (var j = 0; j < realPos; ++j) {
  24161. var againstPosition = vectorPositions[j];
  24162. if (testedPosition.equals(againstPosition)) {
  24163. dupes[realPos] = j;
  24164. break;
  24165. }
  24166. }
  24167. }, function () {
  24168. for (var i = 0; i < indices.length; ++i) {
  24169. indices[i] = dupes[indices[i]] || indices[i];
  24170. }
  24171. //indices are now reordered
  24172. var originalSubMeshes = _this.subMeshes.slice(0);
  24173. _this.setIndices(indices);
  24174. _this.subMeshes = originalSubMeshes;
  24175. if (successCallback) {
  24176. successCallback(_this);
  24177. }
  24178. });
  24179. return this;
  24180. };
  24181. Mesh.prototype.serialize = function (serializationObject) {
  24182. serializationObject.name = this.name;
  24183. serializationObject.id = this.id;
  24184. serializationObject.type = this.getClassName();
  24185. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24186. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24187. }
  24188. serializationObject.position = this.position.asArray();
  24189. if (this.rotationQuaternion) {
  24190. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24191. }
  24192. else if (this.rotation) {
  24193. serializationObject.rotation = this.rotation.asArray();
  24194. }
  24195. serializationObject.scaling = this.scaling.asArray();
  24196. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24197. serializationObject.isEnabled = this.isEnabled();
  24198. serializationObject.isVisible = this.isVisible;
  24199. serializationObject.infiniteDistance = this.infiniteDistance;
  24200. serializationObject.pickable = this.isPickable;
  24201. serializationObject.receiveShadows = this.receiveShadows;
  24202. serializationObject.billboardMode = this.billboardMode;
  24203. serializationObject.visibility = this.visibility;
  24204. serializationObject.checkCollisions = this.checkCollisions;
  24205. serializationObject.isBlocker = this.isBlocker;
  24206. // Parent
  24207. if (this.parent) {
  24208. serializationObject.parentId = this.parent.id;
  24209. }
  24210. // Geometry
  24211. var geometry = this._geometry;
  24212. if (geometry) {
  24213. var geometryId = geometry.id;
  24214. serializationObject.geometryId = geometryId;
  24215. // SubMeshes
  24216. serializationObject.subMeshes = [];
  24217. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24218. var subMesh = this.subMeshes[subIndex];
  24219. serializationObject.subMeshes.push({
  24220. materialIndex: subMesh.materialIndex,
  24221. verticesStart: subMesh.verticesStart,
  24222. verticesCount: subMesh.verticesCount,
  24223. indexStart: subMesh.indexStart,
  24224. indexCount: subMesh.indexCount
  24225. });
  24226. }
  24227. }
  24228. // Material
  24229. if (this.material) {
  24230. serializationObject.materialId = this.material.id;
  24231. }
  24232. else {
  24233. this.material = null;
  24234. }
  24235. // Morph targets
  24236. if (this.morphTargetManager) {
  24237. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24238. }
  24239. // Skeleton
  24240. if (this.skeleton) {
  24241. serializationObject.skeletonId = this.skeleton.id;
  24242. }
  24243. // Physics
  24244. //TODO implement correct serialization for physics impostors.
  24245. var impostor = this.getPhysicsImpostor();
  24246. if (impostor) {
  24247. serializationObject.physicsMass = impostor.getParam("mass");
  24248. serializationObject.physicsFriction = impostor.getParam("friction");
  24249. serializationObject.physicsRestitution = impostor.getParam("mass");
  24250. serializationObject.physicsImpostor = impostor.type;
  24251. }
  24252. // Metadata
  24253. if (this.metadata) {
  24254. serializationObject.metadata = this.metadata;
  24255. }
  24256. // Instances
  24257. serializationObject.instances = [];
  24258. for (var index = 0; index < this.instances.length; index++) {
  24259. var instance = this.instances[index];
  24260. var serializationInstance = {
  24261. name: instance.name,
  24262. position: instance.position.asArray(),
  24263. scaling: instance.scaling.asArray()
  24264. };
  24265. if (instance.rotationQuaternion) {
  24266. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24267. }
  24268. else if (instance.rotation) {
  24269. serializationInstance.rotation = instance.rotation.asArray();
  24270. }
  24271. serializationObject.instances.push(serializationInstance);
  24272. // Animations
  24273. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24274. serializationInstance.ranges = instance.serializeAnimationRanges();
  24275. }
  24276. //
  24277. // Animations
  24278. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24279. serializationObject.ranges = this.serializeAnimationRanges();
  24280. // Layer mask
  24281. serializationObject.layerMask = this.layerMask;
  24282. // Alpha
  24283. serializationObject.alphaIndex = this.alphaIndex;
  24284. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24285. // Overlay
  24286. serializationObject.overlayAlpha = this.overlayAlpha;
  24287. serializationObject.overlayColor = this.overlayColor.asArray();
  24288. serializationObject.renderOverlay = this.renderOverlay;
  24289. // Fog
  24290. serializationObject.applyFog = this.applyFog;
  24291. // Action Manager
  24292. if (this.actionManager) {
  24293. serializationObject.actions = this.actionManager.serialize(this.name);
  24294. }
  24295. };
  24296. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24297. if (!this.geometry) {
  24298. return;
  24299. }
  24300. this._markSubMeshesAsAttributesDirty();
  24301. var morphTargetManager = this._morphTargetManager;
  24302. if (morphTargetManager && morphTargetManager.vertexCount) {
  24303. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24304. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24305. this.morphTargetManager = null;
  24306. return;
  24307. }
  24308. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24309. var morphTarget = morphTargetManager.getActiveTarget(index);
  24310. var positions = morphTarget.getPositions();
  24311. if (!positions) {
  24312. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24313. return;
  24314. }
  24315. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24316. var normals = morphTarget.getNormals();
  24317. if (normals) {
  24318. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24319. }
  24320. var tangents = morphTarget.getTangents();
  24321. if (tangents) {
  24322. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24323. }
  24324. }
  24325. }
  24326. else {
  24327. var index = 0;
  24328. // Positions
  24329. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24330. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24331. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24332. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24333. }
  24334. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24335. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24336. }
  24337. index++;
  24338. }
  24339. }
  24340. };
  24341. // Statics
  24342. /**
  24343. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24344. * The parameter `parsedMesh` is the mesh to be copied.
  24345. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24346. */
  24347. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24348. var mesh;
  24349. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24350. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24351. }
  24352. else {
  24353. mesh = new Mesh(parsedMesh.name, scene);
  24354. }
  24355. mesh.id = parsedMesh.id;
  24356. if (BABYLON.Tags) {
  24357. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24358. }
  24359. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24360. if (parsedMesh.metadata !== undefined) {
  24361. mesh.metadata = parsedMesh.metadata;
  24362. }
  24363. if (parsedMesh.rotationQuaternion) {
  24364. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24365. }
  24366. else if (parsedMesh.rotation) {
  24367. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24368. }
  24369. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24370. if (parsedMesh.localMatrix) {
  24371. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24372. }
  24373. else if (parsedMesh.pivotMatrix) {
  24374. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24375. }
  24376. mesh.setEnabled(parsedMesh.isEnabled);
  24377. mesh.isVisible = parsedMesh.isVisible;
  24378. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24379. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24380. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24381. if (parsedMesh.applyFog !== undefined) {
  24382. mesh.applyFog = parsedMesh.applyFog;
  24383. }
  24384. if (parsedMesh.pickable !== undefined) {
  24385. mesh.isPickable = parsedMesh.pickable;
  24386. }
  24387. if (parsedMesh.alphaIndex !== undefined) {
  24388. mesh.alphaIndex = parsedMesh.alphaIndex;
  24389. }
  24390. mesh.receiveShadows = parsedMesh.receiveShadows;
  24391. mesh.billboardMode = parsedMesh.billboardMode;
  24392. if (parsedMesh.visibility !== undefined) {
  24393. mesh.visibility = parsedMesh.visibility;
  24394. }
  24395. mesh.checkCollisions = parsedMesh.checkCollisions;
  24396. if (parsedMesh.isBlocker !== undefined) {
  24397. mesh.isBlocker = parsedMesh.isBlocker;
  24398. }
  24399. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24400. // freezeWorldMatrix
  24401. if (parsedMesh.freezeWorldMatrix) {
  24402. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24403. }
  24404. // Parent
  24405. if (parsedMesh.parentId) {
  24406. mesh._waitingParentId = parsedMesh.parentId;
  24407. }
  24408. // Actions
  24409. if (parsedMesh.actions !== undefined) {
  24410. mesh._waitingActions = parsedMesh.actions;
  24411. }
  24412. // Overlay
  24413. if (parsedMesh.overlayAlpha !== undefined) {
  24414. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24415. }
  24416. if (parsedMesh.overlayColor !== undefined) {
  24417. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24418. }
  24419. if (parsedMesh.renderOverlay !== undefined) {
  24420. mesh.renderOverlay = parsedMesh.renderOverlay;
  24421. }
  24422. // Geometry
  24423. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24424. if (parsedMesh.delayLoadingFile) {
  24425. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24426. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24427. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24428. if (parsedMesh._binaryInfo) {
  24429. mesh._binaryInfo = parsedMesh._binaryInfo;
  24430. }
  24431. mesh._delayInfo = [];
  24432. if (parsedMesh.hasUVs) {
  24433. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24434. }
  24435. if (parsedMesh.hasUVs2) {
  24436. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24437. }
  24438. if (parsedMesh.hasUVs3) {
  24439. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24440. }
  24441. if (parsedMesh.hasUVs4) {
  24442. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24443. }
  24444. if (parsedMesh.hasUVs5) {
  24445. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24446. }
  24447. if (parsedMesh.hasUVs6) {
  24448. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24449. }
  24450. if (parsedMesh.hasColors) {
  24451. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24452. }
  24453. if (parsedMesh.hasMatricesIndices) {
  24454. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24455. }
  24456. if (parsedMesh.hasMatricesWeights) {
  24457. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24458. }
  24459. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24460. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24461. mesh._checkDelayState();
  24462. }
  24463. }
  24464. else {
  24465. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24466. }
  24467. // Material
  24468. if (parsedMesh.materialId) {
  24469. mesh.setMaterialByID(parsedMesh.materialId);
  24470. }
  24471. else {
  24472. mesh.material = null;
  24473. }
  24474. // Morph targets
  24475. if (parsedMesh.morphTargetManagerId > -1) {
  24476. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24477. }
  24478. // Skeleton
  24479. if (parsedMesh.skeletonId > -1) {
  24480. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24481. if (parsedMesh.numBoneInfluencers) {
  24482. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24483. }
  24484. }
  24485. // Animations
  24486. if (parsedMesh.animations) {
  24487. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24488. var parsedAnimation = parsedMesh.animations[animationIndex];
  24489. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24490. }
  24491. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24492. }
  24493. if (parsedMesh.autoAnimate) {
  24494. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24495. }
  24496. // Layer Mask
  24497. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24498. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24499. }
  24500. else {
  24501. mesh.layerMask = 0x0FFFFFFF;
  24502. }
  24503. // Physics
  24504. if (parsedMesh.physicsImpostor) {
  24505. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24506. mass: parsedMesh.physicsMass,
  24507. friction: parsedMesh.physicsFriction,
  24508. restitution: parsedMesh.physicsRestitution
  24509. }, scene);
  24510. }
  24511. // Instances
  24512. if (parsedMesh.instances) {
  24513. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24514. var parsedInstance = parsedMesh.instances[index];
  24515. var instance = mesh.createInstance(parsedInstance.name);
  24516. if (BABYLON.Tags) {
  24517. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24518. }
  24519. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24520. if (parsedInstance.parentId) {
  24521. instance._waitingParentId = parsedInstance.parentId;
  24522. }
  24523. if (parsedInstance.rotationQuaternion) {
  24524. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24525. }
  24526. else if (parsedInstance.rotation) {
  24527. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24528. }
  24529. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24530. instance.checkCollisions = mesh.checkCollisions;
  24531. if (parsedMesh.animations) {
  24532. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24533. parsedAnimation = parsedMesh.animations[animationIndex];
  24534. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24535. }
  24536. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24537. }
  24538. }
  24539. }
  24540. return mesh;
  24541. };
  24542. /**
  24543. * Creates a ribbon mesh.
  24544. * Please consider using the same method from the MeshBuilder class instead.
  24545. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  24546. *
  24547. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24548. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24549. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24550. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24551. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  24552. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  24553. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  24554. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24555. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24557. */
  24558. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24559. if (closeArray === void 0) { closeArray = false; }
  24560. if (updatable === void 0) { updatable = false; }
  24561. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24562. pathArray: pathArray,
  24563. closeArray: closeArray,
  24564. closePath: closePath,
  24565. offset: offset,
  24566. updatable: updatable,
  24567. sideOrientation: sideOrientation,
  24568. instance: instance
  24569. }, scene);
  24570. };
  24571. /**
  24572. * Creates a plane polygonal mesh. By default, this is a disc.
  24573. * Please consider using the same method from the MeshBuilder class instead.
  24574. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24575. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  24576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24579. */
  24580. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24581. if (scene === void 0) { scene = null; }
  24582. var options = {
  24583. radius: radius,
  24584. tessellation: tessellation,
  24585. sideOrientation: sideOrientation,
  24586. updatable: updatable
  24587. };
  24588. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24589. };
  24590. /**
  24591. * Creates a box mesh.
  24592. * Please consider using the same method from the MeshBuilder class instead.
  24593. * The parameter `size` sets the size (float) of each box side (default 1).
  24594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24595. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24597. */
  24598. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24599. if (scene === void 0) { scene = null; }
  24600. var options = {
  24601. size: size,
  24602. sideOrientation: sideOrientation,
  24603. updatable: updatable
  24604. };
  24605. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24606. };
  24607. /**
  24608. * Creates a sphere mesh.
  24609. * Please consider using the same method from the MeshBuilder class instead.
  24610. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24611. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24612. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24613. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24615. */
  24616. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24617. var options = {
  24618. segments: segments,
  24619. diameterX: diameter,
  24620. diameterY: diameter,
  24621. diameterZ: diameter,
  24622. sideOrientation: sideOrientation,
  24623. updatable: updatable
  24624. };
  24625. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24626. };
  24627. /**
  24628. * Creates a cylinder or a cone mesh.
  24629. * Please consider using the same method from the MeshBuilder class instead.
  24630. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24631. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24632. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  24633. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24634. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24635. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24636. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24638. */
  24639. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24640. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24641. if (scene !== undefined) {
  24642. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24643. updatable = scene;
  24644. }
  24645. scene = subdivisions;
  24646. subdivisions = 1;
  24647. }
  24648. var options = {
  24649. height: height,
  24650. diameterTop: diameterTop,
  24651. diameterBottom: diameterBottom,
  24652. tessellation: tessellation,
  24653. subdivisions: subdivisions,
  24654. sideOrientation: sideOrientation,
  24655. updatable: updatable
  24656. };
  24657. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24658. };
  24659. // Torus (Code from SharpDX.org)
  24660. /**
  24661. * Creates a torus mesh.
  24662. * Please consider using the same method from the MeshBuilder class instead.
  24663. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24664. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24665. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24666. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24667. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24669. */
  24670. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24671. var options = {
  24672. diameter: diameter,
  24673. thickness: thickness,
  24674. tessellation: tessellation,
  24675. sideOrientation: sideOrientation,
  24676. updatable: updatable
  24677. };
  24678. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24679. };
  24680. /**
  24681. * Creates a torus knot mesh.
  24682. * Please consider using the same method from the MeshBuilder class instead.
  24683. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24684. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24685. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24686. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24687. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24688. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24690. */
  24691. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24692. var options = {
  24693. radius: radius,
  24694. tube: tube,
  24695. radialSegments: radialSegments,
  24696. tubularSegments: tubularSegments,
  24697. p: p,
  24698. q: q,
  24699. sideOrientation: sideOrientation,
  24700. updatable: updatable
  24701. };
  24702. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24703. };
  24704. /**
  24705. * Creates a line mesh.
  24706. * Please consider using the same method from the MeshBuilder class instead.
  24707. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  24708. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24709. * The parameter `points` is an array successive Vector3.
  24710. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  24711. * When updating an instance, remember that only point positions can change, not the number of points.
  24712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24713. */
  24714. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24715. if (scene === void 0) { scene = null; }
  24716. if (updatable === void 0) { updatable = false; }
  24717. if (instance === void 0) { instance = null; }
  24718. var options = {
  24719. points: points,
  24720. updatable: updatable,
  24721. instance: instance
  24722. };
  24723. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24724. };
  24725. /**
  24726. * Creates a dashed line mesh.
  24727. * Please consider using the same method from the MeshBuilder class instead.
  24728. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  24729. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24730. * The parameter `points` is an array successive Vector3.
  24731. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24732. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24733. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24734. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  24735. * When updating an instance, remember that only point positions can change, not the number of points.
  24736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24737. */
  24738. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24739. if (scene === void 0) { scene = null; }
  24740. var options = {
  24741. points: points,
  24742. dashSize: dashSize,
  24743. gapSize: gapSize,
  24744. dashNb: dashNb,
  24745. updatable: updatable,
  24746. instance: instance
  24747. };
  24748. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24749. };
  24750. /**
  24751. * Creates a polygon mesh.
  24752. * Please consider using the same method from the MeshBuilder class instead.
  24753. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24754. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  24755. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24757. * Remember you can only change the shape positions, not their number when updating a polygon.
  24758. */
  24759. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24760. var options = {
  24761. shape: shape,
  24762. holes: holes,
  24763. updatable: updatable,
  24764. sideOrientation: sideOrientation
  24765. };
  24766. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24767. };
  24768. /**
  24769. * Creates an extruded polygon mesh, with depth in the Y direction.
  24770. * Please consider using the same method from the MeshBuilder class instead.
  24771. */
  24772. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24773. var options = {
  24774. shape: shape,
  24775. holes: holes,
  24776. depth: depth,
  24777. updatable: updatable,
  24778. sideOrientation: sideOrientation
  24779. };
  24780. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24781. };
  24782. /**
  24783. * Creates an extruded shape mesh.
  24784. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  24785. * Please consider using the same method from the MeshBuilder class instead.
  24786. *
  24787. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24788. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  24789. * extruded along the Z axis.
  24790. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24791. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  24792. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24793. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  24794. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  24795. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24799. */
  24800. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24801. if (scene === void 0) { scene = null; }
  24802. var options = {
  24803. shape: shape,
  24804. path: path,
  24805. scale: scale,
  24806. rotation: rotation,
  24807. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24808. sideOrientation: sideOrientation,
  24809. instance: instance,
  24810. updatable: updatable
  24811. };
  24812. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24813. };
  24814. /**
  24815. * Creates an custom extruded shape mesh.
  24816. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  24817. * Please consider using the same method from the MeshBuilder class instead.
  24818. *
  24819. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24820. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  24821. * extruded along the Z axis.
  24822. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24823. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  24824. * and the distance of this point from the begining of the path :
  24825. * ```javascript
  24826. * var rotationFunction = function(i, distance) {
  24827. * // do things
  24828. * return rotationValue; }
  24829. * ```
  24830. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24831. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  24832. * and the distance of this point from the begining of the path :
  24833. * ```javascript
  24834. * var scaleFunction = function(i, distance) {
  24835. * // do things
  24836. * return scaleValue;}
  24837. * ```
  24838. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24839. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24840. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24841. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  24842. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  24843. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24844. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24845. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24847. */
  24848. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24849. var options = {
  24850. shape: shape,
  24851. path: path,
  24852. scaleFunction: scaleFunction,
  24853. rotationFunction: rotationFunction,
  24854. ribbonCloseArray: ribbonCloseArray,
  24855. ribbonClosePath: ribbonClosePath,
  24856. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24857. sideOrientation: sideOrientation,
  24858. instance: instance,
  24859. updatable: updatable
  24860. };
  24861. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24862. };
  24863. /**
  24864. * Creates lathe mesh.
  24865. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24866. * Please consider using the same method from the MeshBuilder class instead.
  24867. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  24868. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24869. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24870. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24872. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24874. */
  24875. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24876. var options = {
  24877. shape: shape,
  24878. radius: radius,
  24879. tessellation: tessellation,
  24880. sideOrientation: sideOrientation,
  24881. updatable: updatable
  24882. };
  24883. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24884. };
  24885. /**
  24886. * Creates a plane mesh.
  24887. * Please consider using the same method from the MeshBuilder class instead.
  24888. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24889. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24890. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24891. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24892. */
  24893. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24894. var options = {
  24895. size: size,
  24896. width: size,
  24897. height: size,
  24898. sideOrientation: sideOrientation,
  24899. updatable: updatable
  24900. };
  24901. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24902. };
  24903. /**
  24904. * Creates a ground mesh.
  24905. * Please consider using the same method from the MeshBuilder class instead.
  24906. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24907. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24908. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24909. */
  24910. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24911. var options = {
  24912. width: width,
  24913. height: height,
  24914. subdivisions: subdivisions,
  24915. updatable: updatable
  24916. };
  24917. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24918. };
  24919. /**
  24920. * Creates a tiled ground mesh.
  24921. * Please consider using the same method from the MeshBuilder class instead.
  24922. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24923. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24924. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24925. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24926. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24927. * numbers of subdivisions on the ground width and height of each tile.
  24928. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24929. */
  24930. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24931. var options = {
  24932. xmin: xmin,
  24933. zmin: zmin,
  24934. xmax: xmax,
  24935. zmax: zmax,
  24936. subdivisions: subdivisions,
  24937. precision: precision,
  24938. updatable: updatable
  24939. };
  24940. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24941. };
  24942. /**
  24943. * Creates a ground mesh from a height map.
  24944. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24945. * Please consider using the same method from the MeshBuilder class instead.
  24946. * The parameter `url` sets the URL of the height map image resource.
  24947. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24948. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24949. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24950. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24951. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  24952. * This function is passed the newly built mesh :
  24953. * ```javascript
  24954. * function(mesh) { // do things
  24955. * return; }
  24956. * ```
  24957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24958. */
  24959. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24960. var options = {
  24961. width: width,
  24962. height: height,
  24963. subdivisions: subdivisions,
  24964. minHeight: minHeight,
  24965. maxHeight: maxHeight,
  24966. updatable: updatable,
  24967. onReady: onReady
  24968. };
  24969. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24970. };
  24971. /**
  24972. * Creates a tube mesh.
  24973. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  24974. * Please consider using the same method from the MeshBuilder class instead.
  24975. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24976. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24977. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24978. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24979. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  24980. * It must return a radius value (positive float) :
  24981. * ```javascript
  24982. * var radiusFunction = function(i, distance) {
  24983. * // do things
  24984. * return radius; }
  24985. * ```
  24986. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  24987. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  24988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24991. */
  24992. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24993. var options = {
  24994. path: path,
  24995. radius: radius,
  24996. tessellation: tessellation,
  24997. radiusFunction: radiusFunction,
  24998. arc: 1,
  24999. cap: cap,
  25000. updatable: updatable,
  25001. sideOrientation: sideOrientation,
  25002. instance: instance
  25003. };
  25004. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25005. };
  25006. /**
  25007. * Creates a polyhedron mesh.
  25008. * Please consider using the same method from the MeshBuilder class instead.
  25009. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  25010. * to choose the wanted type.
  25011. * The parameter `size` (positive float, default 1) sets the polygon size.
  25012. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25013. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  25014. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  25015. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  25016. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  25017. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  25018. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25019. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25021. */
  25022. Mesh.CreatePolyhedron = function (name, options, scene) {
  25023. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25024. };
  25025. /**
  25026. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25027. * Please consider using the same method from the MeshBuilder class instead.
  25028. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25029. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  25030. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25031. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  25032. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25033. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25035. */
  25036. Mesh.CreateIcoSphere = function (name, options, scene) {
  25037. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25038. };
  25039. /**
  25040. * Creates a decal mesh.
  25041. * Please consider using the same method from the MeshBuilder class instead.
  25042. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  25043. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25044. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25045. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25046. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25047. */
  25048. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25049. var options = {
  25050. position: position,
  25051. normal: normal,
  25052. size: size,
  25053. angle: angle
  25054. };
  25055. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25056. };
  25057. // Skeletons
  25058. /**
  25059. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25060. */
  25061. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25062. if (!this._sourcePositions) {
  25063. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25064. if (!source) {
  25065. return this._sourcePositions;
  25066. }
  25067. this._sourcePositions = new Float32Array(source);
  25068. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25069. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25070. }
  25071. }
  25072. return this._sourcePositions;
  25073. };
  25074. /**
  25075. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25076. */
  25077. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25078. if (!this._sourceNormals) {
  25079. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25080. if (!source) {
  25081. return this._sourceNormals;
  25082. }
  25083. this._sourceNormals = new Float32Array(source);
  25084. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25085. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25086. }
  25087. }
  25088. return this._sourceNormals;
  25089. };
  25090. /**
  25091. * Updates the vertex buffer by applying transformation from the bones.
  25092. * Returns the Mesh.
  25093. *
  25094. * @param {skeleton} skeleton to apply
  25095. */
  25096. Mesh.prototype.applySkeleton = function (skeleton) {
  25097. if (!this.geometry) {
  25098. return this;
  25099. }
  25100. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25101. return this;
  25102. }
  25103. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25104. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25105. return this;
  25106. }
  25107. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25108. return this;
  25109. }
  25110. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25111. return this;
  25112. }
  25113. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25114. return this;
  25115. }
  25116. if (!this._sourcePositions) {
  25117. var submeshes = this.subMeshes.slice();
  25118. this.setPositionsForCPUSkinning();
  25119. this.subMeshes = submeshes;
  25120. }
  25121. if (!this._sourceNormals) {
  25122. this.setNormalsForCPUSkinning();
  25123. }
  25124. // positionsData checks for not being Float32Array will only pass at most once
  25125. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25126. if (!positionsData) {
  25127. return this;
  25128. }
  25129. if (!(positionsData instanceof Float32Array)) {
  25130. positionsData = new Float32Array(positionsData);
  25131. }
  25132. // normalsData checks for not being Float32Array will only pass at most once
  25133. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25134. if (!normalsData) {
  25135. return this;
  25136. }
  25137. if (!(normalsData instanceof Float32Array)) {
  25138. normalsData = new Float32Array(normalsData);
  25139. }
  25140. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25141. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25142. if (!matricesWeightsData || !matricesIndicesData) {
  25143. return this;
  25144. }
  25145. var needExtras = this.numBoneInfluencers > 4;
  25146. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25147. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25148. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25149. return this;
  25150. }
  25151. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25152. var tempVector3 = BABYLON.Vector3.Zero();
  25153. var finalMatrix = new BABYLON.Matrix();
  25154. var tempMatrix = new BABYLON.Matrix();
  25155. var matWeightIdx = 0;
  25156. var inf;
  25157. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25158. var weight;
  25159. for (inf = 0; inf < 4; inf++) {
  25160. weight = matricesWeightsData[matWeightIdx + inf];
  25161. if (weight > 0) {
  25162. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25163. finalMatrix.addToSelf(tempMatrix);
  25164. }
  25165. else
  25166. break;
  25167. }
  25168. if (needExtras) {
  25169. for (inf = 0; inf < 4; inf++) {
  25170. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25171. if (weight > 0) {
  25172. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25173. finalMatrix.addToSelf(tempMatrix);
  25174. }
  25175. else
  25176. break;
  25177. }
  25178. }
  25179. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25180. tempVector3.toArray(positionsData, index);
  25181. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25182. tempVector3.toArray(normalsData, index);
  25183. finalMatrix.reset();
  25184. }
  25185. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25186. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25187. return this;
  25188. };
  25189. // Tools
  25190. /**
  25191. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25192. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25193. */
  25194. Mesh.MinMax = function (meshes) {
  25195. var minVector = null;
  25196. var maxVector = null;
  25197. meshes.forEach(function (mesh, index, array) {
  25198. var boundingInfo = mesh.getBoundingInfo();
  25199. if (!boundingInfo) {
  25200. return;
  25201. }
  25202. var boundingBox = boundingInfo.boundingBox;
  25203. if (!minVector || !maxVector) {
  25204. minVector = boundingBox.minimumWorld;
  25205. maxVector = boundingBox.maximumWorld;
  25206. }
  25207. else {
  25208. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25209. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25210. }
  25211. });
  25212. if (!minVector || !maxVector) {
  25213. return {
  25214. min: BABYLON.Vector3.Zero(),
  25215. max: BABYLON.Vector3.Zero()
  25216. };
  25217. }
  25218. return {
  25219. min: minVector,
  25220. max: maxVector
  25221. };
  25222. };
  25223. /**
  25224. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25225. */
  25226. Mesh.Center = function (meshesOrMinMaxVector) {
  25227. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25228. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25229. };
  25230. /**
  25231. * Merge the array of meshes into a single mesh for performance reasons.
  25232. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25233. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25234. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25235. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25236. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25237. */
  25238. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25239. if (disposeSource === void 0) { disposeSource = true; }
  25240. var index;
  25241. if (!allow32BitsIndices) {
  25242. var totalVertices = 0;
  25243. // Counting vertices
  25244. for (index = 0; index < meshes.length; index++) {
  25245. if (meshes[index]) {
  25246. totalVertices += meshes[index].getTotalVertices();
  25247. if (totalVertices > 65536) {
  25248. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25249. return null;
  25250. }
  25251. }
  25252. }
  25253. }
  25254. // Merge
  25255. var vertexData = null;
  25256. var otherVertexData;
  25257. var indiceArray = new Array();
  25258. var source = null;
  25259. for (index = 0; index < meshes.length; index++) {
  25260. if (meshes[index]) {
  25261. meshes[index].computeWorldMatrix(true);
  25262. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25263. otherVertexData.transform(meshes[index].getWorldMatrix());
  25264. if (vertexData) {
  25265. vertexData.merge(otherVertexData);
  25266. }
  25267. else {
  25268. vertexData = otherVertexData;
  25269. source = meshes[index];
  25270. }
  25271. if (subdivideWithSubMeshes) {
  25272. indiceArray.push(meshes[index].getTotalIndices());
  25273. }
  25274. }
  25275. }
  25276. source = source;
  25277. if (!meshSubclass) {
  25278. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25279. }
  25280. vertexData.applyToMesh(meshSubclass);
  25281. // Setting properties
  25282. meshSubclass.material = source.material;
  25283. meshSubclass.checkCollisions = source.checkCollisions;
  25284. // Cleaning
  25285. if (disposeSource) {
  25286. for (index = 0; index < meshes.length; index++) {
  25287. if (meshes[index]) {
  25288. meshes[index].dispose();
  25289. }
  25290. }
  25291. }
  25292. // Subdivide
  25293. if (subdivideWithSubMeshes) {
  25294. //-- Suppresions du submesh global
  25295. meshSubclass.releaseSubMeshes();
  25296. index = 0;
  25297. var offset = 0;
  25298. //-- aplique la subdivision en fonction du tableau d'indices
  25299. while (index < indiceArray.length) {
  25300. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25301. offset += indiceArray[index];
  25302. index++;
  25303. }
  25304. }
  25305. return meshSubclass;
  25306. };
  25307. // Consts
  25308. Mesh._FRONTSIDE = 0;
  25309. Mesh._BACKSIDE = 1;
  25310. Mesh._DOUBLESIDE = 2;
  25311. Mesh._DEFAULTSIDE = 0;
  25312. Mesh._NO_CAP = 0;
  25313. Mesh._CAP_START = 1;
  25314. Mesh._CAP_END = 2;
  25315. Mesh._CAP_ALL = 3;
  25316. return Mesh;
  25317. }(BABYLON.AbstractMesh));
  25318. BABYLON.Mesh = Mesh;
  25319. })(BABYLON || (BABYLON = {}));
  25320. //# sourceMappingURL=babylon.mesh.js.map
  25321. var BABYLON;
  25322. (function (BABYLON) {
  25323. var BaseSubMesh = /** @class */ (function () {
  25324. function BaseSubMesh() {
  25325. }
  25326. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25327. get: function () {
  25328. return this._materialEffect;
  25329. },
  25330. enumerable: true,
  25331. configurable: true
  25332. });
  25333. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25334. if (defines === void 0) { defines = null; }
  25335. if (this._materialEffect === effect) {
  25336. if (!effect) {
  25337. this._materialDefines = null;
  25338. }
  25339. return;
  25340. }
  25341. this._materialDefines = defines;
  25342. this._materialEffect = effect;
  25343. };
  25344. return BaseSubMesh;
  25345. }());
  25346. BABYLON.BaseSubMesh = BaseSubMesh;
  25347. var SubMesh = /** @class */ (function (_super) {
  25348. __extends(SubMesh, _super);
  25349. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25350. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25351. var _this = _super.call(this) || this;
  25352. _this.materialIndex = materialIndex;
  25353. _this.verticesStart = verticesStart;
  25354. _this.verticesCount = verticesCount;
  25355. _this.indexStart = indexStart;
  25356. _this.indexCount = indexCount;
  25357. _this._renderId = 0;
  25358. _this._mesh = mesh;
  25359. _this._renderingMesh = renderingMesh || mesh;
  25360. mesh.subMeshes.push(_this);
  25361. _this._trianglePlanes = [];
  25362. _this._id = mesh.subMeshes.length - 1;
  25363. if (createBoundingBox) {
  25364. _this.refreshBoundingInfo();
  25365. mesh.computeWorldMatrix(true);
  25366. }
  25367. return _this;
  25368. }
  25369. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25370. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25371. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25372. };
  25373. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25374. get: function () {
  25375. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25376. },
  25377. enumerable: true,
  25378. configurable: true
  25379. });
  25380. /**
  25381. * Returns the submesh BoudingInfo object.
  25382. */
  25383. SubMesh.prototype.getBoundingInfo = function () {
  25384. if (this.IsGlobal) {
  25385. return this._mesh.getBoundingInfo();
  25386. }
  25387. return this._boundingInfo;
  25388. };
  25389. /**
  25390. * Sets the submesh BoundingInfo.
  25391. * Return the SubMesh.
  25392. */
  25393. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25394. this._boundingInfo = boundingInfo;
  25395. return this;
  25396. };
  25397. /**
  25398. * Returns the mesh of the current submesh.
  25399. */
  25400. SubMesh.prototype.getMesh = function () {
  25401. return this._mesh;
  25402. };
  25403. /**
  25404. * Returns the rendering mesh of the submesh.
  25405. */
  25406. SubMesh.prototype.getRenderingMesh = function () {
  25407. return this._renderingMesh;
  25408. };
  25409. /**
  25410. * Returns the submesh material.
  25411. */
  25412. SubMesh.prototype.getMaterial = function () {
  25413. var rootMaterial = this._renderingMesh.material;
  25414. if (rootMaterial && rootMaterial.getSubMaterial) {
  25415. var multiMaterial = rootMaterial;
  25416. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25417. if (this._currentMaterial !== effectiveMaterial) {
  25418. this._currentMaterial = effectiveMaterial;
  25419. this._materialDefines = null;
  25420. }
  25421. return effectiveMaterial;
  25422. }
  25423. if (!rootMaterial) {
  25424. return this._mesh.getScene().defaultMaterial;
  25425. }
  25426. return rootMaterial;
  25427. };
  25428. // Methods
  25429. /**
  25430. * Sets a new updated BoundingInfo object to the submesh.
  25431. * Returns the SubMesh.
  25432. */
  25433. SubMesh.prototype.refreshBoundingInfo = function () {
  25434. this._lastColliderWorldVertices = null;
  25435. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25436. return this;
  25437. }
  25438. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25439. if (!data) {
  25440. this._boundingInfo = this._mesh._boundingInfo;
  25441. return this;
  25442. }
  25443. var indices = this._renderingMesh.getIndices();
  25444. var extend;
  25445. //is this the only submesh?
  25446. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25447. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25448. if (!boundingInfo) {
  25449. return this;
  25450. }
  25451. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25452. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25453. }
  25454. else {
  25455. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25456. }
  25457. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25458. return this;
  25459. };
  25460. SubMesh.prototype._checkCollision = function (collider) {
  25461. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25462. if (!boundingInfo) {
  25463. return false;
  25464. }
  25465. return boundingInfo._checkCollision(collider);
  25466. };
  25467. /**
  25468. * Updates the submesh BoundingInfo.
  25469. * Returns the Submesh.
  25470. */
  25471. SubMesh.prototype.updateBoundingInfo = function (world) {
  25472. var boundingInfo = this.getBoundingInfo();
  25473. if (!boundingInfo) {
  25474. this.refreshBoundingInfo();
  25475. boundingInfo = this.getBoundingInfo();
  25476. }
  25477. boundingInfo.update(world);
  25478. return this;
  25479. };
  25480. /**
  25481. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25482. * Boolean returned.
  25483. */
  25484. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25485. var boundingInfo = this.getBoundingInfo();
  25486. if (!boundingInfo) {
  25487. return false;
  25488. }
  25489. return boundingInfo.isInFrustum(frustumPlanes);
  25490. };
  25491. /**
  25492. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25493. * Boolean returned.
  25494. */
  25495. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25496. var boundingInfo = this.getBoundingInfo();
  25497. if (!boundingInfo) {
  25498. return false;
  25499. }
  25500. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25501. };
  25502. /**
  25503. * Renders the submesh.
  25504. * Returns it.
  25505. */
  25506. SubMesh.prototype.render = function (enableAlphaMode) {
  25507. this._renderingMesh.render(this, enableAlphaMode);
  25508. return this;
  25509. };
  25510. /**
  25511. * Returns a new Index Buffer.
  25512. * Type returned : WebGLBuffer.
  25513. */
  25514. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25515. if (!this._linesIndexBuffer) {
  25516. var linesIndices = [];
  25517. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25518. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25519. }
  25520. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25521. this.linesIndexCount = linesIndices.length;
  25522. }
  25523. return this._linesIndexBuffer;
  25524. };
  25525. /**
  25526. * True is the passed Ray intersects the submesh bounding box.
  25527. * Boolean returned.
  25528. */
  25529. SubMesh.prototype.canIntersects = function (ray) {
  25530. var boundingInfo = this.getBoundingInfo();
  25531. if (!boundingInfo) {
  25532. return false;
  25533. }
  25534. return ray.intersectsBox(boundingInfo.boundingBox);
  25535. };
  25536. /**
  25537. * Returns an object IntersectionInfo.
  25538. */
  25539. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25540. var intersectInfo = null;
  25541. // LineMesh first as it's also a Mesh...
  25542. if (this._mesh instanceof BABYLON.LinesMesh) {
  25543. var lineMesh = this._mesh;
  25544. // Line test
  25545. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25546. var p0 = positions[indices[index]];
  25547. var p1 = positions[indices[index + 1]];
  25548. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25549. if (length < 0) {
  25550. continue;
  25551. }
  25552. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25553. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25554. if (fastCheck) {
  25555. break;
  25556. }
  25557. }
  25558. }
  25559. }
  25560. else {
  25561. // Triangles test
  25562. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25563. var p0 = positions[indices[index]];
  25564. var p1 = positions[indices[index + 1]];
  25565. var p2 = positions[indices[index + 2]];
  25566. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25567. if (currentIntersectInfo) {
  25568. if (currentIntersectInfo.distance < 0) {
  25569. continue;
  25570. }
  25571. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25572. intersectInfo = currentIntersectInfo;
  25573. intersectInfo.faceId = index / 3;
  25574. if (fastCheck) {
  25575. break;
  25576. }
  25577. }
  25578. }
  25579. }
  25580. }
  25581. return intersectInfo;
  25582. };
  25583. SubMesh.prototype._rebuild = function () {
  25584. if (this._linesIndexBuffer) {
  25585. this._linesIndexBuffer = null;
  25586. }
  25587. };
  25588. // Clone
  25589. /**
  25590. * Creates a new Submesh from the passed Mesh.
  25591. */
  25592. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25593. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25594. if (!this.IsGlobal) {
  25595. var boundingInfo = this.getBoundingInfo();
  25596. if (!boundingInfo) {
  25597. return result;
  25598. }
  25599. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25600. }
  25601. return result;
  25602. };
  25603. // Dispose
  25604. /**
  25605. * Disposes the Submesh.
  25606. * Returns nothing.
  25607. */
  25608. SubMesh.prototype.dispose = function () {
  25609. if (this._linesIndexBuffer) {
  25610. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25611. this._linesIndexBuffer = null;
  25612. }
  25613. // Remove from mesh
  25614. var index = this._mesh.subMeshes.indexOf(this);
  25615. this._mesh.subMeshes.splice(index, 1);
  25616. };
  25617. // Statics
  25618. /**
  25619. * Creates a new Submesh from the passed parameters :
  25620. * - materialIndex (integer) : the index of the main mesh material.
  25621. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25622. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25623. * - mesh (Mesh) : the main mesh to create the submesh from.
  25624. * - renderingMesh (optional Mesh) : rendering mesh.
  25625. */
  25626. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25627. var minVertexIndex = Number.MAX_VALUE;
  25628. var maxVertexIndex = -Number.MAX_VALUE;
  25629. renderingMesh = (renderingMesh || mesh);
  25630. var indices = renderingMesh.getIndices();
  25631. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25632. var vertexIndex = indices[index];
  25633. if (vertexIndex < minVertexIndex)
  25634. minVertexIndex = vertexIndex;
  25635. if (vertexIndex > maxVertexIndex)
  25636. maxVertexIndex = vertexIndex;
  25637. }
  25638. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25639. };
  25640. return SubMesh;
  25641. }(BaseSubMesh));
  25642. BABYLON.SubMesh = SubMesh;
  25643. })(BABYLON || (BABYLON = {}));
  25644. //# sourceMappingURL=babylon.subMesh.js.map
  25645. var BABYLON;
  25646. (function (BABYLON) {
  25647. var EffectFallbacks = /** @class */ (function () {
  25648. function EffectFallbacks() {
  25649. this._defines = {};
  25650. this._currentRank = 32;
  25651. this._maxRank = -1;
  25652. }
  25653. EffectFallbacks.prototype.unBindMesh = function () {
  25654. this._mesh = null;
  25655. };
  25656. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25657. if (!this._defines[rank]) {
  25658. if (rank < this._currentRank) {
  25659. this._currentRank = rank;
  25660. }
  25661. if (rank > this._maxRank) {
  25662. this._maxRank = rank;
  25663. }
  25664. this._defines[rank] = new Array();
  25665. }
  25666. this._defines[rank].push(define);
  25667. };
  25668. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25669. this._meshRank = rank;
  25670. this._mesh = mesh;
  25671. if (rank < this._currentRank) {
  25672. this._currentRank = rank;
  25673. }
  25674. if (rank > this._maxRank) {
  25675. this._maxRank = rank;
  25676. }
  25677. };
  25678. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25679. get: function () {
  25680. return this._currentRank <= this._maxRank;
  25681. },
  25682. enumerable: true,
  25683. configurable: true
  25684. });
  25685. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25686. // First we try to switch to CPU skinning
  25687. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25688. this._mesh.computeBonesUsingShaders = false;
  25689. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25690. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25691. var scene = this._mesh.getScene();
  25692. for (var index = 0; index < scene.meshes.length; index++) {
  25693. var otherMesh = scene.meshes[index];
  25694. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25695. otherMesh.computeBonesUsingShaders = false;
  25696. }
  25697. }
  25698. }
  25699. else {
  25700. var currentFallbacks = this._defines[this._currentRank];
  25701. if (currentFallbacks) {
  25702. for (var index = 0; index < currentFallbacks.length; index++) {
  25703. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25704. }
  25705. }
  25706. this._currentRank++;
  25707. }
  25708. return currentDefines;
  25709. };
  25710. return EffectFallbacks;
  25711. }());
  25712. BABYLON.EffectFallbacks = EffectFallbacks;
  25713. var EffectCreationOptions = /** @class */ (function () {
  25714. function EffectCreationOptions() {
  25715. }
  25716. return EffectCreationOptions;
  25717. }());
  25718. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25719. var Effect = /** @class */ (function () {
  25720. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25721. if (samplers === void 0) { samplers = null; }
  25722. if (defines === void 0) { defines = null; }
  25723. if (fallbacks === void 0) { fallbacks = null; }
  25724. if (onCompiled === void 0) { onCompiled = null; }
  25725. if (onError === void 0) { onError = null; }
  25726. var _this = this;
  25727. this.uniqueId = 0;
  25728. this.onCompileObservable = new BABYLON.Observable();
  25729. this.onErrorObservable = new BABYLON.Observable();
  25730. this.onBindObservable = new BABYLON.Observable();
  25731. this._uniformBuffersNames = {};
  25732. this._isReady = false;
  25733. this._compilationError = "";
  25734. this.name = baseName;
  25735. if (attributesNamesOrOptions.attributes) {
  25736. var options = attributesNamesOrOptions;
  25737. this._engine = uniformsNamesOrEngine;
  25738. this._attributesNames = options.attributes;
  25739. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25740. this._samplers = options.samplers;
  25741. this.defines = options.defines;
  25742. this.onError = options.onError;
  25743. this.onCompiled = options.onCompiled;
  25744. this._fallbacks = options.fallbacks;
  25745. this._indexParameters = options.indexParameters;
  25746. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  25747. if (options.uniformBuffersNames) {
  25748. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25749. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25750. }
  25751. }
  25752. }
  25753. else {
  25754. this._engine = engine;
  25755. this.defines = defines;
  25756. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25757. this._samplers = samplers;
  25758. this._attributesNames = attributesNamesOrOptions;
  25759. this.onError = onError;
  25760. this.onCompiled = onCompiled;
  25761. this._indexParameters = indexParameters;
  25762. this._fallbacks = fallbacks;
  25763. }
  25764. this.uniqueId = Effect._uniqueIdSeed++;
  25765. var vertexSource;
  25766. var fragmentSource;
  25767. if (baseName.vertexElement) {
  25768. vertexSource = document.getElementById(baseName.vertexElement);
  25769. if (!vertexSource) {
  25770. vertexSource = baseName.vertexElement;
  25771. }
  25772. }
  25773. else {
  25774. vertexSource = baseName.vertex || baseName;
  25775. }
  25776. if (baseName.fragmentElement) {
  25777. fragmentSource = document.getElementById(baseName.fragmentElement);
  25778. if (!fragmentSource) {
  25779. fragmentSource = baseName.fragmentElement;
  25780. }
  25781. }
  25782. else {
  25783. fragmentSource = baseName.fragment || baseName;
  25784. }
  25785. this._loadVertexShader(vertexSource, function (vertexCode) {
  25786. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25787. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25788. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25789. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25790. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25791. if (baseName) {
  25792. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25793. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25794. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25795. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25796. }
  25797. else {
  25798. _this._vertexSourceCode = migratedVertexCode;
  25799. _this._fragmentSourceCode = migratedFragmentCode;
  25800. }
  25801. _this._prepareEffect();
  25802. });
  25803. });
  25804. });
  25805. });
  25806. });
  25807. });
  25808. }
  25809. Object.defineProperty(Effect.prototype, "key", {
  25810. get: function () {
  25811. return this._key;
  25812. },
  25813. enumerable: true,
  25814. configurable: true
  25815. });
  25816. // Properties
  25817. Effect.prototype.isReady = function () {
  25818. return this._isReady;
  25819. };
  25820. Effect.prototype.getEngine = function () {
  25821. return this._engine;
  25822. };
  25823. Effect.prototype.getProgram = function () {
  25824. return this._program;
  25825. };
  25826. Effect.prototype.getAttributesNames = function () {
  25827. return this._attributesNames;
  25828. };
  25829. Effect.prototype.getAttributeLocation = function (index) {
  25830. return this._attributes[index];
  25831. };
  25832. Effect.prototype.getAttributeLocationByName = function (name) {
  25833. var index = this._attributesNames.indexOf(name);
  25834. return this._attributes[index];
  25835. };
  25836. Effect.prototype.getAttributesCount = function () {
  25837. return this._attributes.length;
  25838. };
  25839. Effect.prototype.getUniformIndex = function (uniformName) {
  25840. return this._uniformsNames.indexOf(uniformName);
  25841. };
  25842. Effect.prototype.getUniform = function (uniformName) {
  25843. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25844. };
  25845. Effect.prototype.getSamplers = function () {
  25846. return this._samplers;
  25847. };
  25848. Effect.prototype.getCompilationError = function () {
  25849. return this._compilationError;
  25850. };
  25851. // Methods
  25852. Effect.prototype.executeWhenCompiled = function (func) {
  25853. if (this.isReady()) {
  25854. func(this);
  25855. return;
  25856. }
  25857. this.onCompileObservable.add(function (effect) {
  25858. func(effect);
  25859. });
  25860. };
  25861. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25862. if (BABYLON.Tools.IsWindowObjectExist()) {
  25863. // DOM element ?
  25864. if (vertex instanceof HTMLElement) {
  25865. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25866. callback(vertexCode);
  25867. return;
  25868. }
  25869. }
  25870. // Base64 encoded ?
  25871. if (vertex.substr(0, 7) === "base64:") {
  25872. var vertexBinary = window.atob(vertex.substr(7));
  25873. callback(vertexBinary);
  25874. return;
  25875. }
  25876. // Is in local store ?
  25877. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25878. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25879. return;
  25880. }
  25881. var vertexShaderUrl;
  25882. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25883. vertexShaderUrl = vertex;
  25884. }
  25885. else {
  25886. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25887. }
  25888. // Vertex shader
  25889. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25890. };
  25891. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25892. if (BABYLON.Tools.IsWindowObjectExist()) {
  25893. // DOM element ?
  25894. if (fragment instanceof HTMLElement) {
  25895. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25896. callback(fragmentCode);
  25897. return;
  25898. }
  25899. }
  25900. // Base64 encoded ?
  25901. if (fragment.substr(0, 7) === "base64:") {
  25902. var fragmentBinary = window.atob(fragment.substr(7));
  25903. callback(fragmentBinary);
  25904. return;
  25905. }
  25906. // Is in local store ?
  25907. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25908. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25909. return;
  25910. }
  25911. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25912. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25913. return;
  25914. }
  25915. var fragmentShaderUrl;
  25916. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25917. fragmentShaderUrl = fragment;
  25918. }
  25919. else {
  25920. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25921. }
  25922. // Fragment shader
  25923. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25924. };
  25925. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25926. // Rebuild shaders source code
  25927. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25928. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25929. vertexCode = prefix + vertexCode;
  25930. fragmentCode = prefix + fragmentCode;
  25931. // Number lines of shaders source code
  25932. var i = 2;
  25933. var regex = /\n/gm;
  25934. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25935. i = 2;
  25936. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25937. // Dump shaders name and formatted source code
  25938. if (this.name.vertexElement) {
  25939. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25940. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25941. }
  25942. else if (this.name.vertex) {
  25943. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25944. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25945. }
  25946. else {
  25947. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25948. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25949. }
  25950. };
  25951. ;
  25952. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25953. var preparedSourceCode = this._processPrecision(sourceCode);
  25954. if (this._engine.webGLVersion == 1) {
  25955. callback(preparedSourceCode);
  25956. return;
  25957. }
  25958. // Already converted
  25959. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25960. callback(preparedSourceCode.replace("#version 300 es", ""));
  25961. return;
  25962. }
  25963. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25964. // Remove extensions
  25965. // #extension GL_OES_standard_derivatives : enable
  25966. // #extension GL_EXT_shader_texture_lod : enable
  25967. // #extension GL_EXT_frag_depth : enable
  25968. // #extension GL_EXT_draw_buffers : require
  25969. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25970. var result = preparedSourceCode.replace(regex, "");
  25971. // Migrate to GLSL v300
  25972. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25973. result = result.replace(/attribute[ \t]/g, "in ");
  25974. result = result.replace(/[ \t]attribute/g, " in");
  25975. if (isFragment) {
  25976. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25977. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25978. result = result.replace(/texture2D\s*\(/g, "texture(");
  25979. result = result.replace(/textureCube\s*\(/g, "texture(");
  25980. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25981. result = result.replace(/gl_FragColor/g, "glFragColor");
  25982. result = result.replace(/gl_FragData/g, "glFragData");
  25983. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25984. }
  25985. callback(result);
  25986. };
  25987. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25988. var _this = this;
  25989. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25990. var match = regex.exec(sourceCode);
  25991. var returnValue = new String(sourceCode);
  25992. while (match != null) {
  25993. var includeFile = match[1];
  25994. // Uniform declaration
  25995. if (includeFile.indexOf("__decl__") !== -1) {
  25996. includeFile = includeFile.replace(/__decl__/, "");
  25997. if (this._engine.supportsUniformBuffers) {
  25998. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25999. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26000. }
  26001. includeFile = includeFile + "Declaration";
  26002. }
  26003. if (Effect.IncludesShadersStore[includeFile]) {
  26004. // Substitution
  26005. var includeContent = Effect.IncludesShadersStore[includeFile];
  26006. if (match[2]) {
  26007. var splits = match[3].split(",");
  26008. for (var index = 0; index < splits.length; index += 2) {
  26009. var source = new RegExp(splits[index], "g");
  26010. var dest = splits[index + 1];
  26011. includeContent = includeContent.replace(source, dest);
  26012. }
  26013. }
  26014. if (match[4]) {
  26015. var indexString = match[5];
  26016. if (indexString.indexOf("..") !== -1) {
  26017. var indexSplits = indexString.split("..");
  26018. var minIndex = parseInt(indexSplits[0]);
  26019. var maxIndex = parseInt(indexSplits[1]);
  26020. var sourceIncludeContent = includeContent.slice(0);
  26021. includeContent = "";
  26022. if (isNaN(maxIndex)) {
  26023. maxIndex = this._indexParameters[indexSplits[1]];
  26024. }
  26025. for (var i = minIndex; i < maxIndex; i++) {
  26026. if (!this._engine.supportsUniformBuffers) {
  26027. // Ubo replacement
  26028. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26029. return p1 + "{X}";
  26030. });
  26031. }
  26032. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26033. }
  26034. }
  26035. else {
  26036. if (!this._engine.supportsUniformBuffers) {
  26037. // Ubo replacement
  26038. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26039. return p1 + "{X}";
  26040. });
  26041. }
  26042. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26043. }
  26044. }
  26045. // Replace
  26046. returnValue = returnValue.replace(match[0], includeContent);
  26047. }
  26048. else {
  26049. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26050. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26051. Effect.IncludesShadersStore[includeFile] = fileContent;
  26052. _this._processIncludes(returnValue, callback);
  26053. });
  26054. return;
  26055. }
  26056. match = regex.exec(sourceCode);
  26057. }
  26058. callback(returnValue);
  26059. };
  26060. Effect.prototype._processPrecision = function (source) {
  26061. if (source.indexOf("precision highp float") === -1) {
  26062. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26063. source = "precision mediump float;\n" + source;
  26064. }
  26065. else {
  26066. source = "precision highp float;\n" + source;
  26067. }
  26068. }
  26069. else {
  26070. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26071. source = source.replace("precision highp float", "precision mediump float");
  26072. }
  26073. }
  26074. return source;
  26075. };
  26076. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26077. var _this = this;
  26078. this._isReady = false;
  26079. this._vertexSourceCodeOverride = vertexSourceCode;
  26080. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26081. this.onError = function (effect, error) {
  26082. if (onError) {
  26083. onError(error);
  26084. }
  26085. };
  26086. this.onCompiled = function () {
  26087. var scenes = _this.getEngine().scenes;
  26088. for (var i = 0; i < scenes.length; i++) {
  26089. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26090. }
  26091. if (onCompiled) {
  26092. onCompiled(_this._program);
  26093. }
  26094. };
  26095. this._fallbacks = null;
  26096. this._prepareEffect();
  26097. };
  26098. Effect.prototype._prepareEffect = function () {
  26099. var attributesNames = this._attributesNames;
  26100. var defines = this.defines;
  26101. var fallbacks = this._fallbacks;
  26102. this._valueCache = {};
  26103. var previousProgram = this._program;
  26104. try {
  26105. var engine = this._engine;
  26106. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26107. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26108. }
  26109. else {
  26110. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26111. }
  26112. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26113. if (engine.webGLVersion > 1) {
  26114. for (var name in this._uniformBuffersNames) {
  26115. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26116. }
  26117. }
  26118. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26119. this._attributes = engine.getAttributes(this._program, attributesNames);
  26120. var index;
  26121. for (index = 0; index < this._samplers.length; index++) {
  26122. var sampler = this.getUniform(this._samplers[index]);
  26123. if (sampler == null) {
  26124. this._samplers.splice(index, 1);
  26125. index--;
  26126. }
  26127. }
  26128. engine.bindSamplers(this);
  26129. this._compilationError = "";
  26130. this._isReady = true;
  26131. if (this.onCompiled) {
  26132. this.onCompiled(this);
  26133. }
  26134. this.onCompileObservable.notifyObservers(this);
  26135. this.onCompileObservable.clear();
  26136. // Unbind mesh reference in fallbacks
  26137. if (this._fallbacks) {
  26138. this._fallbacks.unBindMesh();
  26139. }
  26140. if (previousProgram) {
  26141. this.getEngine()._deleteProgram(previousProgram);
  26142. }
  26143. }
  26144. catch (e) {
  26145. this._compilationError = e.message;
  26146. // Let's go through fallbacks then
  26147. BABYLON.Tools.Error("Unable to compile effect:");
  26148. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26149. return " " + uniform;
  26150. }));
  26151. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26152. return " " + attribute;
  26153. }));
  26154. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26155. BABYLON.Tools.Error("Error: " + this._compilationError);
  26156. if (previousProgram) {
  26157. this._program = previousProgram;
  26158. this._isReady = true;
  26159. if (this.onError) {
  26160. this.onError(this, this._compilationError);
  26161. }
  26162. this.onErrorObservable.notifyObservers(this);
  26163. }
  26164. if (fallbacks && fallbacks.isMoreFallbacks) {
  26165. BABYLON.Tools.Error("Trying next fallback.");
  26166. this.defines = fallbacks.reduce(this.defines);
  26167. this._prepareEffect();
  26168. }
  26169. else {
  26170. if (this.onError) {
  26171. this.onError(this, this._compilationError);
  26172. }
  26173. this.onErrorObservable.notifyObservers(this);
  26174. this.onErrorObservable.clear();
  26175. // Unbind mesh reference in fallbacks
  26176. if (this._fallbacks) {
  26177. this._fallbacks.unBindMesh();
  26178. }
  26179. }
  26180. }
  26181. };
  26182. Object.defineProperty(Effect.prototype, "isSupported", {
  26183. get: function () {
  26184. return this._compilationError === "";
  26185. },
  26186. enumerable: true,
  26187. configurable: true
  26188. });
  26189. Effect.prototype._bindTexture = function (channel, texture) {
  26190. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26191. };
  26192. Effect.prototype.setTexture = function (channel, texture) {
  26193. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26194. };
  26195. Effect.prototype.setTextureArray = function (channel, textures) {
  26196. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26197. var initialPos = this._samplers.indexOf(channel);
  26198. for (var index = 1; index < textures.length; index++) {
  26199. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26200. }
  26201. }
  26202. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26203. };
  26204. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26205. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26206. };
  26207. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26208. var cache = this._valueCache[uniformName];
  26209. var flag = matrix.updateFlag;
  26210. if (cache !== undefined && cache === flag) {
  26211. return false;
  26212. }
  26213. this._valueCache[uniformName] = flag;
  26214. return true;
  26215. };
  26216. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26217. var cache = this._valueCache[uniformName];
  26218. if (!cache) {
  26219. cache = [x, y];
  26220. this._valueCache[uniformName] = cache;
  26221. return true;
  26222. }
  26223. var changed = false;
  26224. if (cache[0] !== x) {
  26225. cache[0] = x;
  26226. changed = true;
  26227. }
  26228. if (cache[1] !== y) {
  26229. cache[1] = y;
  26230. changed = true;
  26231. }
  26232. return changed;
  26233. };
  26234. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26235. var cache = this._valueCache[uniformName];
  26236. if (!cache) {
  26237. cache = [x, y, z];
  26238. this._valueCache[uniformName] = cache;
  26239. return true;
  26240. }
  26241. var changed = false;
  26242. if (cache[0] !== x) {
  26243. cache[0] = x;
  26244. changed = true;
  26245. }
  26246. if (cache[1] !== y) {
  26247. cache[1] = y;
  26248. changed = true;
  26249. }
  26250. if (cache[2] !== z) {
  26251. cache[2] = z;
  26252. changed = true;
  26253. }
  26254. return changed;
  26255. };
  26256. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26257. var cache = this._valueCache[uniformName];
  26258. if (!cache) {
  26259. cache = [x, y, z, w];
  26260. this._valueCache[uniformName] = cache;
  26261. return true;
  26262. }
  26263. var changed = false;
  26264. if (cache[0] !== x) {
  26265. cache[0] = x;
  26266. changed = true;
  26267. }
  26268. if (cache[1] !== y) {
  26269. cache[1] = y;
  26270. changed = true;
  26271. }
  26272. if (cache[2] !== z) {
  26273. cache[2] = z;
  26274. changed = true;
  26275. }
  26276. if (cache[3] !== w) {
  26277. cache[3] = w;
  26278. changed = true;
  26279. }
  26280. return changed;
  26281. };
  26282. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26283. var bufferName = this._uniformBuffersNames[name];
  26284. if (Effect._baseCache[bufferName] === buffer) {
  26285. return;
  26286. }
  26287. Effect._baseCache[bufferName] = buffer;
  26288. this._engine.bindUniformBufferBase(buffer, bufferName);
  26289. };
  26290. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26291. this._engine.bindUniformBlock(this._program, blockName, index);
  26292. };
  26293. Effect.prototype.setIntArray = function (uniformName, array) {
  26294. this._valueCache[uniformName] = null;
  26295. this._engine.setIntArray(this.getUniform(uniformName), array);
  26296. return this;
  26297. };
  26298. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26299. this._valueCache[uniformName] = null;
  26300. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26301. return this;
  26302. };
  26303. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26304. this._valueCache[uniformName] = null;
  26305. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26306. return this;
  26307. };
  26308. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26309. this._valueCache[uniformName] = null;
  26310. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26311. return this;
  26312. };
  26313. Effect.prototype.setFloatArray = function (uniformName, array) {
  26314. this._valueCache[uniformName] = null;
  26315. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26316. return this;
  26317. };
  26318. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26319. this._valueCache[uniformName] = null;
  26320. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26321. return this;
  26322. };
  26323. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26324. this._valueCache[uniformName] = null;
  26325. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26326. return this;
  26327. };
  26328. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26329. this._valueCache[uniformName] = null;
  26330. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26331. return this;
  26332. };
  26333. Effect.prototype.setArray = function (uniformName, array) {
  26334. this._valueCache[uniformName] = null;
  26335. this._engine.setArray(this.getUniform(uniformName), array);
  26336. return this;
  26337. };
  26338. Effect.prototype.setArray2 = function (uniformName, array) {
  26339. this._valueCache[uniformName] = null;
  26340. this._engine.setArray2(this.getUniform(uniformName), array);
  26341. return this;
  26342. };
  26343. Effect.prototype.setArray3 = function (uniformName, array) {
  26344. this._valueCache[uniformName] = null;
  26345. this._engine.setArray3(this.getUniform(uniformName), array);
  26346. return this;
  26347. };
  26348. Effect.prototype.setArray4 = function (uniformName, array) {
  26349. this._valueCache[uniformName] = null;
  26350. this._engine.setArray4(this.getUniform(uniformName), array);
  26351. return this;
  26352. };
  26353. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26354. if (!matrices) {
  26355. return this;
  26356. }
  26357. this._valueCache[uniformName] = null;
  26358. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26359. return this;
  26360. };
  26361. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26362. if (this._cacheMatrix(uniformName, matrix)) {
  26363. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26364. }
  26365. return this;
  26366. };
  26367. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26368. this._valueCache[uniformName] = null;
  26369. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26370. return this;
  26371. };
  26372. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26373. this._valueCache[uniformName] = null;
  26374. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26375. return this;
  26376. };
  26377. Effect.prototype.setFloat = function (uniformName, value) {
  26378. var cache = this._valueCache[uniformName];
  26379. if (cache !== undefined && cache === value)
  26380. return this;
  26381. this._valueCache[uniformName] = value;
  26382. this._engine.setFloat(this.getUniform(uniformName), value);
  26383. return this;
  26384. };
  26385. Effect.prototype.setBool = function (uniformName, bool) {
  26386. var cache = this._valueCache[uniformName];
  26387. if (cache !== undefined && cache === bool)
  26388. return this;
  26389. this._valueCache[uniformName] = bool;
  26390. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26391. return this;
  26392. };
  26393. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26394. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26395. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26396. }
  26397. return this;
  26398. };
  26399. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26400. if (this._cacheFloat2(uniformName, x, y)) {
  26401. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26402. }
  26403. return this;
  26404. };
  26405. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26406. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26407. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26408. }
  26409. return this;
  26410. };
  26411. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26412. if (this._cacheFloat3(uniformName, x, y, z)) {
  26413. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26414. }
  26415. return this;
  26416. };
  26417. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26418. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26419. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26420. }
  26421. return this;
  26422. };
  26423. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26424. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26425. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26426. }
  26427. return this;
  26428. };
  26429. Effect.prototype.setColor3 = function (uniformName, color3) {
  26430. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26431. this._engine.setColor3(this.getUniform(uniformName), color3);
  26432. }
  26433. return this;
  26434. };
  26435. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26436. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26437. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26438. }
  26439. return this;
  26440. };
  26441. Effect.ResetCache = function () {
  26442. Effect._baseCache = {};
  26443. };
  26444. Effect._uniqueIdSeed = 0;
  26445. Effect._baseCache = {};
  26446. // Statics
  26447. Effect.ShadersStore = {};
  26448. Effect.IncludesShadersStore = {};
  26449. return Effect;
  26450. }());
  26451. BABYLON.Effect = Effect;
  26452. })(BABYLON || (BABYLON = {}));
  26453. //# sourceMappingURL=babylon.effect.js.map
  26454. var BABYLON;
  26455. (function (BABYLON) {
  26456. var MaterialHelper = /** @class */ (function () {
  26457. function MaterialHelper() {
  26458. }
  26459. MaterialHelper.BindEyePosition = function (effect, scene) {
  26460. if (scene._forcedViewPosition) {
  26461. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26462. return;
  26463. }
  26464. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26465. };
  26466. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26467. defines._needUVs = true;
  26468. defines[key] = true;
  26469. if (texture.getTextureMatrix().isIdentity(true)) {
  26470. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26471. if (texture.coordinatesIndex === 0) {
  26472. defines["MAINUV1"] = true;
  26473. }
  26474. else {
  26475. defines["MAINUV2"] = true;
  26476. }
  26477. }
  26478. else {
  26479. defines[key + "DIRECTUV"] = 0;
  26480. }
  26481. };
  26482. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26483. var matrix = texture.getTextureMatrix();
  26484. if (!matrix.isIdentity(true)) {
  26485. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26486. }
  26487. };
  26488. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26489. if (defines._areMiscDirty) {
  26490. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26491. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26492. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26493. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26494. }
  26495. };
  26496. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26497. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26498. var changed = false;
  26499. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26500. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26501. changed = true;
  26502. }
  26503. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26504. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26505. changed = true;
  26506. }
  26507. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26508. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26509. changed = true;
  26510. }
  26511. if (defines["INSTANCES"] !== useInstances) {
  26512. defines["INSTANCES"] = useInstances;
  26513. changed = true;
  26514. }
  26515. if (changed) {
  26516. defines.markAsUnprocessed();
  26517. }
  26518. };
  26519. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  26520. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26521. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  26522. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26523. return false;
  26524. }
  26525. defines._normals = defines._needNormals;
  26526. defines._uvs = defines._needUVs;
  26527. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26528. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26529. defines["TANGENT"] = true;
  26530. }
  26531. if (defines._needUVs) {
  26532. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26533. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26534. }
  26535. else {
  26536. defines["UV1"] = false;
  26537. defines["UV2"] = false;
  26538. }
  26539. if (useVertexColor) {
  26540. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26541. defines["VERTEXCOLOR"] = hasVertexColors;
  26542. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  26543. }
  26544. if (useBones) {
  26545. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26546. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26547. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26548. }
  26549. else {
  26550. defines["NUM_BONE_INFLUENCERS"] = 0;
  26551. defines["BonesPerMesh"] = 0;
  26552. }
  26553. }
  26554. if (useMorphTargets) {
  26555. var manager = mesh.morphTargetManager;
  26556. if (manager) {
  26557. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26558. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26559. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26560. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26561. }
  26562. else {
  26563. defines["MORPHTARGETS_TANGENT"] = false;
  26564. defines["MORPHTARGETS_NORMAL"] = false;
  26565. defines["MORPHTARGETS"] = false;
  26566. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26567. }
  26568. }
  26569. return true;
  26570. };
  26571. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26572. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26573. if (disableLighting === void 0) { disableLighting = false; }
  26574. if (!defines._areLightsDirty) {
  26575. return defines._needNormals;
  26576. }
  26577. var lightIndex = 0;
  26578. var needNormals = false;
  26579. var needRebuild = false;
  26580. var lightmapMode = false;
  26581. var shadowEnabled = false;
  26582. var specularEnabled = false;
  26583. if (scene.lightsEnabled && !disableLighting) {
  26584. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26585. var light = _a[_i];
  26586. needNormals = true;
  26587. if (defines["LIGHT" + lightIndex] === undefined) {
  26588. needRebuild = true;
  26589. }
  26590. defines["LIGHT" + lightIndex] = true;
  26591. defines["SPOTLIGHT" + lightIndex] = false;
  26592. defines["HEMILIGHT" + lightIndex] = false;
  26593. defines["POINTLIGHT" + lightIndex] = false;
  26594. defines["DIRLIGHT" + lightIndex] = false;
  26595. var type;
  26596. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26597. type = "SPOTLIGHT" + lightIndex;
  26598. }
  26599. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26600. type = "HEMILIGHT" + lightIndex;
  26601. }
  26602. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26603. type = "POINTLIGHT" + lightIndex;
  26604. }
  26605. else {
  26606. type = "DIRLIGHT" + lightIndex;
  26607. }
  26608. defines[type] = true;
  26609. // Specular
  26610. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26611. specularEnabled = true;
  26612. }
  26613. // Shadows
  26614. defines["SHADOW" + lightIndex] = false;
  26615. defines["SHADOWPCF" + lightIndex] = false;
  26616. defines["SHADOWESM" + lightIndex] = false;
  26617. defines["SHADOWCUBE" + lightIndex] = false;
  26618. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26619. var shadowGenerator = light.getShadowGenerator();
  26620. if (shadowGenerator) {
  26621. shadowEnabled = true;
  26622. shadowGenerator.prepareDefines(defines, lightIndex);
  26623. }
  26624. }
  26625. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26626. lightmapMode = true;
  26627. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26628. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26629. }
  26630. else {
  26631. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26632. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26633. }
  26634. lightIndex++;
  26635. if (lightIndex === maxSimultaneousLights)
  26636. break;
  26637. }
  26638. }
  26639. defines["SPECULARTERM"] = specularEnabled;
  26640. defines["SHADOWS"] = shadowEnabled;
  26641. // Resetting all other lights if any
  26642. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26643. if (defines["LIGHT" + index] !== undefined) {
  26644. defines["LIGHT" + index] = false;
  26645. defines["HEMILIGHT" + lightIndex] = false;
  26646. defines["POINTLIGHT" + lightIndex] = false;
  26647. defines["DIRLIGHT" + lightIndex] = false;
  26648. defines["SPOTLIGHT" + lightIndex] = false;
  26649. defines["SHADOW" + lightIndex] = false;
  26650. }
  26651. }
  26652. var caps = scene.getEngine().getCaps();
  26653. if (defines["SHADOWFLOAT"] === undefined) {
  26654. needRebuild = true;
  26655. }
  26656. defines["SHADOWFLOAT"] = shadowEnabled &&
  26657. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26658. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26659. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26660. if (needRebuild) {
  26661. defines.rebuild();
  26662. }
  26663. return needNormals;
  26664. };
  26665. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26666. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26667. var uniformsList;
  26668. var uniformBuffersList = null;
  26669. if (uniformsListOrOptions.uniformsNames) {
  26670. var options = uniformsListOrOptions;
  26671. uniformsList = options.uniformsNames;
  26672. uniformBuffersList = options.uniformBuffersNames;
  26673. samplersList = options.samplers;
  26674. defines = options.defines;
  26675. maxSimultaneousLights = options.maxSimultaneousLights;
  26676. }
  26677. else {
  26678. uniformsList = uniformsListOrOptions;
  26679. if (!samplersList) {
  26680. samplersList = [];
  26681. }
  26682. }
  26683. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26684. if (!defines["LIGHT" + lightIndex]) {
  26685. break;
  26686. }
  26687. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26688. if (uniformBuffersList) {
  26689. uniformBuffersList.push("Light" + lightIndex);
  26690. }
  26691. samplersList.push("shadowSampler" + lightIndex);
  26692. }
  26693. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26694. uniformsList.push("morphTargetInfluences");
  26695. }
  26696. };
  26697. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  26698. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26699. if (rank === void 0) { rank = 0; }
  26700. var lightFallbackRank = 0;
  26701. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26702. if (!defines["LIGHT" + lightIndex]) {
  26703. break;
  26704. }
  26705. if (lightIndex > 0) {
  26706. lightFallbackRank = rank + lightIndex;
  26707. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  26708. }
  26709. if (!defines["SHADOWS"]) {
  26710. if (defines["SHADOW" + lightIndex]) {
  26711. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  26712. }
  26713. if (defines["SHADOWPCF" + lightIndex]) {
  26714. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  26715. }
  26716. if (defines["SHADOWESM" + lightIndex]) {
  26717. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  26718. }
  26719. }
  26720. }
  26721. return lightFallbackRank++;
  26722. };
  26723. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26724. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26725. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26726. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26727. var manager = mesh.morphTargetManager;
  26728. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26729. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26730. for (var index = 0; index < influencers; index++) {
  26731. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26732. if (normal) {
  26733. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26734. }
  26735. if (tangent) {
  26736. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26737. }
  26738. if (attribs.length > maxAttributesCount) {
  26739. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26740. }
  26741. }
  26742. }
  26743. };
  26744. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26745. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26746. fallbacks.addCPUSkinningFallback(0, mesh);
  26747. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26748. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26749. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26750. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26751. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26752. }
  26753. }
  26754. };
  26755. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26756. if (defines["INSTANCES"]) {
  26757. attribs.push("world0");
  26758. attribs.push("world1");
  26759. attribs.push("world2");
  26760. attribs.push("world3");
  26761. }
  26762. };
  26763. // Bindings
  26764. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26765. if (light.shadowEnabled && mesh.receiveShadows) {
  26766. var shadowGenerator = light.getShadowGenerator();
  26767. if (shadowGenerator) {
  26768. shadowGenerator.bindShadowLight(lightIndex, effect);
  26769. }
  26770. }
  26771. };
  26772. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26773. light.transferToEffect(effect, lightIndex + "");
  26774. };
  26775. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26776. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26777. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26778. var lightIndex = 0;
  26779. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26780. var light = _a[_i];
  26781. var scaledIntensity = light.getScaledIntensity();
  26782. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26783. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26784. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26785. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26786. if (defines["SPECULARTERM"]) {
  26787. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26788. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26789. }
  26790. // Shadows
  26791. if (scene.shadowsEnabled) {
  26792. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26793. }
  26794. light._uniformBuffer.update();
  26795. lightIndex++;
  26796. if (lightIndex === maxSimultaneousLights)
  26797. break;
  26798. }
  26799. };
  26800. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26801. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26802. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26803. effect.setColor3("vFogColor", scene.fogColor);
  26804. }
  26805. };
  26806. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26807. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26808. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26809. if (matrices && effect) {
  26810. effect.setMatrices("mBones", matrices);
  26811. }
  26812. }
  26813. };
  26814. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26815. var manager = abstractMesh.morphTargetManager;
  26816. if (!abstractMesh || !manager) {
  26817. return;
  26818. }
  26819. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26820. };
  26821. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26822. if (defines["LOGARITHMICDEPTH"]) {
  26823. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26824. }
  26825. };
  26826. MaterialHelper.BindClipPlane = function (effect, scene) {
  26827. if (scene.clipPlane) {
  26828. var clipPlane = scene.clipPlane;
  26829. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26830. }
  26831. };
  26832. return MaterialHelper;
  26833. }());
  26834. BABYLON.MaterialHelper = MaterialHelper;
  26835. })(BABYLON || (BABYLON = {}));
  26836. //# sourceMappingURL=babylon.materialHelper.js.map
  26837. var BABYLON;
  26838. (function (BABYLON) {
  26839. var MaterialDefines = /** @class */ (function () {
  26840. function MaterialDefines() {
  26841. this._isDirty = true;
  26842. this._areLightsDirty = true;
  26843. this._areAttributesDirty = true;
  26844. this._areTexturesDirty = true;
  26845. this._areFresnelDirty = true;
  26846. this._areMiscDirty = true;
  26847. this._areImageProcessingDirty = true;
  26848. this._normals = false;
  26849. this._uvs = false;
  26850. this._needNormals = false;
  26851. this._needUVs = false;
  26852. }
  26853. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26854. get: function () {
  26855. return this._isDirty;
  26856. },
  26857. enumerable: true,
  26858. configurable: true
  26859. });
  26860. MaterialDefines.prototype.markAsProcessed = function () {
  26861. this._isDirty = false;
  26862. this._areAttributesDirty = false;
  26863. this._areTexturesDirty = false;
  26864. this._areFresnelDirty = false;
  26865. this._areLightsDirty = false;
  26866. this._areMiscDirty = false;
  26867. this._areImageProcessingDirty = false;
  26868. };
  26869. MaterialDefines.prototype.markAsUnprocessed = function () {
  26870. this._isDirty = true;
  26871. };
  26872. MaterialDefines.prototype.markAllAsDirty = function () {
  26873. this._areTexturesDirty = true;
  26874. this._areAttributesDirty = true;
  26875. this._areLightsDirty = true;
  26876. this._areFresnelDirty = true;
  26877. this._areMiscDirty = true;
  26878. this._areImageProcessingDirty = true;
  26879. this._isDirty = true;
  26880. };
  26881. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26882. this._areImageProcessingDirty = true;
  26883. this._isDirty = true;
  26884. };
  26885. MaterialDefines.prototype.markAsLightDirty = function () {
  26886. this._areLightsDirty = true;
  26887. this._isDirty = true;
  26888. };
  26889. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26890. this._areAttributesDirty = true;
  26891. this._isDirty = true;
  26892. };
  26893. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26894. this._areTexturesDirty = true;
  26895. this._isDirty = true;
  26896. };
  26897. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26898. this._areFresnelDirty = true;
  26899. this._isDirty = true;
  26900. };
  26901. MaterialDefines.prototype.markAsMiscDirty = function () {
  26902. this._areMiscDirty = true;
  26903. this._isDirty = true;
  26904. };
  26905. MaterialDefines.prototype.rebuild = function () {
  26906. if (this._keys) {
  26907. delete this._keys;
  26908. }
  26909. this._keys = [];
  26910. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26911. var key = _a[_i];
  26912. if (key[0] === "_") {
  26913. continue;
  26914. }
  26915. this._keys.push(key);
  26916. }
  26917. };
  26918. MaterialDefines.prototype.isEqual = function (other) {
  26919. if (this._keys.length !== other._keys.length) {
  26920. return false;
  26921. }
  26922. for (var index = 0; index < this._keys.length; index++) {
  26923. var prop = this._keys[index];
  26924. if (this[prop] !== other[prop]) {
  26925. return false;
  26926. }
  26927. }
  26928. return true;
  26929. };
  26930. MaterialDefines.prototype.cloneTo = function (other) {
  26931. if (this._keys.length !== other._keys.length) {
  26932. other._keys = this._keys.slice(0);
  26933. }
  26934. for (var index = 0; index < this._keys.length; index++) {
  26935. var prop = this._keys[index];
  26936. other[prop] = this[prop];
  26937. }
  26938. };
  26939. MaterialDefines.prototype.reset = function () {
  26940. for (var index = 0; index < this._keys.length; index++) {
  26941. var prop = this._keys[index];
  26942. if (typeof (this[prop]) === "number") {
  26943. this[prop] = 0;
  26944. }
  26945. else {
  26946. this[prop] = false;
  26947. }
  26948. }
  26949. };
  26950. MaterialDefines.prototype.toString = function () {
  26951. var result = "";
  26952. for (var index = 0; index < this._keys.length; index++) {
  26953. var prop = this._keys[index];
  26954. var value = this[prop];
  26955. if (typeof (value) === "number") {
  26956. result += "#define " + prop + " " + this[prop] + "\n";
  26957. }
  26958. else if (value) {
  26959. result += "#define " + prop + "\n";
  26960. }
  26961. }
  26962. return result;
  26963. };
  26964. return MaterialDefines;
  26965. }());
  26966. BABYLON.MaterialDefines = MaterialDefines;
  26967. var Material = /** @class */ (function () {
  26968. function Material(name, scene, doNotAdd) {
  26969. this.checkReadyOnEveryCall = false;
  26970. this.checkReadyOnlyOnce = false;
  26971. this.state = "";
  26972. this.alpha = 1.0;
  26973. this._backFaceCulling = true;
  26974. this.doNotSerialize = false;
  26975. this.storeEffectOnSubMeshes = false;
  26976. /**
  26977. * An event triggered when the material is disposed.
  26978. * @type {BABYLON.Observable}
  26979. */
  26980. this.onDisposeObservable = new BABYLON.Observable();
  26981. /**
  26982. * An event triggered when the material is bound.
  26983. * @type {BABYLON.Observable}
  26984. */
  26985. this.onBindObservable = new BABYLON.Observable();
  26986. /**
  26987. * An event triggered when the material is unbound.
  26988. * @type {BABYLON.Observable}
  26989. */
  26990. this.onUnBindObservable = new BABYLON.Observable();
  26991. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26992. this._needDepthPrePass = false;
  26993. this.disableDepthWrite = false;
  26994. this.forceDepthWrite = false;
  26995. this.separateCullingPass = false;
  26996. this._fogEnabled = true;
  26997. this.pointSize = 1.0;
  26998. this.zOffset = 0;
  26999. this._wasPreviouslyReady = false;
  27000. this._fillMode = Material.TriangleFillMode;
  27001. this.name = name;
  27002. this.id = name || BABYLON.Tools.RandomId();
  27003. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27004. if (this._scene.useRightHandedSystem) {
  27005. this.sideOrientation = Material.ClockWiseSideOrientation;
  27006. }
  27007. else {
  27008. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27009. }
  27010. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27011. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27012. if (!doNotAdd) {
  27013. this._scene.materials.push(this);
  27014. }
  27015. }
  27016. Object.defineProperty(Material, "TriangleFillMode", {
  27017. get: function () {
  27018. return Material._TriangleFillMode;
  27019. },
  27020. enumerable: true,
  27021. configurable: true
  27022. });
  27023. Object.defineProperty(Material, "WireFrameFillMode", {
  27024. get: function () {
  27025. return Material._WireFrameFillMode;
  27026. },
  27027. enumerable: true,
  27028. configurable: true
  27029. });
  27030. Object.defineProperty(Material, "PointFillMode", {
  27031. get: function () {
  27032. return Material._PointFillMode;
  27033. },
  27034. enumerable: true,
  27035. configurable: true
  27036. });
  27037. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27038. get: function () {
  27039. return Material._ClockWiseSideOrientation;
  27040. },
  27041. enumerable: true,
  27042. configurable: true
  27043. });
  27044. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27045. get: function () {
  27046. return Material._CounterClockWiseSideOrientation;
  27047. },
  27048. enumerable: true,
  27049. configurable: true
  27050. });
  27051. Object.defineProperty(Material, "TextureDirtyFlag", {
  27052. get: function () {
  27053. return Material._TextureDirtyFlag;
  27054. },
  27055. enumerable: true,
  27056. configurable: true
  27057. });
  27058. Object.defineProperty(Material, "LightDirtyFlag", {
  27059. get: function () {
  27060. return Material._LightDirtyFlag;
  27061. },
  27062. enumerable: true,
  27063. configurable: true
  27064. });
  27065. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27066. get: function () {
  27067. return Material._FresnelDirtyFlag;
  27068. },
  27069. enumerable: true,
  27070. configurable: true
  27071. });
  27072. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27073. get: function () {
  27074. return Material._AttributesDirtyFlag;
  27075. },
  27076. enumerable: true,
  27077. configurable: true
  27078. });
  27079. Object.defineProperty(Material, "MiscDirtyFlag", {
  27080. get: function () {
  27081. return Material._MiscDirtyFlag;
  27082. },
  27083. enumerable: true,
  27084. configurable: true
  27085. });
  27086. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27087. get: function () {
  27088. return this._backFaceCulling;
  27089. },
  27090. set: function (value) {
  27091. if (this._backFaceCulling === value) {
  27092. return;
  27093. }
  27094. this._backFaceCulling = value;
  27095. this.markAsDirty(Material.TextureDirtyFlag);
  27096. },
  27097. enumerable: true,
  27098. configurable: true
  27099. });
  27100. Object.defineProperty(Material.prototype, "onDispose", {
  27101. set: function (callback) {
  27102. if (this._onDisposeObserver) {
  27103. this.onDisposeObservable.remove(this._onDisposeObserver);
  27104. }
  27105. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27106. },
  27107. enumerable: true,
  27108. configurable: true
  27109. });
  27110. Object.defineProperty(Material.prototype, "onBind", {
  27111. set: function (callback) {
  27112. if (this._onBindObserver) {
  27113. this.onBindObservable.remove(this._onBindObserver);
  27114. }
  27115. this._onBindObserver = this.onBindObservable.add(callback);
  27116. },
  27117. enumerable: true,
  27118. configurable: true
  27119. });
  27120. Object.defineProperty(Material.prototype, "alphaMode", {
  27121. get: function () {
  27122. return this._alphaMode;
  27123. },
  27124. set: function (value) {
  27125. if (this._alphaMode === value) {
  27126. return;
  27127. }
  27128. this._alphaMode = value;
  27129. this.markAsDirty(Material.TextureDirtyFlag);
  27130. },
  27131. enumerable: true,
  27132. configurable: true
  27133. });
  27134. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27135. get: function () {
  27136. return this._needDepthPrePass;
  27137. },
  27138. set: function (value) {
  27139. if (this._needDepthPrePass === value) {
  27140. return;
  27141. }
  27142. this._needDepthPrePass = value;
  27143. if (this._needDepthPrePass) {
  27144. this.checkReadyOnEveryCall = true;
  27145. }
  27146. },
  27147. enumerable: true,
  27148. configurable: true
  27149. });
  27150. Object.defineProperty(Material.prototype, "fogEnabled", {
  27151. get: function () {
  27152. return this._fogEnabled;
  27153. },
  27154. set: function (value) {
  27155. if (this._fogEnabled === value) {
  27156. return;
  27157. }
  27158. this._fogEnabled = value;
  27159. this.markAsDirty(Material.MiscDirtyFlag);
  27160. },
  27161. enumerable: true,
  27162. configurable: true
  27163. });
  27164. Object.defineProperty(Material.prototype, "wireframe", {
  27165. get: function () {
  27166. return this._fillMode === Material.WireFrameFillMode;
  27167. },
  27168. set: function (value) {
  27169. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27170. },
  27171. enumerable: true,
  27172. configurable: true
  27173. });
  27174. Object.defineProperty(Material.prototype, "pointsCloud", {
  27175. get: function () {
  27176. return this._fillMode === Material.PointFillMode;
  27177. },
  27178. set: function (value) {
  27179. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27180. },
  27181. enumerable: true,
  27182. configurable: true
  27183. });
  27184. Object.defineProperty(Material.prototype, "fillMode", {
  27185. get: function () {
  27186. return this._fillMode;
  27187. },
  27188. set: function (value) {
  27189. if (this._fillMode === value) {
  27190. return;
  27191. }
  27192. this._fillMode = value;
  27193. this.markAsDirty(Material.MiscDirtyFlag);
  27194. },
  27195. enumerable: true,
  27196. configurable: true
  27197. });
  27198. /**
  27199. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27200. * subclasses should override adding information pertainent to themselves
  27201. */
  27202. Material.prototype.toString = function (fullDetails) {
  27203. var ret = "Name: " + this.name;
  27204. if (fullDetails) {
  27205. }
  27206. return ret;
  27207. };
  27208. /**
  27209. * Child classes can use it to update shaders
  27210. */
  27211. Material.prototype.getClassName = function () {
  27212. return "Material";
  27213. };
  27214. Object.defineProperty(Material.prototype, "isFrozen", {
  27215. get: function () {
  27216. return this.checkReadyOnlyOnce;
  27217. },
  27218. enumerable: true,
  27219. configurable: true
  27220. });
  27221. Material.prototype.freeze = function () {
  27222. this.checkReadyOnlyOnce = true;
  27223. };
  27224. Material.prototype.unfreeze = function () {
  27225. this.checkReadyOnlyOnce = false;
  27226. };
  27227. Material.prototype.isReady = function (mesh, useInstances) {
  27228. return true;
  27229. };
  27230. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27231. return false;
  27232. };
  27233. Material.prototype.getEffect = function () {
  27234. return this._effect;
  27235. };
  27236. Material.prototype.getScene = function () {
  27237. return this._scene;
  27238. };
  27239. Material.prototype.needAlphaBlending = function () {
  27240. return (this.alpha < 1.0);
  27241. };
  27242. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27243. return (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27244. };
  27245. Material.prototype.needAlphaTesting = function () {
  27246. return false;
  27247. };
  27248. Material.prototype.getAlphaTestTexture = function () {
  27249. return null;
  27250. };
  27251. Material.prototype.markDirty = function () {
  27252. this._wasPreviouslyReady = false;
  27253. };
  27254. Material.prototype._preBind = function (effect, overrideOrientation) {
  27255. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27256. var engine = this._scene.getEngine();
  27257. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27258. var reverse = orientation === Material.ClockWiseSideOrientation;
  27259. engine.enableEffect(effect ? effect : this._effect);
  27260. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27261. return reverse;
  27262. };
  27263. Material.prototype.bind = function (world, mesh) {
  27264. };
  27265. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27266. };
  27267. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27268. };
  27269. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27270. sceneUbo.bindToEffect(effect, "Scene");
  27271. };
  27272. Material.prototype.bindView = function (effect) {
  27273. if (!this._useUBO) {
  27274. effect.setMatrix("view", this.getScene().getViewMatrix());
  27275. }
  27276. else {
  27277. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27278. }
  27279. };
  27280. Material.prototype.bindViewProjection = function (effect) {
  27281. if (!this._useUBO) {
  27282. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27283. }
  27284. else {
  27285. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27286. }
  27287. };
  27288. Material.prototype._afterBind = function (mesh) {
  27289. this._scene._cachedMaterial = this;
  27290. if (mesh) {
  27291. this._scene._cachedVisibility = mesh.visibility;
  27292. }
  27293. else {
  27294. this._scene._cachedVisibility = 1;
  27295. }
  27296. if (mesh) {
  27297. this.onBindObservable.notifyObservers(mesh);
  27298. }
  27299. if (this.disableDepthWrite) {
  27300. var engine = this._scene.getEngine();
  27301. this._cachedDepthWriteState = engine.getDepthWrite();
  27302. engine.setDepthWrite(false);
  27303. }
  27304. };
  27305. Material.prototype.unbind = function () {
  27306. this.onUnBindObservable.notifyObservers(this);
  27307. if (this.disableDepthWrite) {
  27308. var engine = this._scene.getEngine();
  27309. engine.setDepthWrite(this._cachedDepthWriteState);
  27310. }
  27311. };
  27312. Material.prototype.getActiveTextures = function () {
  27313. return [];
  27314. };
  27315. Material.prototype.hasTexture = function (texture) {
  27316. return false;
  27317. };
  27318. Material.prototype.clone = function (name) {
  27319. return null;
  27320. };
  27321. Material.prototype.getBindedMeshes = function () {
  27322. var result = new Array();
  27323. for (var index = 0; index < this._scene.meshes.length; index++) {
  27324. var mesh = this._scene.meshes[index];
  27325. if (mesh.material === this) {
  27326. result.push(mesh);
  27327. }
  27328. }
  27329. return result;
  27330. };
  27331. /**
  27332. * Force shader compilation including textures ready check
  27333. */
  27334. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27335. var _this = this;
  27336. var subMesh = new BABYLON.BaseSubMesh();
  27337. var scene = this.getScene();
  27338. var engine = scene.getEngine();
  27339. var checkReady = function () {
  27340. if (!_this._scene || !_this._scene.getEngine()) {
  27341. return;
  27342. }
  27343. if (subMesh._materialDefines) {
  27344. subMesh._materialDefines._renderId = -1;
  27345. }
  27346. var alphaTestState = engine.getAlphaTesting();
  27347. var clipPlaneState = scene.clipPlane;
  27348. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27349. if (options && options.clipPlane) {
  27350. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27351. }
  27352. if (_this.storeEffectOnSubMeshes) {
  27353. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27354. if (onCompiled) {
  27355. onCompiled(_this);
  27356. }
  27357. }
  27358. else {
  27359. setTimeout(checkReady, 16);
  27360. }
  27361. }
  27362. else {
  27363. if (_this.isReady(mesh)) {
  27364. if (onCompiled) {
  27365. onCompiled(_this);
  27366. }
  27367. }
  27368. else {
  27369. setTimeout(checkReady, 16);
  27370. }
  27371. }
  27372. engine.setAlphaTesting(alphaTestState);
  27373. if (options && options.clipPlane) {
  27374. scene.clipPlane = clipPlaneState;
  27375. }
  27376. };
  27377. checkReady();
  27378. };
  27379. Material.prototype.markAsDirty = function (flag) {
  27380. if (flag & Material.TextureDirtyFlag) {
  27381. this._markAllSubMeshesAsTexturesDirty();
  27382. }
  27383. if (flag & Material.LightDirtyFlag) {
  27384. this._markAllSubMeshesAsLightsDirty();
  27385. }
  27386. if (flag & Material.FresnelDirtyFlag) {
  27387. this._markAllSubMeshesAsFresnelDirty();
  27388. }
  27389. if (flag & Material.AttributesDirtyFlag) {
  27390. this._markAllSubMeshesAsAttributesDirty();
  27391. }
  27392. if (flag & Material.MiscDirtyFlag) {
  27393. this._markAllSubMeshesAsMiscDirty();
  27394. }
  27395. this.getScene().resetCachedMaterial();
  27396. };
  27397. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27398. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27399. var mesh = _a[_i];
  27400. if (!mesh.subMeshes) {
  27401. continue;
  27402. }
  27403. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27404. var subMesh = _c[_b];
  27405. if (subMesh.getMaterial() !== this) {
  27406. continue;
  27407. }
  27408. if (!subMesh._materialDefines) {
  27409. continue;
  27410. }
  27411. func(subMesh._materialDefines);
  27412. }
  27413. }
  27414. };
  27415. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27416. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27417. };
  27418. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27419. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27420. };
  27421. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27422. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27423. };
  27424. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27425. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27426. };
  27427. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27428. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27429. };
  27430. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27431. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27432. };
  27433. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27434. // Animations
  27435. this.getScene().stopAnimation(this);
  27436. // Remove from scene
  27437. var index = this._scene.materials.indexOf(this);
  27438. if (index >= 0) {
  27439. this._scene.materials.splice(index, 1);
  27440. }
  27441. // Remove from meshes
  27442. for (index = 0; index < this._scene.meshes.length; index++) {
  27443. var mesh = this._scene.meshes[index];
  27444. if (mesh.material === this) {
  27445. mesh.material = null;
  27446. if (mesh.geometry) {
  27447. var geometry = (mesh.geometry);
  27448. if (this.storeEffectOnSubMeshes) {
  27449. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27450. var subMesh = _a[_i];
  27451. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27452. if (forceDisposeEffect && subMesh._materialEffect) {
  27453. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27454. }
  27455. }
  27456. }
  27457. else {
  27458. geometry._releaseVertexArrayObject(this._effect);
  27459. }
  27460. }
  27461. }
  27462. }
  27463. this._uniformBuffer.dispose();
  27464. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27465. if (forceDisposeEffect && this._effect) {
  27466. if (!this.storeEffectOnSubMeshes) {
  27467. this._scene.getEngine()._releaseEffect(this._effect);
  27468. }
  27469. this._effect = null;
  27470. }
  27471. // Callback
  27472. this.onDisposeObservable.notifyObservers(this);
  27473. this.onDisposeObservable.clear();
  27474. this.onBindObservable.clear();
  27475. this.onUnBindObservable.clear();
  27476. };
  27477. Material.prototype.serialize = function () {
  27478. return BABYLON.SerializationHelper.Serialize(this);
  27479. };
  27480. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27481. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27482. multiMaterial.id = parsedMultiMaterial.id;
  27483. if (BABYLON.Tags) {
  27484. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27485. }
  27486. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27487. var subMatId = parsedMultiMaterial.materials[matIndex];
  27488. if (subMatId) {
  27489. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27490. }
  27491. else {
  27492. multiMaterial.subMaterials.push(null);
  27493. }
  27494. }
  27495. return multiMaterial;
  27496. };
  27497. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27498. if (!parsedMaterial.customType) {
  27499. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27500. }
  27501. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27502. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27503. if (!BABYLON.LegacyPBRMaterial) {
  27504. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27505. return;
  27506. }
  27507. }
  27508. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27509. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27510. ;
  27511. };
  27512. Material._TriangleFillMode = 0;
  27513. Material._WireFrameFillMode = 1;
  27514. Material._PointFillMode = 2;
  27515. Material._ClockWiseSideOrientation = 0;
  27516. Material._CounterClockWiseSideOrientation = 1;
  27517. Material._TextureDirtyFlag = 1;
  27518. Material._LightDirtyFlag = 2;
  27519. Material._FresnelDirtyFlag = 4;
  27520. Material._AttributesDirtyFlag = 8;
  27521. Material._MiscDirtyFlag = 16;
  27522. __decorate([
  27523. BABYLON.serialize()
  27524. ], Material.prototype, "id", void 0);
  27525. __decorate([
  27526. BABYLON.serialize()
  27527. ], Material.prototype, "name", void 0);
  27528. __decorate([
  27529. BABYLON.serialize()
  27530. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27531. __decorate([
  27532. BABYLON.serialize()
  27533. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27534. __decorate([
  27535. BABYLON.serialize()
  27536. ], Material.prototype, "state", void 0);
  27537. __decorate([
  27538. BABYLON.serialize()
  27539. ], Material.prototype, "alpha", void 0);
  27540. __decorate([
  27541. BABYLON.serialize("backFaceCulling")
  27542. ], Material.prototype, "_backFaceCulling", void 0);
  27543. __decorate([
  27544. BABYLON.serialize()
  27545. ], Material.prototype, "sideOrientation", void 0);
  27546. __decorate([
  27547. BABYLON.serialize("alphaMode")
  27548. ], Material.prototype, "_alphaMode", void 0);
  27549. __decorate([
  27550. BABYLON.serialize()
  27551. ], Material.prototype, "_needDepthPrePass", void 0);
  27552. __decorate([
  27553. BABYLON.serialize()
  27554. ], Material.prototype, "disableDepthWrite", void 0);
  27555. __decorate([
  27556. BABYLON.serialize()
  27557. ], Material.prototype, "forceDepthWrite", void 0);
  27558. __decorate([
  27559. BABYLON.serialize()
  27560. ], Material.prototype, "separateCullingPass", void 0);
  27561. __decorate([
  27562. BABYLON.serialize("fogEnabled")
  27563. ], Material.prototype, "_fogEnabled", void 0);
  27564. __decorate([
  27565. BABYLON.serialize()
  27566. ], Material.prototype, "pointSize", void 0);
  27567. __decorate([
  27568. BABYLON.serialize()
  27569. ], Material.prototype, "zOffset", void 0);
  27570. __decorate([
  27571. BABYLON.serialize()
  27572. ], Material.prototype, "wireframe", null);
  27573. __decorate([
  27574. BABYLON.serialize()
  27575. ], Material.prototype, "pointsCloud", null);
  27576. __decorate([
  27577. BABYLON.serialize()
  27578. ], Material.prototype, "fillMode", null);
  27579. return Material;
  27580. }());
  27581. BABYLON.Material = Material;
  27582. })(BABYLON || (BABYLON = {}));
  27583. //# sourceMappingURL=babylon.material.js.map
  27584. var BABYLON;
  27585. (function (BABYLON) {
  27586. var UniformBuffer = /** @class */ (function () {
  27587. /**
  27588. * Uniform buffer objects.
  27589. *
  27590. * Handles blocks of uniform on the GPU.
  27591. *
  27592. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27593. *
  27594. * For more information, please refer to :
  27595. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27596. */
  27597. function UniformBuffer(engine, data, dynamic) {
  27598. this._engine = engine;
  27599. this._noUBO = !engine.supportsUniformBuffers;
  27600. this._dynamic = dynamic;
  27601. this._data = data || [];
  27602. this._uniformLocations = {};
  27603. this._uniformSizes = {};
  27604. this._uniformLocationPointer = 0;
  27605. this._needSync = false;
  27606. if (this._noUBO) {
  27607. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27608. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27609. this.updateFloat = this._updateFloatForEffect;
  27610. this.updateFloat2 = this._updateFloat2ForEffect;
  27611. this.updateFloat3 = this._updateFloat3ForEffect;
  27612. this.updateFloat4 = this._updateFloat4ForEffect;
  27613. this.updateMatrix = this._updateMatrixForEffect;
  27614. this.updateVector3 = this._updateVector3ForEffect;
  27615. this.updateVector4 = this._updateVector4ForEffect;
  27616. this.updateColor3 = this._updateColor3ForEffect;
  27617. this.updateColor4 = this._updateColor4ForEffect;
  27618. }
  27619. else {
  27620. this._engine._uniformBuffers.push(this);
  27621. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27622. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27623. this.updateFloat = this._updateFloatForUniform;
  27624. this.updateFloat2 = this._updateFloat2ForUniform;
  27625. this.updateFloat3 = this._updateFloat3ForUniform;
  27626. this.updateFloat4 = this._updateFloat4ForUniform;
  27627. this.updateMatrix = this._updateMatrixForUniform;
  27628. this.updateVector3 = this._updateVector3ForUniform;
  27629. this.updateVector4 = this._updateVector4ForUniform;
  27630. this.updateColor3 = this._updateColor3ForUniform;
  27631. this.updateColor4 = this._updateColor4ForUniform;
  27632. }
  27633. }
  27634. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27635. // Properties
  27636. /**
  27637. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27638. * or just falling back on setUniformXXX calls.
  27639. */
  27640. get: function () {
  27641. return !this._noUBO;
  27642. },
  27643. enumerable: true,
  27644. configurable: true
  27645. });
  27646. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27647. /**
  27648. * Indicates if the WebGL underlying uniform buffer is in sync
  27649. * with the javascript cache data.
  27650. */
  27651. get: function () {
  27652. return !this._needSync;
  27653. },
  27654. enumerable: true,
  27655. configurable: true
  27656. });
  27657. /**
  27658. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27659. * Also, a dynamic UniformBuffer will disable cache verification and always
  27660. * update the underlying WebGL uniform buffer to the GPU.
  27661. */
  27662. UniformBuffer.prototype.isDynamic = function () {
  27663. return this._dynamic !== undefined;
  27664. };
  27665. /**
  27666. * The data cache on JS side.
  27667. */
  27668. UniformBuffer.prototype.getData = function () {
  27669. return this._bufferData;
  27670. };
  27671. /**
  27672. * The underlying WebGL Uniform buffer.
  27673. */
  27674. UniformBuffer.prototype.getBuffer = function () {
  27675. return this._buffer;
  27676. };
  27677. /**
  27678. * std140 layout specifies how to align data within an UBO structure.
  27679. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27680. * for specs.
  27681. */
  27682. UniformBuffer.prototype._fillAlignment = function (size) {
  27683. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27684. // and 4x4 matrices
  27685. // TODO : change if other types are used
  27686. var alignment;
  27687. if (size <= 2) {
  27688. alignment = size;
  27689. }
  27690. else {
  27691. alignment = 4;
  27692. }
  27693. if ((this._uniformLocationPointer % alignment) !== 0) {
  27694. var oldPointer = this._uniformLocationPointer;
  27695. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27696. var diff = this._uniformLocationPointer - oldPointer;
  27697. for (var i = 0; i < diff; i++) {
  27698. this._data.push(0);
  27699. }
  27700. }
  27701. };
  27702. /**
  27703. * Adds an uniform in the buffer.
  27704. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27705. * for the layout to be correct !
  27706. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27707. * @param {number|number[]} size Data size, or data directly.
  27708. */
  27709. UniformBuffer.prototype.addUniform = function (name, size) {
  27710. if (this._noUBO) {
  27711. return;
  27712. }
  27713. if (this._uniformLocations[name] !== undefined) {
  27714. // Already existing uniform
  27715. return;
  27716. }
  27717. // This function must be called in the order of the shader layout !
  27718. // size can be the size of the uniform, or data directly
  27719. var data;
  27720. if (size instanceof Array) {
  27721. data = size;
  27722. size = data.length;
  27723. }
  27724. else {
  27725. size = size;
  27726. data = [];
  27727. // Fill with zeros
  27728. for (var i = 0; i < size; i++) {
  27729. data.push(0);
  27730. }
  27731. }
  27732. this._fillAlignment(size);
  27733. this._uniformSizes[name] = size;
  27734. this._uniformLocations[name] = this._uniformLocationPointer;
  27735. this._uniformLocationPointer += size;
  27736. for (var i = 0; i < size; i++) {
  27737. this._data.push(data[i]);
  27738. }
  27739. this._needSync = true;
  27740. };
  27741. /**
  27742. * Wrapper for addUniform.
  27743. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27744. * @param {Matrix} mat A 4x4 matrix.
  27745. */
  27746. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27747. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27748. };
  27749. /**
  27750. * Wrapper for addUniform.
  27751. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27752. * @param {number} x
  27753. * @param {number} y
  27754. */
  27755. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27756. var temp = [x, y];
  27757. this.addUniform(name, temp);
  27758. };
  27759. /**
  27760. * Wrapper for addUniform.
  27761. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27762. * @param {number} x
  27763. * @param {number} y
  27764. * @param {number} z
  27765. */
  27766. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27767. var temp = [x, y, z];
  27768. this.addUniform(name, temp);
  27769. };
  27770. /**
  27771. * Wrapper for addUniform.
  27772. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27773. * @param {Color3} color
  27774. */
  27775. UniformBuffer.prototype.addColor3 = function (name, color) {
  27776. var temp = new Array();
  27777. color.toArray(temp);
  27778. this.addUniform(name, temp);
  27779. };
  27780. /**
  27781. * Wrapper for addUniform.
  27782. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27783. * @param {Color3} color
  27784. * @param {number} alpha
  27785. */
  27786. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27787. var temp = new Array();
  27788. color.toArray(temp);
  27789. temp.push(alpha);
  27790. this.addUniform(name, temp);
  27791. };
  27792. /**
  27793. * Wrapper for addUniform.
  27794. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27795. * @param {Vector3} vector
  27796. */
  27797. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27798. var temp = new Array();
  27799. vector.toArray(temp);
  27800. this.addUniform(name, temp);
  27801. };
  27802. /**
  27803. * Wrapper for addUniform.
  27804. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27805. */
  27806. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27807. this.addUniform(name, 12);
  27808. };
  27809. /**
  27810. * Wrapper for addUniform.
  27811. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27812. */
  27813. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27814. this.addUniform(name, 8);
  27815. };
  27816. /**
  27817. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27818. */
  27819. UniformBuffer.prototype.create = function () {
  27820. if (this._noUBO) {
  27821. return;
  27822. }
  27823. if (this._buffer) {
  27824. return; // nothing to do
  27825. }
  27826. // See spec, alignment must be filled as a vec4
  27827. this._fillAlignment(4);
  27828. this._bufferData = new Float32Array(this._data);
  27829. this._rebuild();
  27830. this._needSync = true;
  27831. };
  27832. UniformBuffer.prototype._rebuild = function () {
  27833. if (this._noUBO) {
  27834. return;
  27835. }
  27836. if (this._dynamic) {
  27837. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27838. }
  27839. else {
  27840. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27841. }
  27842. };
  27843. /**
  27844. * Updates the WebGL Uniform Buffer on the GPU.
  27845. * If the `dynamic` flag is set to true, no cache comparison is done.
  27846. * Otherwise, the buffer will be updated only if the cache differs.
  27847. */
  27848. UniformBuffer.prototype.update = function () {
  27849. if (!this._buffer) {
  27850. this.create();
  27851. return;
  27852. }
  27853. if (!this._dynamic && !this._needSync) {
  27854. return;
  27855. }
  27856. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27857. this._needSync = false;
  27858. };
  27859. /**
  27860. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27861. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27862. * @param {number[]|Float32Array} data Flattened data
  27863. * @param {number} size Size of the data.
  27864. */
  27865. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27866. var location = this._uniformLocations[uniformName];
  27867. if (location === undefined) {
  27868. if (this._buffer) {
  27869. // Cannot add an uniform if the buffer is already created
  27870. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27871. return;
  27872. }
  27873. this.addUniform(uniformName, size);
  27874. location = this._uniformLocations[uniformName];
  27875. }
  27876. if (!this._buffer) {
  27877. this.create();
  27878. }
  27879. if (!this._dynamic) {
  27880. // Cache for static uniform buffers
  27881. var changed = false;
  27882. for (var i = 0; i < size; i++) {
  27883. if (this._bufferData[location + i] !== data[i]) {
  27884. changed = true;
  27885. this._bufferData[location + i] = data[i];
  27886. }
  27887. }
  27888. this._needSync = this._needSync || changed;
  27889. }
  27890. else {
  27891. // No cache for dynamic
  27892. for (var i = 0; i < size; i++) {
  27893. this._bufferData[location + i] = data[i];
  27894. }
  27895. }
  27896. };
  27897. // Update methods
  27898. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27899. // To match std140, matrix must be realigned
  27900. for (var i = 0; i < 3; i++) {
  27901. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27902. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27903. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27904. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27905. }
  27906. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27907. };
  27908. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27909. this._currentEffect.setMatrix3x3(name, matrix);
  27910. };
  27911. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27912. this._currentEffect.setMatrix2x2(name, matrix);
  27913. };
  27914. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27915. // To match std140, matrix must be realigned
  27916. for (var i = 0; i < 2; i++) {
  27917. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27918. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27919. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27920. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27921. }
  27922. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27923. };
  27924. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27925. this._currentEffect.setFloat(name, x);
  27926. };
  27927. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27928. UniformBuffer._tempBuffer[0] = x;
  27929. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27930. };
  27931. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27932. if (suffix === void 0) { suffix = ""; }
  27933. this._currentEffect.setFloat2(name + suffix, x, y);
  27934. };
  27935. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27936. if (suffix === void 0) { suffix = ""; }
  27937. UniformBuffer._tempBuffer[0] = x;
  27938. UniformBuffer._tempBuffer[1] = y;
  27939. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27940. };
  27941. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27942. if (suffix === void 0) { suffix = ""; }
  27943. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27944. };
  27945. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27946. if (suffix === void 0) { suffix = ""; }
  27947. UniformBuffer._tempBuffer[0] = x;
  27948. UniformBuffer._tempBuffer[1] = y;
  27949. UniformBuffer._tempBuffer[2] = z;
  27950. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27951. };
  27952. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27953. if (suffix === void 0) { suffix = ""; }
  27954. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27955. };
  27956. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27957. if (suffix === void 0) { suffix = ""; }
  27958. UniformBuffer._tempBuffer[0] = x;
  27959. UniformBuffer._tempBuffer[1] = y;
  27960. UniformBuffer._tempBuffer[2] = z;
  27961. UniformBuffer._tempBuffer[3] = w;
  27962. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27963. };
  27964. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27965. this._currentEffect.setMatrix(name, mat);
  27966. };
  27967. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27968. this.updateUniform(name, mat.toArray(), 16);
  27969. };
  27970. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27971. this._currentEffect.setVector3(name, vector);
  27972. };
  27973. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27974. vector.toArray(UniformBuffer._tempBuffer);
  27975. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27976. };
  27977. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27978. this._currentEffect.setVector4(name, vector);
  27979. };
  27980. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27981. vector.toArray(UniformBuffer._tempBuffer);
  27982. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27983. };
  27984. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27985. if (suffix === void 0) { suffix = ""; }
  27986. this._currentEffect.setColor3(name + suffix, color);
  27987. };
  27988. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27989. if (suffix === void 0) { suffix = ""; }
  27990. color.toArray(UniformBuffer._tempBuffer);
  27991. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27992. };
  27993. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27994. if (suffix === void 0) { suffix = ""; }
  27995. this._currentEffect.setColor4(name + suffix, color, alpha);
  27996. };
  27997. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27998. if (suffix === void 0) { suffix = ""; }
  27999. color.toArray(UniformBuffer._tempBuffer);
  28000. UniformBuffer._tempBuffer[3] = alpha;
  28001. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28002. };
  28003. /**
  28004. * Sets a sampler uniform on the effect.
  28005. * @param {string} name Name of the sampler.
  28006. * @param {Texture} texture
  28007. */
  28008. UniformBuffer.prototype.setTexture = function (name, texture) {
  28009. this._currentEffect.setTexture(name, texture);
  28010. };
  28011. /**
  28012. * Directly updates the value of the uniform in the cache AND on the GPU.
  28013. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28014. * @param {number[]|Float32Array} data Flattened data
  28015. */
  28016. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28017. this.updateUniform(uniformName, data, data.length);
  28018. this.update();
  28019. };
  28020. /**
  28021. * Binds this uniform buffer to an effect.
  28022. * @param {Effect} effect
  28023. * @param {string} name Name of the uniform block in the shader.
  28024. */
  28025. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28026. this._currentEffect = effect;
  28027. if (this._noUBO || !this._buffer) {
  28028. return;
  28029. }
  28030. effect.bindUniformBuffer(this._buffer, name);
  28031. };
  28032. /**
  28033. * Disposes the uniform buffer.
  28034. */
  28035. UniformBuffer.prototype.dispose = function () {
  28036. if (this._noUBO) {
  28037. return;
  28038. }
  28039. var index = this._engine._uniformBuffers.indexOf(this);
  28040. if (index !== -1) {
  28041. this._engine._uniformBuffers.splice(index, 1);
  28042. }
  28043. if (!this._buffer) {
  28044. return;
  28045. }
  28046. if (this._engine._releaseBuffer(this._buffer)) {
  28047. this._buffer = null;
  28048. }
  28049. };
  28050. // Pool for avoiding memory leaks
  28051. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28052. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28053. return UniformBuffer;
  28054. }());
  28055. BABYLON.UniformBuffer = UniformBuffer;
  28056. })(BABYLON || (BABYLON = {}));
  28057. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28058. var BABYLON;
  28059. (function (BABYLON) {
  28060. var PushMaterial = /** @class */ (function (_super) {
  28061. __extends(PushMaterial, _super);
  28062. function PushMaterial(name, scene) {
  28063. var _this = _super.call(this, name, scene) || this;
  28064. _this.storeEffectOnSubMeshes = true;
  28065. return _this;
  28066. }
  28067. PushMaterial.prototype.getEffect = function () {
  28068. return this._activeEffect;
  28069. };
  28070. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28071. if (!mesh) {
  28072. return false;
  28073. }
  28074. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28075. return true;
  28076. }
  28077. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28078. };
  28079. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28080. this._activeEffect.setMatrix("world", world);
  28081. };
  28082. PushMaterial.prototype.bind = function (world, mesh) {
  28083. if (!mesh) {
  28084. return;
  28085. }
  28086. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28087. };
  28088. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28089. if (effect === void 0) { effect = null; }
  28090. _super.prototype._afterBind.call(this, mesh);
  28091. this.getScene()._cachedEffect = effect;
  28092. };
  28093. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28094. if (visibility === void 0) { visibility = 1; }
  28095. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28096. };
  28097. return PushMaterial;
  28098. }(BABYLON.Material));
  28099. BABYLON.PushMaterial = PushMaterial;
  28100. })(BABYLON || (BABYLON = {}));
  28101. //# sourceMappingURL=babylon.pushMaterial.js.map
  28102. var BABYLON;
  28103. (function (BABYLON) {
  28104. var VertexData = /** @class */ (function () {
  28105. function VertexData() {
  28106. }
  28107. VertexData.prototype.set = function (data, kind) {
  28108. switch (kind) {
  28109. case BABYLON.VertexBuffer.PositionKind:
  28110. this.positions = data;
  28111. break;
  28112. case BABYLON.VertexBuffer.NormalKind:
  28113. this.normals = data;
  28114. break;
  28115. case BABYLON.VertexBuffer.TangentKind:
  28116. this.tangents = data;
  28117. break;
  28118. case BABYLON.VertexBuffer.UVKind:
  28119. this.uvs = data;
  28120. break;
  28121. case BABYLON.VertexBuffer.UV2Kind:
  28122. this.uvs2 = data;
  28123. break;
  28124. case BABYLON.VertexBuffer.UV3Kind:
  28125. this.uvs3 = data;
  28126. break;
  28127. case BABYLON.VertexBuffer.UV4Kind:
  28128. this.uvs4 = data;
  28129. break;
  28130. case BABYLON.VertexBuffer.UV5Kind:
  28131. this.uvs5 = data;
  28132. break;
  28133. case BABYLON.VertexBuffer.UV6Kind:
  28134. this.uvs6 = data;
  28135. break;
  28136. case BABYLON.VertexBuffer.ColorKind:
  28137. this.colors = data;
  28138. break;
  28139. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28140. this.matricesIndices = data;
  28141. break;
  28142. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28143. this.matricesWeights = data;
  28144. break;
  28145. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28146. this.matricesIndicesExtra = data;
  28147. break;
  28148. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28149. this.matricesWeightsExtra = data;
  28150. break;
  28151. }
  28152. };
  28153. /**
  28154. * Associates the vertexData to the passed Mesh.
  28155. * Sets it as updatable or not (default `false`).
  28156. * Returns the VertexData.
  28157. */
  28158. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28159. this._applyTo(mesh, updatable);
  28160. return this;
  28161. };
  28162. /**
  28163. * Associates the vertexData to the passed Geometry.
  28164. * Sets it as updatable or not (default `false`).
  28165. * Returns the VertexData.
  28166. */
  28167. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28168. this._applyTo(geometry, updatable);
  28169. return this;
  28170. };
  28171. /**
  28172. * Updates the associated mesh.
  28173. * Returns the VertexData.
  28174. */
  28175. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28176. this._update(mesh);
  28177. return this;
  28178. };
  28179. /**
  28180. * Updates the associated geometry.
  28181. * Returns the VertexData.
  28182. */
  28183. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28184. this._update(geometry);
  28185. return this;
  28186. };
  28187. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28188. if (updatable === void 0) { updatable = false; }
  28189. if (this.positions) {
  28190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28191. }
  28192. if (this.normals) {
  28193. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28194. }
  28195. if (this.tangents) {
  28196. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28197. }
  28198. if (this.uvs) {
  28199. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28200. }
  28201. if (this.uvs2) {
  28202. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28203. }
  28204. if (this.uvs3) {
  28205. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28206. }
  28207. if (this.uvs4) {
  28208. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28209. }
  28210. if (this.uvs5) {
  28211. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28212. }
  28213. if (this.uvs6) {
  28214. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28215. }
  28216. if (this.colors) {
  28217. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28218. }
  28219. if (this.matricesIndices) {
  28220. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28221. }
  28222. if (this.matricesWeights) {
  28223. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28224. }
  28225. if (this.matricesIndicesExtra) {
  28226. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28227. }
  28228. if (this.matricesWeightsExtra) {
  28229. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28230. }
  28231. if (this.indices) {
  28232. meshOrGeometry.setIndices(this.indices, null, updatable);
  28233. }
  28234. return this;
  28235. };
  28236. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28237. if (this.positions) {
  28238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28239. }
  28240. if (this.normals) {
  28241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28242. }
  28243. if (this.tangents) {
  28244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28245. }
  28246. if (this.uvs) {
  28247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28248. }
  28249. if (this.uvs2) {
  28250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28251. }
  28252. if (this.uvs3) {
  28253. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28254. }
  28255. if (this.uvs4) {
  28256. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28257. }
  28258. if (this.uvs5) {
  28259. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28260. }
  28261. if (this.uvs6) {
  28262. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28263. }
  28264. if (this.colors) {
  28265. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28266. }
  28267. if (this.matricesIndices) {
  28268. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28269. }
  28270. if (this.matricesWeights) {
  28271. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28272. }
  28273. if (this.matricesIndicesExtra) {
  28274. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28275. }
  28276. if (this.matricesWeightsExtra) {
  28277. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28278. }
  28279. if (this.indices) {
  28280. meshOrGeometry.setIndices(this.indices, null);
  28281. }
  28282. return this;
  28283. };
  28284. /**
  28285. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28286. * Returns the VertexData.
  28287. */
  28288. VertexData.prototype.transform = function (matrix) {
  28289. var transformed = BABYLON.Vector3.Zero();
  28290. var index;
  28291. if (this.positions) {
  28292. var position = BABYLON.Vector3.Zero();
  28293. for (index = 0; index < this.positions.length; index += 3) {
  28294. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28295. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28296. this.positions[index] = transformed.x;
  28297. this.positions[index + 1] = transformed.y;
  28298. this.positions[index + 2] = transformed.z;
  28299. }
  28300. }
  28301. if (this.normals) {
  28302. var normal = BABYLON.Vector3.Zero();
  28303. for (index = 0; index < this.normals.length; index += 3) {
  28304. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28305. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28306. this.normals[index] = transformed.x;
  28307. this.normals[index + 1] = transformed.y;
  28308. this.normals[index + 2] = transformed.z;
  28309. }
  28310. }
  28311. if (this.tangents) {
  28312. var tangent = BABYLON.Vector4.Zero();
  28313. var tangentTransformed = BABYLON.Vector4.Zero();
  28314. for (index = 0; index < this.tangents.length; index += 4) {
  28315. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28316. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28317. this.tangents[index] = tangentTransformed.x;
  28318. this.tangents[index + 1] = tangentTransformed.y;
  28319. this.tangents[index + 2] = tangentTransformed.z;
  28320. this.tangents[index + 3] = tangentTransformed.w;
  28321. }
  28322. }
  28323. return this;
  28324. };
  28325. /**
  28326. * Merges the passed VertexData into the current one.
  28327. * Returns the modified VertexData.
  28328. */
  28329. VertexData.prototype.merge = function (other, options) {
  28330. options = options || {};
  28331. if (other.indices) {
  28332. if (!this.indices) {
  28333. this.indices = [];
  28334. }
  28335. var offset = this.positions ? this.positions.length / 3 : 0;
  28336. for (var index = 0; index < other.indices.length; index++) {
  28337. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28338. this.indices.push(other.indices[index] + offset);
  28339. }
  28340. }
  28341. this.positions = this._mergeElement(this.positions, other.positions);
  28342. if (!this.positions) {
  28343. return this;
  28344. }
  28345. var count = this.positions.length / 3;
  28346. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28347. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28348. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28349. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28350. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28351. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28352. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28353. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28354. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28355. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28356. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28357. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28358. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28359. return this;
  28360. };
  28361. VertexData.prototype._mergeElement = function (source, other, length) {
  28362. if (length === void 0) { length = 0; }
  28363. if (!other && !source) {
  28364. return null;
  28365. }
  28366. if (!other) {
  28367. return this._mergeElement(source, new Float32Array(source.length), length);
  28368. }
  28369. if (!source) {
  28370. if (length === 0 || length === other.length) {
  28371. return other;
  28372. }
  28373. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28374. }
  28375. var len = other.length + source.length;
  28376. var isSrcTypedArray = source instanceof Float32Array;
  28377. var isOthTypedArray = other instanceof Float32Array;
  28378. // use non-loop method when the source is Float32Array
  28379. if (isSrcTypedArray) {
  28380. var ret32 = new Float32Array(len);
  28381. ret32.set(source);
  28382. ret32.set(other, source.length);
  28383. return ret32;
  28384. // source is number[], when other is also use concat
  28385. }
  28386. else if (!isOthTypedArray) {
  28387. return source.concat(other);
  28388. // source is a number[], but other is a Float32Array, loop required
  28389. }
  28390. else {
  28391. var ret = source.slice(0); // copy source to a separate array
  28392. for (var i = 0, len = other.length; i < len; i++) {
  28393. ret.push(other[i]);
  28394. }
  28395. return ret;
  28396. }
  28397. };
  28398. /**
  28399. * Serializes the VertexData.
  28400. * Returns a serialized object.
  28401. */
  28402. VertexData.prototype.serialize = function () {
  28403. var serializationObject = this.serialize();
  28404. if (this.positions) {
  28405. serializationObject.positions = this.positions;
  28406. }
  28407. if (this.normals) {
  28408. serializationObject.normals = this.normals;
  28409. }
  28410. if (this.tangents) {
  28411. serializationObject.tangents = this.tangents;
  28412. }
  28413. if (this.uvs) {
  28414. serializationObject.uvs = this.uvs;
  28415. }
  28416. if (this.uvs2) {
  28417. serializationObject.uvs2 = this.uvs2;
  28418. }
  28419. if (this.uvs3) {
  28420. serializationObject.uvs3 = this.uvs3;
  28421. }
  28422. if (this.uvs4) {
  28423. serializationObject.uvs4 = this.uvs4;
  28424. }
  28425. if (this.uvs5) {
  28426. serializationObject.uvs5 = this.uvs5;
  28427. }
  28428. if (this.uvs6) {
  28429. serializationObject.uvs6 = this.uvs6;
  28430. }
  28431. if (this.colors) {
  28432. serializationObject.colors = this.colors;
  28433. }
  28434. if (this.matricesIndices) {
  28435. serializationObject.matricesIndices = this.matricesIndices;
  28436. serializationObject.matricesIndices._isExpanded = true;
  28437. }
  28438. if (this.matricesWeights) {
  28439. serializationObject.matricesWeights = this.matricesWeights;
  28440. }
  28441. if (this.matricesIndicesExtra) {
  28442. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28443. serializationObject.matricesIndicesExtra._isExpanded = true;
  28444. }
  28445. if (this.matricesWeightsExtra) {
  28446. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28447. }
  28448. serializationObject.indices = this.indices;
  28449. return serializationObject;
  28450. };
  28451. // Statics
  28452. /**
  28453. * Returns the object VertexData associated to the passed mesh.
  28454. */
  28455. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28456. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28457. };
  28458. /**
  28459. * Returns the object VertexData associated to the passed geometry.
  28460. */
  28461. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28462. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28463. };
  28464. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28465. var result = new VertexData();
  28466. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28467. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28468. }
  28469. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28470. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28471. }
  28472. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28473. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28474. }
  28475. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28476. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28477. }
  28478. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28479. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28480. }
  28481. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28482. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28483. }
  28484. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28485. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28486. }
  28487. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28488. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28489. }
  28490. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28491. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28492. }
  28493. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28494. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28495. }
  28496. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28497. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28498. }
  28499. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28500. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28501. }
  28502. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28503. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28504. }
  28505. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28506. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28507. }
  28508. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28509. return result;
  28510. };
  28511. /**
  28512. * Creates the vertexData of the Ribbon.
  28513. */
  28514. VertexData.CreateRibbon = function (options) {
  28515. var pathArray = options.pathArray;
  28516. var closeArray = options.closeArray || false;
  28517. var closePath = options.closePath || false;
  28518. var invertUV = options.invertUV || false;
  28519. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28520. var offset = options.offset || defaultOffset;
  28521. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28522. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28523. var customUV = options.uvs;
  28524. var customColors = options.colors;
  28525. var positions = [];
  28526. var indices = [];
  28527. var normals = [];
  28528. var uvs = [];
  28529. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28530. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28531. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28532. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28533. var minlg; // minimal length among all paths from pathArray
  28534. var lg = []; // array of path lengths : nb of vertex per path
  28535. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28536. var p; // path iterator
  28537. var i; // point iterator
  28538. var j; // point iterator
  28539. // if single path in pathArray
  28540. if (pathArray.length < 2) {
  28541. var ar1 = [];
  28542. var ar2 = [];
  28543. for (i = 0; i < pathArray[0].length - offset; i++) {
  28544. ar1.push(pathArray[0][i]);
  28545. ar2.push(pathArray[0][i + offset]);
  28546. }
  28547. pathArray = [ar1, ar2];
  28548. }
  28549. // positions and horizontal distances (u)
  28550. var idc = 0;
  28551. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28552. var path;
  28553. var l;
  28554. minlg = pathArray[0].length;
  28555. var vectlg;
  28556. var dist;
  28557. for (p = 0; p < pathArray.length; p++) {
  28558. uTotalDistance[p] = 0;
  28559. us[p] = [0];
  28560. path = pathArray[p];
  28561. l = path.length;
  28562. minlg = (minlg < l) ? minlg : l;
  28563. j = 0;
  28564. while (j < l) {
  28565. positions.push(path[j].x, path[j].y, path[j].z);
  28566. if (j > 0) {
  28567. vectlg = path[j].subtract(path[j - 1]).length();
  28568. dist = vectlg + uTotalDistance[p];
  28569. us[p].push(dist);
  28570. uTotalDistance[p] = dist;
  28571. }
  28572. j++;
  28573. }
  28574. if (closePath) {
  28575. j--;
  28576. positions.push(path[0].x, path[0].y, path[0].z);
  28577. vectlg = path[j].subtract(path[0]).length();
  28578. dist = vectlg + uTotalDistance[p];
  28579. us[p].push(dist);
  28580. uTotalDistance[p] = dist;
  28581. }
  28582. lg[p] = l + closePathCorr;
  28583. idx[p] = idc;
  28584. idc += (l + closePathCorr);
  28585. }
  28586. // vertical distances (v)
  28587. var path1;
  28588. var path2;
  28589. var vertex1 = null;
  28590. var vertex2 = null;
  28591. for (i = 0; i < minlg + closePathCorr; i++) {
  28592. vTotalDistance[i] = 0;
  28593. vs[i] = [0];
  28594. for (p = 0; p < pathArray.length - 1; p++) {
  28595. path1 = pathArray[p];
  28596. path2 = pathArray[p + 1];
  28597. if (i === minlg) {
  28598. vertex1 = path1[0];
  28599. vertex2 = path2[0];
  28600. }
  28601. else {
  28602. vertex1 = path1[i];
  28603. vertex2 = path2[i];
  28604. }
  28605. vectlg = vertex2.subtract(vertex1).length();
  28606. dist = vectlg + vTotalDistance[i];
  28607. vs[i].push(dist);
  28608. vTotalDistance[i] = dist;
  28609. }
  28610. if (closeArray && vertex2 && vertex1) {
  28611. path1 = pathArray[p];
  28612. path2 = pathArray[0];
  28613. if (i === minlg) {
  28614. vertex2 = path2[0];
  28615. }
  28616. vectlg = vertex2.subtract(vertex1).length();
  28617. dist = vectlg + vTotalDistance[i];
  28618. vTotalDistance[i] = dist;
  28619. }
  28620. }
  28621. // uvs
  28622. var u;
  28623. var v;
  28624. if (customUV) {
  28625. for (p = 0; p < customUV.length; p++) {
  28626. uvs.push(customUV[p].x, customUV[p].y);
  28627. }
  28628. }
  28629. else {
  28630. for (p = 0; p < pathArray.length; p++) {
  28631. for (i = 0; i < minlg + closePathCorr; i++) {
  28632. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28633. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28634. if (invertUV) {
  28635. uvs.push(v, u);
  28636. }
  28637. else {
  28638. uvs.push(u, v);
  28639. }
  28640. }
  28641. }
  28642. }
  28643. // indices
  28644. p = 0; // path index
  28645. var pi = 0; // positions array index
  28646. var l1 = lg[p] - 1; // path1 length
  28647. var l2 = lg[p + 1] - 1; // path2 length
  28648. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28649. var shft = idx[1] - idx[0]; // shift
  28650. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28651. while (pi <= min && p < path1nb) {
  28652. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  28653. indices.push(pi, pi + shft, pi + 1);
  28654. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28655. pi += 1;
  28656. if (pi === min) {
  28657. p++;
  28658. if (p === lg.length - 1) {
  28659. shft = idx[0] - idx[p];
  28660. l1 = lg[p] - 1;
  28661. l2 = lg[0] - 1;
  28662. }
  28663. else {
  28664. shft = idx[p + 1] - idx[p];
  28665. l1 = lg[p] - 1;
  28666. l2 = lg[p + 1] - 1;
  28667. }
  28668. pi = idx[p];
  28669. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28670. }
  28671. }
  28672. // normals
  28673. VertexData.ComputeNormals(positions, indices, normals);
  28674. if (closePath) {
  28675. var indexFirst = 0;
  28676. var indexLast = 0;
  28677. for (p = 0; p < pathArray.length; p++) {
  28678. indexFirst = idx[p] * 3;
  28679. if (p + 1 < pathArray.length) {
  28680. indexLast = (idx[p + 1] - 1) * 3;
  28681. }
  28682. else {
  28683. indexLast = normals.length - 3;
  28684. }
  28685. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28686. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28687. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28688. normals[indexLast] = normals[indexFirst];
  28689. normals[indexLast + 1] = normals[indexFirst + 1];
  28690. normals[indexLast + 2] = normals[indexFirst + 2];
  28691. }
  28692. }
  28693. // sides
  28694. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28695. // Colors
  28696. var colors = null;
  28697. if (customColors) {
  28698. colors = new Float32Array(customColors.length * 4);
  28699. for (var c = 0; c < customColors.length; c++) {
  28700. colors[c * 4] = customColors[c].r;
  28701. colors[c * 4 + 1] = customColors[c].g;
  28702. colors[c * 4 + 2] = customColors[c].b;
  28703. colors[c * 4 + 3] = customColors[c].a;
  28704. }
  28705. }
  28706. // Result
  28707. var vertexData = new VertexData();
  28708. var positions32 = new Float32Array(positions);
  28709. var normals32 = new Float32Array(normals);
  28710. var uvs32 = new Float32Array(uvs);
  28711. vertexData.indices = indices;
  28712. vertexData.positions = positions32;
  28713. vertexData.normals = normals32;
  28714. vertexData.uvs = uvs32;
  28715. if (colors) {
  28716. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28717. }
  28718. if (closePath) {
  28719. vertexData._idx = idx;
  28720. }
  28721. return vertexData;
  28722. };
  28723. /**
  28724. * Creates the VertexData of the Box.
  28725. */
  28726. VertexData.CreateBox = function (options) {
  28727. var normalsSource = [
  28728. new BABYLON.Vector3(0, 0, 1),
  28729. new BABYLON.Vector3(0, 0, -1),
  28730. new BABYLON.Vector3(1, 0, 0),
  28731. new BABYLON.Vector3(-1, 0, 0),
  28732. new BABYLON.Vector3(0, 1, 0),
  28733. new BABYLON.Vector3(0, -1, 0)
  28734. ];
  28735. var indices = [];
  28736. var positions = [];
  28737. var normals = [];
  28738. var uvs = [];
  28739. var width = options.width || options.size || 1;
  28740. var height = options.height || options.size || 1;
  28741. var depth = options.depth || options.size || 1;
  28742. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28743. var faceUV = options.faceUV || new Array(6);
  28744. var faceColors = options.faceColors;
  28745. var colors = [];
  28746. // default face colors and UV if undefined
  28747. for (var f = 0; f < 6; f++) {
  28748. if (faceUV[f] === undefined) {
  28749. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28750. }
  28751. if (faceColors && faceColors[f] === undefined) {
  28752. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28753. }
  28754. }
  28755. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28756. // Create each face in turn.
  28757. for (var index = 0; index < normalsSource.length; index++) {
  28758. var normal = normalsSource[index];
  28759. // Get two vectors perpendicular to the face normal and to each other.
  28760. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28761. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28762. // Six indices (two triangles) per face.
  28763. var verticesLength = positions.length / 3;
  28764. indices.push(verticesLength);
  28765. indices.push(verticesLength + 1);
  28766. indices.push(verticesLength + 2);
  28767. indices.push(verticesLength);
  28768. indices.push(verticesLength + 2);
  28769. indices.push(verticesLength + 3);
  28770. // Four vertices per face.
  28771. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28772. positions.push(vertex.x, vertex.y, vertex.z);
  28773. normals.push(normal.x, normal.y, normal.z);
  28774. uvs.push(faceUV[index].z, faceUV[index].w);
  28775. if (faceColors) {
  28776. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28777. }
  28778. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28779. positions.push(vertex.x, vertex.y, vertex.z);
  28780. normals.push(normal.x, normal.y, normal.z);
  28781. uvs.push(faceUV[index].x, faceUV[index].w);
  28782. if (faceColors) {
  28783. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28784. }
  28785. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28786. positions.push(vertex.x, vertex.y, vertex.z);
  28787. normals.push(normal.x, normal.y, normal.z);
  28788. uvs.push(faceUV[index].x, faceUV[index].y);
  28789. if (faceColors) {
  28790. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28791. }
  28792. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28793. positions.push(vertex.x, vertex.y, vertex.z);
  28794. normals.push(normal.x, normal.y, normal.z);
  28795. uvs.push(faceUV[index].z, faceUV[index].y);
  28796. if (faceColors) {
  28797. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28798. }
  28799. }
  28800. // sides
  28801. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28802. // Result
  28803. var vertexData = new VertexData();
  28804. vertexData.indices = indices;
  28805. vertexData.positions = positions;
  28806. vertexData.normals = normals;
  28807. vertexData.uvs = uvs;
  28808. if (faceColors) {
  28809. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28810. vertexData.colors = totalColors;
  28811. }
  28812. return vertexData;
  28813. };
  28814. /**
  28815. * Creates the VertexData of the Sphere.
  28816. */
  28817. VertexData.CreateSphere = function (options) {
  28818. var segments = options.segments || 32;
  28819. var diameterX = options.diameterX || options.diameter || 1;
  28820. var diameterY = options.diameterY || options.diameter || 1;
  28821. var diameterZ = options.diameterZ || options.diameter || 1;
  28822. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28823. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28824. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28825. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28826. var totalZRotationSteps = 2 + segments;
  28827. var totalYRotationSteps = 2 * totalZRotationSteps;
  28828. var indices = [];
  28829. var positions = [];
  28830. var normals = [];
  28831. var uvs = [];
  28832. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28833. var normalizedZ = zRotationStep / totalZRotationSteps;
  28834. var angleZ = normalizedZ * Math.PI * slice;
  28835. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28836. var normalizedY = yRotationStep / totalYRotationSteps;
  28837. var angleY = normalizedY * Math.PI * 2 * arc;
  28838. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28839. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28840. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28841. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28842. var vertex = complete.multiply(radius);
  28843. var normal = complete.divide(radius).normalize();
  28844. positions.push(vertex.x, vertex.y, vertex.z);
  28845. normals.push(normal.x, normal.y, normal.z);
  28846. uvs.push(normalizedY, normalizedZ);
  28847. }
  28848. if (zRotationStep > 0) {
  28849. var verticesCount = positions.length / 3;
  28850. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28851. indices.push((firstIndex));
  28852. indices.push((firstIndex + 1));
  28853. indices.push(firstIndex + totalYRotationSteps + 1);
  28854. indices.push((firstIndex + totalYRotationSteps + 1));
  28855. indices.push((firstIndex + 1));
  28856. indices.push((firstIndex + totalYRotationSteps + 2));
  28857. }
  28858. }
  28859. }
  28860. // Sides
  28861. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28862. // Result
  28863. var vertexData = new VertexData();
  28864. vertexData.indices = indices;
  28865. vertexData.positions = positions;
  28866. vertexData.normals = normals;
  28867. vertexData.uvs = uvs;
  28868. return vertexData;
  28869. };
  28870. /**
  28871. * Creates the VertexData of the Cylinder or Cone.
  28872. */
  28873. VertexData.CreateCylinder = function (options) {
  28874. var height = options.height || 2;
  28875. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28876. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28877. var tessellation = options.tessellation || 24;
  28878. var subdivisions = options.subdivisions || 1;
  28879. var hasRings = options.hasRings ? true : false;
  28880. var enclose = options.enclose ? true : false;
  28881. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28882. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28883. var faceUV = options.faceUV || new Array(3);
  28884. var faceColors = options.faceColors;
  28885. // default face colors and UV if undefined
  28886. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28887. var ringNb = (hasRings) ? subdivisions : 1;
  28888. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28889. var f;
  28890. for (f = 0; f < surfaceNb; f++) {
  28891. if (faceColors && faceColors[f] === undefined) {
  28892. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28893. }
  28894. }
  28895. for (f = 0; f < surfaceNb; f++) {
  28896. if (faceUV && faceUV[f] === undefined) {
  28897. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28898. }
  28899. }
  28900. var indices = new Array();
  28901. var positions = new Array();
  28902. var normals = new Array();
  28903. var uvs = new Array();
  28904. var colors = new Array();
  28905. var angle_step = Math.PI * 2 * arc / tessellation;
  28906. var angle;
  28907. var h;
  28908. var radius;
  28909. var tan = (diameterBottom - diameterTop) / 2 / height;
  28910. var ringVertex = BABYLON.Vector3.Zero();
  28911. var ringNormal = BABYLON.Vector3.Zero();
  28912. var ringFirstVertex = BABYLON.Vector3.Zero();
  28913. var ringFirstNormal = BABYLON.Vector3.Zero();
  28914. var quadNormal = BABYLON.Vector3.Zero();
  28915. var Y = BABYLON.Axis.Y;
  28916. // positions, normals, uvs
  28917. var i;
  28918. var j;
  28919. var r;
  28920. var ringIdx = 1;
  28921. var s = 1; // surface index
  28922. var cs = 0;
  28923. var v = 0;
  28924. for (i = 0; i <= subdivisions; i++) {
  28925. h = i / subdivisions;
  28926. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28927. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28928. for (r = 0; r < ringIdx; r++) {
  28929. if (hasRings) {
  28930. s += r;
  28931. }
  28932. if (enclose) {
  28933. s += 2 * r;
  28934. }
  28935. for (j = 0; j <= tessellation; j++) {
  28936. angle = j * angle_step;
  28937. // position
  28938. ringVertex.x = Math.cos(-angle) * radius;
  28939. ringVertex.y = -height / 2 + h * height;
  28940. ringVertex.z = Math.sin(-angle) * radius;
  28941. // normal
  28942. if (diameterTop === 0 && i === subdivisions) {
  28943. // if no top cap, reuse former normals
  28944. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28945. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28946. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28947. }
  28948. else {
  28949. ringNormal.x = ringVertex.x;
  28950. ringNormal.z = ringVertex.z;
  28951. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28952. ringNormal.normalize();
  28953. }
  28954. // keep first ring vertex values for enclose
  28955. if (j === 0) {
  28956. ringFirstVertex.copyFrom(ringVertex);
  28957. ringFirstNormal.copyFrom(ringNormal);
  28958. }
  28959. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28960. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28961. if (hasRings) {
  28962. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28963. }
  28964. else {
  28965. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28966. }
  28967. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28968. if (faceColors) {
  28969. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28970. }
  28971. }
  28972. // if enclose, add four vertices and their dedicated normals
  28973. if (arc !== 1 && enclose) {
  28974. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28975. positions.push(0, ringVertex.y, 0);
  28976. positions.push(0, ringVertex.y, 0);
  28977. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28978. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28979. quadNormal.normalize();
  28980. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28981. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28982. quadNormal.normalize();
  28983. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28984. if (hasRings) {
  28985. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28986. }
  28987. else {
  28988. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28989. }
  28990. uvs.push(faceUV[s + 1].x, v);
  28991. uvs.push(faceUV[s + 1].z, v);
  28992. if (hasRings) {
  28993. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28994. }
  28995. else {
  28996. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28997. }
  28998. uvs.push(faceUV[s + 2].x, v);
  28999. uvs.push(faceUV[s + 2].z, v);
  29000. if (faceColors) {
  29001. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29002. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29003. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29004. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29005. }
  29006. }
  29007. if (cs !== s) {
  29008. cs = s;
  29009. }
  29010. }
  29011. }
  29012. // indices
  29013. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29014. var s;
  29015. i = 0;
  29016. for (s = 0; s < subdivisions; s++) {
  29017. var i0 = 0;
  29018. var i1 = 0;
  29019. var i2 = 0;
  29020. var i3 = 0;
  29021. for (j = 0; j < tessellation; j++) {
  29022. i0 = i * (e + 1) + j;
  29023. i1 = (i + 1) * (e + 1) + j;
  29024. i2 = i * (e + 1) + (j + 1);
  29025. i3 = (i + 1) * (e + 1) + (j + 1);
  29026. indices.push(i0, i1, i2);
  29027. indices.push(i3, i2, i1);
  29028. }
  29029. if (arc !== 1 && enclose) {
  29030. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29031. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29032. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29033. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29034. }
  29035. i = (hasRings) ? (i + 2) : (i + 1);
  29036. }
  29037. // Caps
  29038. var createCylinderCap = function (isTop) {
  29039. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29040. if (radius === 0) {
  29041. return;
  29042. }
  29043. // Cap positions, normals & uvs
  29044. var angle;
  29045. var circleVector;
  29046. var i;
  29047. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29048. var c = null;
  29049. if (faceColors) {
  29050. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29051. }
  29052. // cap center
  29053. var vbase = positions.length / 3;
  29054. var offset = isTop ? height / 2 : -height / 2;
  29055. var center = new BABYLON.Vector3(0, offset, 0);
  29056. positions.push(center.x, center.y, center.z);
  29057. normals.push(0, isTop ? 1 : -1, 0);
  29058. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29059. if (c) {
  29060. colors.push(c.r, c.g, c.b, c.a);
  29061. }
  29062. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29063. for (i = 0; i <= tessellation; i++) {
  29064. angle = Math.PI * 2 * i * arc / tessellation;
  29065. var cos = Math.cos(-angle);
  29066. var sin = Math.sin(-angle);
  29067. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29068. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29069. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29070. normals.push(0, isTop ? 1 : -1, 0);
  29071. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29072. if (c) {
  29073. colors.push(c.r, c.g, c.b, c.a);
  29074. }
  29075. }
  29076. // Cap indices
  29077. for (i = 0; i < tessellation; i++) {
  29078. if (!isTop) {
  29079. indices.push(vbase);
  29080. indices.push(vbase + (i + 1));
  29081. indices.push(vbase + (i + 2));
  29082. }
  29083. else {
  29084. indices.push(vbase);
  29085. indices.push(vbase + (i + 2));
  29086. indices.push(vbase + (i + 1));
  29087. }
  29088. }
  29089. };
  29090. // add caps to geometry
  29091. createCylinderCap(false);
  29092. createCylinderCap(true);
  29093. // Sides
  29094. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29095. var vertexData = new VertexData();
  29096. vertexData.indices = indices;
  29097. vertexData.positions = positions;
  29098. vertexData.normals = normals;
  29099. vertexData.uvs = uvs;
  29100. if (faceColors) {
  29101. vertexData.colors = colors;
  29102. }
  29103. return vertexData;
  29104. };
  29105. /**
  29106. * Creates the VertexData of the Torus.
  29107. */
  29108. VertexData.CreateTorus = function (options) {
  29109. var indices = [];
  29110. var positions = [];
  29111. var normals = [];
  29112. var uvs = [];
  29113. var diameter = options.diameter || 1;
  29114. var thickness = options.thickness || 0.5;
  29115. var tessellation = options.tessellation || 16;
  29116. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29117. var stride = tessellation + 1;
  29118. for (var i = 0; i <= tessellation; i++) {
  29119. var u = i / tessellation;
  29120. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29121. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29122. for (var j = 0; j <= tessellation; j++) {
  29123. var v = 1 - j / tessellation;
  29124. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29125. var dx = Math.cos(innerAngle);
  29126. var dy = Math.sin(innerAngle);
  29127. // Create a vertex.
  29128. var normal = new BABYLON.Vector3(dx, dy, 0);
  29129. var position = normal.scale(thickness / 2);
  29130. var textureCoordinate = new BABYLON.Vector2(u, v);
  29131. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29132. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29133. positions.push(position.x, position.y, position.z);
  29134. normals.push(normal.x, normal.y, normal.z);
  29135. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29136. // And create indices for two triangles.
  29137. var nextI = (i + 1) % stride;
  29138. var nextJ = (j + 1) % stride;
  29139. indices.push(i * stride + j);
  29140. indices.push(i * stride + nextJ);
  29141. indices.push(nextI * stride + j);
  29142. indices.push(i * stride + nextJ);
  29143. indices.push(nextI * stride + nextJ);
  29144. indices.push(nextI * stride + j);
  29145. }
  29146. }
  29147. // Sides
  29148. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29149. // Result
  29150. var vertexData = new VertexData();
  29151. vertexData.indices = indices;
  29152. vertexData.positions = positions;
  29153. vertexData.normals = normals;
  29154. vertexData.uvs = uvs;
  29155. return vertexData;
  29156. };
  29157. /**
  29158. * Creates the VertexData of the LineSystem.
  29159. */
  29160. VertexData.CreateLineSystem = function (options) {
  29161. var indices = [];
  29162. var positions = [];
  29163. var lines = options.lines;
  29164. var idx = 0;
  29165. for (var l = 0; l < lines.length; l++) {
  29166. var points = lines[l];
  29167. for (var index = 0; index < points.length; index++) {
  29168. positions.push(points[index].x, points[index].y, points[index].z);
  29169. if (index > 0) {
  29170. indices.push(idx - 1);
  29171. indices.push(idx);
  29172. }
  29173. idx++;
  29174. }
  29175. }
  29176. var vertexData = new VertexData();
  29177. vertexData.indices = indices;
  29178. vertexData.positions = positions;
  29179. return vertexData;
  29180. };
  29181. /**
  29182. * Create the VertexData of the DashedLines.
  29183. */
  29184. VertexData.CreateDashedLines = function (options) {
  29185. var dashSize = options.dashSize || 3;
  29186. var gapSize = options.gapSize || 1;
  29187. var dashNb = options.dashNb || 200;
  29188. var points = options.points;
  29189. var positions = new Array();
  29190. var indices = new Array();
  29191. var curvect = BABYLON.Vector3.Zero();
  29192. var lg = 0;
  29193. var nb = 0;
  29194. var shft = 0;
  29195. var dashshft = 0;
  29196. var curshft = 0;
  29197. var idx = 0;
  29198. var i = 0;
  29199. for (i = 0; i < points.length - 1; i++) {
  29200. points[i + 1].subtractToRef(points[i], curvect);
  29201. lg += curvect.length();
  29202. }
  29203. shft = lg / dashNb;
  29204. dashshft = dashSize * shft / (dashSize + gapSize);
  29205. for (i = 0; i < points.length - 1; i++) {
  29206. points[i + 1].subtractToRef(points[i], curvect);
  29207. nb = Math.floor(curvect.length() / shft);
  29208. curvect.normalize();
  29209. for (var j = 0; j < nb; j++) {
  29210. curshft = shft * j;
  29211. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29212. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29213. indices.push(idx, idx + 1);
  29214. idx += 2;
  29215. }
  29216. }
  29217. // Result
  29218. var vertexData = new VertexData();
  29219. vertexData.positions = positions;
  29220. vertexData.indices = indices;
  29221. return vertexData;
  29222. };
  29223. /**
  29224. * Creates the VertexData of the Ground.
  29225. */
  29226. VertexData.CreateGround = function (options) {
  29227. var indices = [];
  29228. var positions = [];
  29229. var normals = [];
  29230. var uvs = [];
  29231. var row, col;
  29232. var width = options.width || 1;
  29233. var height = options.height || 1;
  29234. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29235. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29236. for (row = 0; row <= subdivisionsY; row++) {
  29237. for (col = 0; col <= subdivisionsX; col++) {
  29238. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29239. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29240. positions.push(position.x, position.y, position.z);
  29241. normals.push(normal.x, normal.y, normal.z);
  29242. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29243. }
  29244. }
  29245. for (row = 0; row < subdivisionsY; row++) {
  29246. for (col = 0; col < subdivisionsX; col++) {
  29247. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29248. indices.push(col + 1 + row * (subdivisionsX + 1));
  29249. indices.push(col + row * (subdivisionsX + 1));
  29250. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29251. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29252. indices.push(col + row * (subdivisionsX + 1));
  29253. }
  29254. }
  29255. // Result
  29256. var vertexData = new VertexData();
  29257. vertexData.indices = indices;
  29258. vertexData.positions = positions;
  29259. vertexData.normals = normals;
  29260. vertexData.uvs = uvs;
  29261. return vertexData;
  29262. };
  29263. /**
  29264. * Creates the VertexData of the TiledGround.
  29265. */
  29266. VertexData.CreateTiledGround = function (options) {
  29267. var xmin = options.xmin || -1.0;
  29268. var zmin = options.zmin || -1.0;
  29269. var xmax = options.xmax || 1.0;
  29270. var zmax = options.zmax || 1.0;
  29271. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29272. var precision = options.precision || { w: 1, h: 1 };
  29273. var indices = new Array();
  29274. var positions = new Array();
  29275. var normals = new Array();
  29276. var uvs = new Array();
  29277. var row, col, tileRow, tileCol;
  29278. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29279. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29280. precision.w = (precision.w < 1) ? 1 : precision.w;
  29281. precision.h = (precision.h < 1) ? 1 : precision.h;
  29282. var tileSize = {
  29283. 'w': (xmax - xmin) / subdivisions.w,
  29284. 'h': (zmax - zmin) / subdivisions.h
  29285. };
  29286. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29287. // Indices
  29288. var base = positions.length / 3;
  29289. var rowLength = precision.w + 1;
  29290. for (row = 0; row < precision.h; row++) {
  29291. for (col = 0; col < precision.w; col++) {
  29292. var square = [
  29293. base + col + row * rowLength,
  29294. base + (col + 1) + row * rowLength,
  29295. base + (col + 1) + (row + 1) * rowLength,
  29296. base + col + (row + 1) * rowLength
  29297. ];
  29298. indices.push(square[1]);
  29299. indices.push(square[2]);
  29300. indices.push(square[3]);
  29301. indices.push(square[0]);
  29302. indices.push(square[1]);
  29303. indices.push(square[3]);
  29304. }
  29305. }
  29306. // Position, normals and uvs
  29307. var position = BABYLON.Vector3.Zero();
  29308. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29309. for (row = 0; row <= precision.h; row++) {
  29310. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29311. for (col = 0; col <= precision.w; col++) {
  29312. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29313. position.y = 0;
  29314. positions.push(position.x, position.y, position.z);
  29315. normals.push(normal.x, normal.y, normal.z);
  29316. uvs.push(col / precision.w, row / precision.h);
  29317. }
  29318. }
  29319. }
  29320. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29321. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29322. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29323. }
  29324. }
  29325. // Result
  29326. var vertexData = new VertexData();
  29327. vertexData.indices = indices;
  29328. vertexData.positions = positions;
  29329. vertexData.normals = normals;
  29330. vertexData.uvs = uvs;
  29331. return vertexData;
  29332. };
  29333. /**
  29334. * Creates the VertexData of the Ground designed from a heightmap.
  29335. */
  29336. VertexData.CreateGroundFromHeightMap = function (options) {
  29337. var indices = [];
  29338. var positions = [];
  29339. var normals = [];
  29340. var uvs = [];
  29341. var row, col;
  29342. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29343. // Vertices
  29344. for (row = 0; row <= options.subdivisions; row++) {
  29345. for (col = 0; col <= options.subdivisions; col++) {
  29346. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  29347. // Compute height
  29348. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29349. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29350. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29351. var r = options.buffer[pos] / 255.0;
  29352. var g = options.buffer[pos + 1] / 255.0;
  29353. var b = options.buffer[pos + 2] / 255.0;
  29354. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29355. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29356. // Add vertex
  29357. positions.push(position.x, position.y, position.z);
  29358. normals.push(0, 0, 0);
  29359. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29360. }
  29361. }
  29362. // Indices
  29363. for (row = 0; row < options.subdivisions; row++) {
  29364. for (col = 0; col < options.subdivisions; col++) {
  29365. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29366. indices.push(col + 1 + row * (options.subdivisions + 1));
  29367. indices.push(col + row * (options.subdivisions + 1));
  29368. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29369. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29370. indices.push(col + row * (options.subdivisions + 1));
  29371. }
  29372. }
  29373. // Normals
  29374. VertexData.ComputeNormals(positions, indices, normals);
  29375. // Result
  29376. var vertexData = new VertexData();
  29377. vertexData.indices = indices;
  29378. vertexData.positions = positions;
  29379. vertexData.normals = normals;
  29380. vertexData.uvs = uvs;
  29381. return vertexData;
  29382. };
  29383. /**
  29384. * Creates the VertexData of the Plane.
  29385. */
  29386. VertexData.CreatePlane = function (options) {
  29387. var indices = [];
  29388. var positions = [];
  29389. var normals = [];
  29390. var uvs = [];
  29391. var width = options.width || options.size || 1;
  29392. var height = options.height || options.size || 1;
  29393. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29394. // Vertices
  29395. var halfWidth = width / 2.0;
  29396. var halfHeight = height / 2.0;
  29397. positions.push(-halfWidth, -halfHeight, 0);
  29398. normals.push(0, 0, -1.0);
  29399. uvs.push(0.0, 0.0);
  29400. positions.push(halfWidth, -halfHeight, 0);
  29401. normals.push(0, 0, -1.0);
  29402. uvs.push(1.0, 0.0);
  29403. positions.push(halfWidth, halfHeight, 0);
  29404. normals.push(0, 0, -1.0);
  29405. uvs.push(1.0, 1.0);
  29406. positions.push(-halfWidth, halfHeight, 0);
  29407. normals.push(0, 0, -1.0);
  29408. uvs.push(0.0, 1.0);
  29409. // Indices
  29410. indices.push(0);
  29411. indices.push(1);
  29412. indices.push(2);
  29413. indices.push(0);
  29414. indices.push(2);
  29415. indices.push(3);
  29416. // Sides
  29417. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29418. // Result
  29419. var vertexData = new VertexData();
  29420. vertexData.indices = indices;
  29421. vertexData.positions = positions;
  29422. vertexData.normals = normals;
  29423. vertexData.uvs = uvs;
  29424. return vertexData;
  29425. };
  29426. /**
  29427. * Creates the VertexData of the Disc or regular Polygon.
  29428. */
  29429. VertexData.CreateDisc = function (options) {
  29430. var positions = new Array();
  29431. var indices = new Array();
  29432. var normals = new Array();
  29433. var uvs = new Array();
  29434. var radius = options.radius || 0.5;
  29435. var tessellation = options.tessellation || 64;
  29436. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29437. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29438. // positions and uvs
  29439. positions.push(0, 0, 0); // disc center first
  29440. uvs.push(0.5, 0.5);
  29441. var theta = Math.PI * 2 * arc;
  29442. var step = theta / tessellation;
  29443. for (var a = 0; a < theta; a += step) {
  29444. var x = Math.cos(a);
  29445. var y = Math.sin(a);
  29446. var u = (x + 1) / 2;
  29447. var v = (1 - y) / 2;
  29448. positions.push(radius * x, radius * y, 0);
  29449. uvs.push(u, v);
  29450. }
  29451. if (arc === 1) {
  29452. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29453. uvs.push(uvs[2], uvs[3]);
  29454. }
  29455. //indices
  29456. var vertexNb = positions.length / 3;
  29457. for (var i = 1; i < vertexNb - 1; i++) {
  29458. indices.push(i + 1, 0, i);
  29459. }
  29460. // result
  29461. VertexData.ComputeNormals(positions, indices, normals);
  29462. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29463. var vertexData = new VertexData();
  29464. vertexData.indices = indices;
  29465. vertexData.positions = positions;
  29466. vertexData.normals = normals;
  29467. vertexData.uvs = uvs;
  29468. return vertexData;
  29469. };
  29470. /**
  29471. * Re-creates the VertexData of the Polygon for sideOrientation.
  29472. */
  29473. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29474. var faceUV = fUV || new Array(3);
  29475. var faceColors = fColors;
  29476. var colors = [];
  29477. // default face colors and UV if undefined
  29478. for (var f = 0; f < 3; f++) {
  29479. if (faceUV[f] === undefined) {
  29480. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29481. }
  29482. if (faceColors && faceColors[f] === undefined) {
  29483. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29484. }
  29485. }
  29486. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29487. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29488. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29489. var indices = polygon.getIndices();
  29490. // set face colours and textures
  29491. var idx = 0;
  29492. var face = 0;
  29493. for (var index = 0; index < normals.length; index += 3) {
  29494. //Edge Face no. 1
  29495. if (Math.abs(normals[index + 1]) < 0.001) {
  29496. face = 1;
  29497. }
  29498. //Top Face no. 0
  29499. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29500. face = 0;
  29501. }
  29502. //Bottom Face no. 2
  29503. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29504. face = 2;
  29505. }
  29506. idx = index / 3;
  29507. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29508. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29509. if (faceColors) {
  29510. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29511. }
  29512. }
  29513. // sides
  29514. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29515. // Result
  29516. var vertexData = new VertexData();
  29517. vertexData.indices = indices;
  29518. vertexData.positions = positions;
  29519. vertexData.normals = normals;
  29520. vertexData.uvs = uvs;
  29521. if (faceColors) {
  29522. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29523. vertexData.colors = totalColors;
  29524. }
  29525. return vertexData;
  29526. };
  29527. /**
  29528. * Creates the VertexData of the IcoSphere.
  29529. */
  29530. VertexData.CreateIcoSphere = function (options) {
  29531. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29532. var radius = options.radius || 1;
  29533. var flat = (options.flat === undefined) ? true : options.flat;
  29534. var subdivisions = options.subdivisions || 4;
  29535. var radiusX = options.radiusX || radius;
  29536. var radiusY = options.radiusY || radius;
  29537. var radiusZ = options.radiusZ || radius;
  29538. var t = (1 + Math.sqrt(5)) / 2;
  29539. // 12 vertex x,y,z
  29540. var ico_vertices = [
  29541. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29542. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29543. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29544. ];
  29545. // index of 3 vertex makes a face of icopshere
  29546. var ico_indices = [
  29547. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29548. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29549. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29550. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29551. ];
  29552. // vertex for uv have aliased position, not for UV
  29553. var vertices_unalias_id = [
  29554. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29555. // vertex alias
  29556. 0,
  29557. 2,
  29558. 3,
  29559. 3,
  29560. 3,
  29561. 4,
  29562. 7,
  29563. 8,
  29564. 9,
  29565. 9,
  29566. 10,
  29567. 11 // 23: B + 12
  29568. ];
  29569. // uv as integer step (not pixels !)
  29570. var ico_vertexuv = [
  29571. 5, 1, 3, 1, 6, 4, 0, 0,
  29572. 5, 3, 4, 2, 2, 2, 4, 0,
  29573. 2, 0, 1, 1, 6, 0, 6, 2,
  29574. // vertex alias (for same vertex on different faces)
  29575. 0, 4,
  29576. 3, 3,
  29577. 4, 4,
  29578. 3, 1,
  29579. 4, 2,
  29580. 4, 4,
  29581. 0, 2,
  29582. 1, 1,
  29583. 2, 2,
  29584. 3, 3,
  29585. 1, 3,
  29586. 2, 4 // 23: B + 12
  29587. ];
  29588. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29589. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29590. // First island of uv mapping
  29591. // v = 4h 3+ 2
  29592. // v = 3h 9+ 4
  29593. // v = 2h 9+ 5 B
  29594. // v = 1h 9 1 0
  29595. // v = 0h 3 8 7 A
  29596. // u = 0 1 2 3 4 5 6 *a
  29597. // Second island of uv mapping
  29598. // v = 4h 0+ B+ 4+
  29599. // v = 3h A+ 2+
  29600. // v = 2h 7+ 6 3+
  29601. // v = 1h 8+ 3+
  29602. // v = 0h
  29603. // u = 0 1 2 3 4 5 6 *a
  29604. // Face layout on texture UV mapping
  29605. // ============
  29606. // \ 4 /\ 16 / ======
  29607. // \ / \ / /\ 11 /
  29608. // \/ 7 \/ / \ /
  29609. // ======= / 10 \/
  29610. // /\ 17 /\ =======
  29611. // / \ / \ \ 15 /\
  29612. // / 8 \/ 12 \ \ / \
  29613. // ============ \/ 6 \
  29614. // \ 18 /\ ============
  29615. // \ / \ \ 5 /\ 0 /
  29616. // \/ 13 \ \ / \ /
  29617. // ======= \/ 1 \/
  29618. // =============
  29619. // /\ 19 /\ 2 /\
  29620. // / \ / \ / \
  29621. // / 14 \/ 9 \/ 3 \
  29622. // ===================
  29623. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29624. var ustep = 138 / 1024;
  29625. var vstep = 239 / 1024;
  29626. var uoffset = 60 / 1024;
  29627. var voffset = 26 / 1024;
  29628. // Second island should have margin, not to touch the first island
  29629. // avoid any borderline artefact in pixel rounding
  29630. var island_u_offset = -40 / 1024;
  29631. var island_v_offset = +20 / 1024;
  29632. // face is either island 0 or 1 :
  29633. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29634. var island = [
  29635. 0, 0, 0, 0, 1,
  29636. 0, 0, 1, 1, 0,
  29637. 0, 0, 1, 1, 0,
  29638. 0, 1, 1, 1, 0 // 15 - 19
  29639. ];
  29640. var indices = new Array();
  29641. var positions = new Array();
  29642. var normals = new Array();
  29643. var uvs = new Array();
  29644. var current_indice = 0;
  29645. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29646. var face_vertex_pos = new Array(3);
  29647. var face_vertex_uv = new Array(3);
  29648. var v012;
  29649. for (v012 = 0; v012 < 3; v012++) {
  29650. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29651. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29652. }
  29653. // create all with normals
  29654. for (var face = 0; face < 20; face++) {
  29655. // 3 vertex per face
  29656. for (v012 = 0; v012 < 3; v012++) {
  29657. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29658. var v_id = ico_indices[3 * face + v012];
  29659. // vertex have 3D position (x,y,z)
  29660. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  29661. // Normalize to get normal, then scale to radius
  29662. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29663. // uv Coordinates from vertex ID
  29664. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  29665. }
  29666. // Subdivide the face (interpolate pos, norm, uv)
  29667. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29668. // - norm is linear interpolation of vertex corner normal
  29669. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29670. // - uv is linear interpolation
  29671. //
  29672. // Topology is as below for sub-divide by 2
  29673. // vertex shown as v0,v1,v2
  29674. // interp index is i1 to progress in range [v0,v1[
  29675. // interp index is i2 to progress in range [v0,v2[
  29676. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29677. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29678. //
  29679. //
  29680. // i2 v2
  29681. // ^ ^
  29682. // / / \
  29683. // / / \
  29684. // / / \
  29685. // / / (0,1) \
  29686. // / #---------\
  29687. // / / \ (0,0)'/ \
  29688. // / / \ / \
  29689. // / / \ / \
  29690. // / / (0,0) \ / (1,0) \
  29691. // / #---------#---------\
  29692. // v0 v1
  29693. //
  29694. // --------------------> i1
  29695. //
  29696. // interp of (i1,i2):
  29697. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29698. // along i1 : lerp(x0,x1, i1/(S-i2))
  29699. //
  29700. // centroid of triangle is needed to get help normal computation
  29701. // (c1,c2) are used for centroid location
  29702. var interp_vertex = function (i1, i2, c1, c2) {
  29703. // vertex is interpolated from
  29704. // - face_vertex_pos[0..2]
  29705. // - face_vertex_uv[0..2]
  29706. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29707. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29708. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29709. pos_interp.normalize();
  29710. var vertex_normal;
  29711. if (flat) {
  29712. // in flat mode, recalculate normal as face centroid normal
  29713. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29714. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29715. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29716. }
  29717. else {
  29718. // in smooth mode, recalculate normal from each single vertex position
  29719. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29720. }
  29721. // Vertex normal need correction due to X,Y,Z radius scaling
  29722. vertex_normal.x /= radiusX;
  29723. vertex_normal.y /= radiusY;
  29724. vertex_normal.z /= radiusZ;
  29725. vertex_normal.normalize();
  29726. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29727. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29728. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29729. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29730. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29731. uvs.push(uv_interp.x, uv_interp.y);
  29732. // push each vertex has member of a face
  29733. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29734. indices.push(current_indice);
  29735. current_indice++;
  29736. };
  29737. for (var i2 = 0; i2 < subdivisions; i2++) {
  29738. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29739. // face : (i1,i2) for /\ :
  29740. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29741. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29742. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29743. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29744. if (i1 + i2 + 1 < subdivisions) {
  29745. // face : (i1,i2)' for \/ :
  29746. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29747. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29748. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29749. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29750. }
  29751. }
  29752. }
  29753. }
  29754. // Sides
  29755. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29756. // Result
  29757. var vertexData = new VertexData();
  29758. vertexData.indices = indices;
  29759. vertexData.positions = positions;
  29760. vertexData.normals = normals;
  29761. vertexData.uvs = uvs;
  29762. return vertexData;
  29763. };
  29764. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29765. /**
  29766. * Creates the VertexData of the Polyhedron.
  29767. */
  29768. VertexData.CreatePolyhedron = function (options) {
  29769. // provided polyhedron types :
  29770. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29771. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  29772. var polyhedra = [];
  29773. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  29774. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  29775. polyhedra[2] = {
  29776. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  29777. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  29778. };
  29779. polyhedra[3] = {
  29780. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  29781. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  29782. };
  29783. polyhedra[4] = {
  29784. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  29785. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  29786. };
  29787. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  29788. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  29789. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  29790. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  29791. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  29792. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  29793. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  29794. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  29795. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  29796. polyhedra[14] = {
  29797. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  29798. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  29799. };
  29800. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29801. var size = options.size;
  29802. var sizeX = options.sizeX || size || 1;
  29803. var sizeY = options.sizeY || size || 1;
  29804. var sizeZ = options.sizeZ || size || 1;
  29805. var data = options.custom || polyhedra[type];
  29806. var nbfaces = data.face.length;
  29807. var faceUV = options.faceUV || new Array(nbfaces);
  29808. var faceColors = options.faceColors;
  29809. var flat = (options.flat === undefined) ? true : options.flat;
  29810. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29811. var positions = new Array();
  29812. var indices = new Array();
  29813. var normals = new Array();
  29814. var uvs = new Array();
  29815. var colors = new Array();
  29816. var index = 0;
  29817. var faceIdx = 0; // face cursor in the array "indexes"
  29818. var indexes = new Array();
  29819. var i = 0;
  29820. var f = 0;
  29821. var u, v, ang, x, y, tmp;
  29822. // default face colors and UV if undefined
  29823. if (flat) {
  29824. for (f = 0; f < nbfaces; f++) {
  29825. if (faceColors && faceColors[f] === undefined) {
  29826. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29827. }
  29828. if (faceUV && faceUV[f] === undefined) {
  29829. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29830. }
  29831. }
  29832. }
  29833. if (!flat) {
  29834. for (i = 0; i < data.vertex.length; i++) {
  29835. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29836. uvs.push(0, 0);
  29837. }
  29838. for (f = 0; f < nbfaces; f++) {
  29839. for (i = 0; i < data.face[f].length - 2; i++) {
  29840. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29841. }
  29842. }
  29843. }
  29844. else {
  29845. for (f = 0; f < nbfaces; f++) {
  29846. var fl = data.face[f].length; // number of vertices of the current face
  29847. ang = 2 * Math.PI / fl;
  29848. x = 0.5 * Math.tan(ang / 2);
  29849. y = 0.5;
  29850. // positions, uvs, colors
  29851. for (i = 0; i < fl; i++) {
  29852. // positions
  29853. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  29854. indexes.push(index);
  29855. index++;
  29856. // uvs
  29857. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29858. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29859. uvs.push(u, v);
  29860. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29861. y = x * Math.sin(ang) + y * Math.cos(ang);
  29862. x = tmp;
  29863. // colors
  29864. if (faceColors) {
  29865. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29866. }
  29867. }
  29868. // indices from indexes
  29869. for (i = 0; i < fl - 2; i++) {
  29870. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29871. }
  29872. faceIdx += fl;
  29873. }
  29874. }
  29875. VertexData.ComputeNormals(positions, indices, normals);
  29876. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29877. var vertexData = new VertexData();
  29878. vertexData.positions = positions;
  29879. vertexData.indices = indices;
  29880. vertexData.normals = normals;
  29881. vertexData.uvs = uvs;
  29882. if (faceColors && flat) {
  29883. vertexData.colors = colors;
  29884. }
  29885. return vertexData;
  29886. };
  29887. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29888. /**
  29889. * Creates the VertexData of the Torus Knot.
  29890. */
  29891. VertexData.CreateTorusKnot = function (options) {
  29892. var indices = new Array();
  29893. var positions = new Array();
  29894. var normals = new Array();
  29895. var uvs = new Array();
  29896. var radius = options.radius || 2;
  29897. var tube = options.tube || 0.5;
  29898. var radialSegments = options.radialSegments || 32;
  29899. var tubularSegments = options.tubularSegments || 32;
  29900. var p = options.p || 2;
  29901. var q = options.q || 3;
  29902. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29903. // Helper
  29904. var getPos = function (angle) {
  29905. var cu = Math.cos(angle);
  29906. var su = Math.sin(angle);
  29907. var quOverP = q / p * angle;
  29908. var cs = Math.cos(quOverP);
  29909. var tx = radius * (2 + cs) * 0.5 * cu;
  29910. var ty = radius * (2 + cs) * su * 0.5;
  29911. var tz = radius * Math.sin(quOverP) * 0.5;
  29912. return new BABYLON.Vector3(tx, ty, tz);
  29913. };
  29914. // Vertices
  29915. var i;
  29916. var j;
  29917. for (i = 0; i <= radialSegments; i++) {
  29918. var modI = i % radialSegments;
  29919. var u = modI / radialSegments * 2 * p * Math.PI;
  29920. var p1 = getPos(u);
  29921. var p2 = getPos(u + 0.01);
  29922. var tang = p2.subtract(p1);
  29923. var n = p2.add(p1);
  29924. var bitan = BABYLON.Vector3.Cross(tang, n);
  29925. n = BABYLON.Vector3.Cross(bitan, tang);
  29926. bitan.normalize();
  29927. n.normalize();
  29928. for (j = 0; j < tubularSegments; j++) {
  29929. var modJ = j % tubularSegments;
  29930. var v = modJ / tubularSegments * 2 * Math.PI;
  29931. var cx = -tube * Math.cos(v);
  29932. var cy = tube * Math.sin(v);
  29933. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29934. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29935. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29936. uvs.push(i / radialSegments);
  29937. uvs.push(j / tubularSegments);
  29938. }
  29939. }
  29940. for (i = 0; i < radialSegments; i++) {
  29941. for (j = 0; j < tubularSegments; j++) {
  29942. var jNext = (j + 1) % tubularSegments;
  29943. var a = i * tubularSegments + j;
  29944. var b = (i + 1) * tubularSegments + j;
  29945. var c = (i + 1) * tubularSegments + jNext;
  29946. var d = i * tubularSegments + jNext;
  29947. indices.push(d);
  29948. indices.push(b);
  29949. indices.push(a);
  29950. indices.push(d);
  29951. indices.push(c);
  29952. indices.push(b);
  29953. }
  29954. }
  29955. // Normals
  29956. VertexData.ComputeNormals(positions, indices, normals);
  29957. // Sides
  29958. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29959. // Result
  29960. var vertexData = new VertexData();
  29961. vertexData.indices = indices;
  29962. vertexData.positions = positions;
  29963. vertexData.normals = normals;
  29964. vertexData.uvs = uvs;
  29965. return vertexData;
  29966. };
  29967. // Tools
  29968. /**
  29969. * @param {any} - positions (number[] or Float32Array)
  29970. * @param {any} - indices (number[] or Uint16Array)
  29971. * @param {any} - normals (number[] or Float32Array)
  29972. * options (optional) :
  29973. * facetPositions : optional array of facet positions (vector3)
  29974. * facetNormals : optional array of facet normals (vector3)
  29975. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29976. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29977. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29978. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29979. * bInfo : optional bounding info, required for facetPartitioning computation
  29980. */
  29981. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29982. // temporary scalar variables
  29983. var index = 0; // facet index
  29984. var p1p2x = 0.0; // p1p2 vector x coordinate
  29985. var p1p2y = 0.0; // p1p2 vector y coordinate
  29986. var p1p2z = 0.0; // p1p2 vector z coordinate
  29987. var p3p2x = 0.0; // p3p2 vector x coordinate
  29988. var p3p2y = 0.0; // p3p2 vector y coordinate
  29989. var p3p2z = 0.0; // p3p2 vector z coordinate
  29990. var faceNormalx = 0.0; // facet normal x coordinate
  29991. var faceNormaly = 0.0; // facet normal y coordinate
  29992. var faceNormalz = 0.0; // facet normal z coordinate
  29993. var length = 0.0; // facet normal length before normalization
  29994. var v1x = 0; // vector1 x index in the positions array
  29995. var v1y = 0; // vector1 y index in the positions array
  29996. var v1z = 0; // vector1 z index in the positions array
  29997. var v2x = 0; // vector2 x index in the positions array
  29998. var v2y = 0; // vector2 y index in the positions array
  29999. var v2z = 0; // vector2 z index in the positions array
  30000. var v3x = 0; // vector3 x index in the positions array
  30001. var v3y = 0; // vector3 y index in the positions array
  30002. var v3z = 0; // vector3 z index in the positions array
  30003. var computeFacetNormals = false;
  30004. var computeFacetPositions = false;
  30005. var computeFacetPartitioning = false;
  30006. var faceNormalSign = 1;
  30007. var ratio = 0;
  30008. if (options) {
  30009. computeFacetNormals = (options.facetNormals) ? true : false;
  30010. computeFacetPositions = (options.facetPositions) ? true : false;
  30011. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30012. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30013. ratio = options.ratio || 0;
  30014. }
  30015. // facetPartitioning reinit if needed
  30016. var xSubRatio = 0;
  30017. var ySubRatio = 0;
  30018. var zSubRatio = 0;
  30019. var subSq = 0;
  30020. if (computeFacetPartitioning && options && options.bbSize) {
  30021. var ox = 0; // X partitioning index for facet position
  30022. var oy = 0; // Y partinioning index for facet position
  30023. var oz = 0; // Z partinioning index for facet position
  30024. var b1x = 0; // X partitioning index for facet v1 vertex
  30025. var b1y = 0; // Y partitioning index for facet v1 vertex
  30026. var b1z = 0; // z partitioning index for facet v1 vertex
  30027. var b2x = 0; // X partitioning index for facet v2 vertex
  30028. var b2y = 0; // Y partitioning index for facet v2 vertex
  30029. var b2z = 0; // Z partitioning index for facet v2 vertex
  30030. var b3x = 0; // X partitioning index for facet v3 vertex
  30031. var b3y = 0; // Y partitioning index for facet v3 vertex
  30032. var b3z = 0; // Z partitioning index for facet v3 vertex
  30033. var block_idx_o = 0; // facet barycenter block index
  30034. var block_idx_v1 = 0; // v1 vertex block index
  30035. var block_idx_v2 = 0; // v2 vertex block index
  30036. var block_idx_v3 = 0; // v3 vertex block index
  30037. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30038. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30039. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30040. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30041. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30042. subSq = options.subDiv.max * options.subDiv.max;
  30043. options.facetPartitioning.length = 0;
  30044. }
  30045. // reset the normals
  30046. for (index = 0; index < positions.length; index++) {
  30047. normals[index] = 0.0;
  30048. }
  30049. // Loop : 1 indice triplet = 1 facet
  30050. var nbFaces = indices.length / 3;
  30051. for (index = 0; index < nbFaces; index++) {
  30052. // get the indexes of the coordinates of each vertex of the facet
  30053. v1x = indices[index * 3] * 3;
  30054. v1y = v1x + 1;
  30055. v1z = v1x + 2;
  30056. v2x = indices[index * 3 + 1] * 3;
  30057. v2y = v2x + 1;
  30058. v2z = v2x + 2;
  30059. v3x = indices[index * 3 + 2] * 3;
  30060. v3y = v3x + 1;
  30061. v3z = v3x + 2;
  30062. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30063. p1p2y = positions[v1y] - positions[v2y];
  30064. p1p2z = positions[v1z] - positions[v2z];
  30065. p3p2x = positions[v3x] - positions[v2x];
  30066. p3p2y = positions[v3y] - positions[v2y];
  30067. p3p2z = positions[v3z] - positions[v2z];
  30068. // compute the face normal with the cross product
  30069. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30070. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30071. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30072. // normalize this normal and store it in the array facetData
  30073. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30074. length = (length === 0) ? 1.0 : length;
  30075. faceNormalx /= length;
  30076. faceNormaly /= length;
  30077. faceNormalz /= length;
  30078. if (computeFacetNormals && options) {
  30079. options.facetNormals[index].x = faceNormalx;
  30080. options.facetNormals[index].y = faceNormaly;
  30081. options.facetNormals[index].z = faceNormalz;
  30082. }
  30083. if (computeFacetPositions && options) {
  30084. // compute and the facet barycenter coordinates in the array facetPositions
  30085. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30086. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30087. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30088. }
  30089. if (computeFacetPartitioning && options) {
  30090. // store the facet indexes in arrays in the main facetPartitioning array :
  30091. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30092. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30093. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30094. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30095. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30096. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30097. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30098. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30099. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30100. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30101. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30102. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30103. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30104. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30105. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30106. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30107. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30108. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30109. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30110. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30111. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30112. // push each facet index in each block containing the vertex
  30113. options.facetPartitioning[block_idx_v1].push(index);
  30114. if (block_idx_v2 != block_idx_v1) {
  30115. options.facetPartitioning[block_idx_v2].push(index);
  30116. }
  30117. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30118. options.facetPartitioning[block_idx_v3].push(index);
  30119. }
  30120. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30121. options.facetPartitioning[block_idx_o].push(index);
  30122. }
  30123. }
  30124. // compute the normals anyway
  30125. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30126. normals[v1y] += faceNormaly;
  30127. normals[v1z] += faceNormalz;
  30128. normals[v2x] += faceNormalx;
  30129. normals[v2y] += faceNormaly;
  30130. normals[v2z] += faceNormalz;
  30131. normals[v3x] += faceNormalx;
  30132. normals[v3y] += faceNormaly;
  30133. normals[v3z] += faceNormalz;
  30134. }
  30135. // last normalization of each normal
  30136. for (index = 0; index < normals.length / 3; index++) {
  30137. faceNormalx = normals[index * 3];
  30138. faceNormaly = normals[index * 3 + 1];
  30139. faceNormalz = normals[index * 3 + 2];
  30140. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30141. length = (length === 0) ? 1.0 : length;
  30142. faceNormalx /= length;
  30143. faceNormaly /= length;
  30144. faceNormalz /= length;
  30145. normals[index * 3] = faceNormalx;
  30146. normals[index * 3 + 1] = faceNormaly;
  30147. normals[index * 3 + 2] = faceNormalz;
  30148. }
  30149. };
  30150. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30151. var li = indices.length;
  30152. var ln = normals.length;
  30153. var i;
  30154. var n;
  30155. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30156. switch (sideOrientation) {
  30157. case BABYLON.Mesh.FRONTSIDE:
  30158. // nothing changed
  30159. break;
  30160. case BABYLON.Mesh.BACKSIDE:
  30161. var tmp;
  30162. // indices
  30163. for (i = 0; i < li; i += 3) {
  30164. tmp = indices[i];
  30165. indices[i] = indices[i + 2];
  30166. indices[i + 2] = tmp;
  30167. }
  30168. // normals
  30169. for (n = 0; n < ln; n++) {
  30170. normals[n] = -normals[n];
  30171. }
  30172. break;
  30173. case BABYLON.Mesh.DOUBLESIDE:
  30174. // positions
  30175. var lp = positions.length;
  30176. var l = lp / 3;
  30177. for (var p = 0; p < lp; p++) {
  30178. positions[lp + p] = positions[p];
  30179. }
  30180. // indices
  30181. for (i = 0; i < li; i += 3) {
  30182. indices[i + li] = indices[i + 2] + l;
  30183. indices[i + 1 + li] = indices[i + 1] + l;
  30184. indices[i + 2 + li] = indices[i] + l;
  30185. }
  30186. // normals
  30187. for (n = 0; n < ln; n++) {
  30188. normals[ln + n] = -normals[n];
  30189. }
  30190. // uvs
  30191. var lu = uvs.length;
  30192. var u = 0;
  30193. for (u = 0; u < lu; u++) {
  30194. uvs[u + lu] = uvs[u];
  30195. }
  30196. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30197. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30198. u = 0;
  30199. for (i = 0; i < lu / 2; i++) {
  30200. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30201. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30202. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30203. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30204. u += 2;
  30205. }
  30206. break;
  30207. }
  30208. };
  30209. /**
  30210. * Creates a new VertexData from the imported parameters.
  30211. */
  30212. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30213. var vertexData = new VertexData();
  30214. // positions
  30215. var positions = parsedVertexData.positions;
  30216. if (positions) {
  30217. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30218. }
  30219. // normals
  30220. var normals = parsedVertexData.normals;
  30221. if (normals) {
  30222. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30223. }
  30224. // tangents
  30225. var tangents = parsedVertexData.tangents;
  30226. if (tangents) {
  30227. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30228. }
  30229. // uvs
  30230. var uvs = parsedVertexData.uvs;
  30231. if (uvs) {
  30232. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30233. }
  30234. // uv2s
  30235. var uv2s = parsedVertexData.uv2s;
  30236. if (uv2s) {
  30237. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30238. }
  30239. // uv3s
  30240. var uv3s = parsedVertexData.uv3s;
  30241. if (uv3s) {
  30242. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30243. }
  30244. // uv4s
  30245. var uv4s = parsedVertexData.uv4s;
  30246. if (uv4s) {
  30247. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30248. }
  30249. // uv5s
  30250. var uv5s = parsedVertexData.uv5s;
  30251. if (uv5s) {
  30252. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30253. }
  30254. // uv6s
  30255. var uv6s = parsedVertexData.uv6s;
  30256. if (uv6s) {
  30257. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30258. }
  30259. // colors
  30260. var colors = parsedVertexData.colors;
  30261. if (colors) {
  30262. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30263. }
  30264. // matricesIndices
  30265. var matricesIndices = parsedVertexData.matricesIndices;
  30266. if (matricesIndices) {
  30267. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30268. }
  30269. // matricesWeights
  30270. var matricesWeights = parsedVertexData.matricesWeights;
  30271. if (matricesWeights) {
  30272. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30273. }
  30274. // indices
  30275. var indices = parsedVertexData.indices;
  30276. if (indices) {
  30277. vertexData.indices = indices;
  30278. }
  30279. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30280. };
  30281. return VertexData;
  30282. }());
  30283. BABYLON.VertexData = VertexData;
  30284. })(BABYLON || (BABYLON = {}));
  30285. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30286. var BABYLON;
  30287. (function (BABYLON) {
  30288. var Geometry = /** @class */ (function () {
  30289. function Geometry(id, scene, vertexData, updatable, mesh) {
  30290. if (updatable === void 0) { updatable = false; }
  30291. if (mesh === void 0) { mesh = null; }
  30292. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30293. this._totalVertices = 0;
  30294. this._isDisposed = false;
  30295. this._indexBufferIsUpdatable = false;
  30296. this.id = id;
  30297. this._engine = scene.getEngine();
  30298. this._meshes = [];
  30299. this._scene = scene;
  30300. //Init vertex buffer cache
  30301. this._vertexBuffers = {};
  30302. this._indices = [];
  30303. this._updatable = updatable;
  30304. // vertexData
  30305. if (vertexData) {
  30306. this.setAllVerticesData(vertexData, updatable);
  30307. }
  30308. else {
  30309. this._totalVertices = 0;
  30310. this._indices = [];
  30311. }
  30312. if (this._engine.getCaps().vertexArrayObject) {
  30313. this._vertexArrayObjects = {};
  30314. }
  30315. // applyToMesh
  30316. if (mesh) {
  30317. if (mesh.getClassName() === "LinesMesh") {
  30318. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30319. this.updateExtend();
  30320. }
  30321. this.applyToMesh(mesh);
  30322. mesh.computeWorldMatrix(true);
  30323. }
  30324. }
  30325. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30326. /**
  30327. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  30328. * @returns The Bias Vector
  30329. */
  30330. get: function () {
  30331. return this._boundingBias;
  30332. },
  30333. set: function (value) {
  30334. if (this._boundingBias && this._boundingBias.equals(value)) {
  30335. return;
  30336. }
  30337. this._boundingBias = value.clone();
  30338. this.updateBoundingInfo(true, null);
  30339. },
  30340. enumerable: true,
  30341. configurable: true
  30342. });
  30343. Geometry.CreateGeometryForMesh = function (mesh) {
  30344. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30345. geometry.applyToMesh(mesh);
  30346. return geometry;
  30347. };
  30348. Object.defineProperty(Geometry.prototype, "extend", {
  30349. get: function () {
  30350. return this._extend;
  30351. },
  30352. enumerable: true,
  30353. configurable: true
  30354. });
  30355. Geometry.prototype.getScene = function () {
  30356. return this._scene;
  30357. };
  30358. Geometry.prototype.getEngine = function () {
  30359. return this._engine;
  30360. };
  30361. Geometry.prototype.isReady = function () {
  30362. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30363. };
  30364. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30365. get: function () {
  30366. for (var index = 0; index < this._meshes.length; index++) {
  30367. if (!this._meshes[index].doNotSerialize) {
  30368. return false;
  30369. }
  30370. }
  30371. return true;
  30372. },
  30373. enumerable: true,
  30374. configurable: true
  30375. });
  30376. Geometry.prototype._rebuild = function () {
  30377. if (this._vertexArrayObjects) {
  30378. this._vertexArrayObjects = {};
  30379. }
  30380. // Index buffer
  30381. if (this._meshes.length !== 0 && this._indices) {
  30382. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30383. }
  30384. // Vertex buffers
  30385. for (var key in this._vertexBuffers) {
  30386. var vertexBuffer = this._vertexBuffers[key];
  30387. vertexBuffer._rebuild();
  30388. }
  30389. };
  30390. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30391. vertexData.applyToGeometry(this, updatable);
  30392. this.notifyUpdate();
  30393. };
  30394. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30395. if (updatable === void 0) { updatable = false; }
  30396. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30397. this.setVerticesBuffer(buffer);
  30398. };
  30399. Geometry.prototype.removeVerticesData = function (kind) {
  30400. if (this._vertexBuffers[kind]) {
  30401. this._vertexBuffers[kind].dispose();
  30402. delete this._vertexBuffers[kind];
  30403. }
  30404. };
  30405. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30406. var kind = buffer.getKind();
  30407. if (this._vertexBuffers[kind]) {
  30408. this._vertexBuffers[kind].dispose();
  30409. }
  30410. this._vertexBuffers[kind] = buffer;
  30411. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30412. var data = buffer.getData();
  30413. var stride = buffer.getStrideSize();
  30414. this._totalVertices = data.length / stride;
  30415. this.updateExtend(data, stride);
  30416. this._resetPointsArrayCache();
  30417. var meshes = this._meshes;
  30418. var numOfMeshes = meshes.length;
  30419. for (var index = 0; index < numOfMeshes; index++) {
  30420. var mesh = meshes[index];
  30421. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30422. mesh._createGlobalSubMesh(false);
  30423. mesh.computeWorldMatrix(true);
  30424. }
  30425. }
  30426. this.notifyUpdate(kind);
  30427. if (this._vertexArrayObjects) {
  30428. this._disposeVertexArrayObjects();
  30429. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30430. }
  30431. };
  30432. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30433. var vertexBuffer = this.getVertexBuffer(kind);
  30434. if (!vertexBuffer) {
  30435. return;
  30436. }
  30437. vertexBuffer.updateDirectly(data, offset);
  30438. this.notifyUpdate(kind);
  30439. };
  30440. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30441. if (updateExtends === void 0) { updateExtends = false; }
  30442. var vertexBuffer = this.getVertexBuffer(kind);
  30443. if (!vertexBuffer) {
  30444. return;
  30445. }
  30446. vertexBuffer.update(data);
  30447. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30448. var stride = vertexBuffer.getStrideSize();
  30449. this._totalVertices = data.length / stride;
  30450. this.updateBoundingInfo(updateExtends, data);
  30451. }
  30452. this.notifyUpdate(kind);
  30453. };
  30454. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30455. if (updateExtends) {
  30456. this.updateExtend(data);
  30457. }
  30458. var meshes = this._meshes;
  30459. var numOfMeshes = meshes.length;
  30460. this._resetPointsArrayCache();
  30461. for (var index = 0; index < numOfMeshes; index++) {
  30462. var mesh = meshes[index];
  30463. if (updateExtends) {
  30464. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30465. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30466. var subMesh = mesh.subMeshes[subIndex];
  30467. subMesh.refreshBoundingInfo();
  30468. }
  30469. }
  30470. }
  30471. };
  30472. Geometry.prototype._bind = function (effect, indexToBind) {
  30473. if (!effect) {
  30474. return;
  30475. }
  30476. if (indexToBind === undefined) {
  30477. indexToBind = this._indexBuffer;
  30478. }
  30479. var vbs = this.getVertexBuffers();
  30480. if (!vbs) {
  30481. return;
  30482. }
  30483. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30484. this._engine.bindBuffers(vbs, indexToBind, effect);
  30485. return;
  30486. }
  30487. // Using VAO
  30488. if (!this._vertexArrayObjects[effect.key]) {
  30489. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30490. }
  30491. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30492. };
  30493. Geometry.prototype.getTotalVertices = function () {
  30494. if (!this.isReady()) {
  30495. return 0;
  30496. }
  30497. return this._totalVertices;
  30498. };
  30499. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30500. var vertexBuffer = this.getVertexBuffer(kind);
  30501. if (!vertexBuffer) {
  30502. return null;
  30503. }
  30504. var orig = vertexBuffer.getData();
  30505. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30506. return orig;
  30507. }
  30508. else {
  30509. var len = orig.length;
  30510. var copy = [];
  30511. for (var i = 0; i < len; i++) {
  30512. copy.push(orig[i]);
  30513. }
  30514. return copy;
  30515. }
  30516. };
  30517. /**
  30518. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30519. * Possible `kind` values :
  30520. * - BABYLON.VertexBuffer.PositionKind
  30521. * - BABYLON.VertexBuffer.UVKind
  30522. * - BABYLON.VertexBuffer.UV2Kind
  30523. * - BABYLON.VertexBuffer.UV3Kind
  30524. * - BABYLON.VertexBuffer.UV4Kind
  30525. * - BABYLON.VertexBuffer.UV5Kind
  30526. * - BABYLON.VertexBuffer.UV6Kind
  30527. * - BABYLON.VertexBuffer.ColorKind
  30528. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30529. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30530. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30531. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30532. */
  30533. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30534. var vb = this._vertexBuffers[kind];
  30535. if (!vb) {
  30536. return false;
  30537. }
  30538. return vb.isUpdatable();
  30539. };
  30540. Geometry.prototype.getVertexBuffer = function (kind) {
  30541. if (!this.isReady()) {
  30542. return null;
  30543. }
  30544. return this._vertexBuffers[kind];
  30545. };
  30546. Geometry.prototype.getVertexBuffers = function () {
  30547. if (!this.isReady()) {
  30548. return null;
  30549. }
  30550. return this._vertexBuffers;
  30551. };
  30552. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30553. if (!this._vertexBuffers) {
  30554. if (this._delayInfo) {
  30555. return this._delayInfo.indexOf(kind) !== -1;
  30556. }
  30557. return false;
  30558. }
  30559. return this._vertexBuffers[kind] !== undefined;
  30560. };
  30561. Geometry.prototype.getVerticesDataKinds = function () {
  30562. var result = [];
  30563. var kind;
  30564. if (!this._vertexBuffers && this._delayInfo) {
  30565. for (kind in this._delayInfo) {
  30566. result.push(kind);
  30567. }
  30568. }
  30569. else {
  30570. for (kind in this._vertexBuffers) {
  30571. result.push(kind);
  30572. }
  30573. }
  30574. return result;
  30575. };
  30576. Geometry.prototype.updateIndices = function (indices, offset) {
  30577. if (!this._indexBuffer) {
  30578. return;
  30579. }
  30580. if (!this._indexBufferIsUpdatable) {
  30581. this.setIndices(indices, null, true);
  30582. }
  30583. else {
  30584. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30585. }
  30586. };
  30587. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30588. if (totalVertices === void 0) { totalVertices = null; }
  30589. if (updatable === void 0) { updatable = false; }
  30590. if (this._indexBuffer) {
  30591. this._engine._releaseBuffer(this._indexBuffer);
  30592. }
  30593. this._disposeVertexArrayObjects();
  30594. this._indices = indices;
  30595. this._indexBufferIsUpdatable = updatable;
  30596. if (this._meshes.length !== 0 && this._indices) {
  30597. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30598. }
  30599. if (totalVertices != undefined) {
  30600. this._totalVertices = totalVertices;
  30601. }
  30602. var meshes = this._meshes;
  30603. var numOfMeshes = meshes.length;
  30604. for (var index = 0; index < numOfMeshes; index++) {
  30605. meshes[index]._createGlobalSubMesh(true);
  30606. }
  30607. this.notifyUpdate();
  30608. };
  30609. Geometry.prototype.getTotalIndices = function () {
  30610. if (!this.isReady()) {
  30611. return 0;
  30612. }
  30613. return this._indices.length;
  30614. };
  30615. Geometry.prototype.getIndices = function (copyWhenShared) {
  30616. if (!this.isReady()) {
  30617. return null;
  30618. }
  30619. var orig = this._indices;
  30620. if (!copyWhenShared || this._meshes.length === 1) {
  30621. return orig;
  30622. }
  30623. else {
  30624. var len = orig.length;
  30625. var copy = [];
  30626. for (var i = 0; i < len; i++) {
  30627. copy.push(orig[i]);
  30628. }
  30629. return copy;
  30630. }
  30631. };
  30632. Geometry.prototype.getIndexBuffer = function () {
  30633. if (!this.isReady()) {
  30634. return null;
  30635. }
  30636. return this._indexBuffer;
  30637. };
  30638. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30639. if (effect === void 0) { effect = null; }
  30640. if (!effect || !this._vertexArrayObjects) {
  30641. return;
  30642. }
  30643. if (this._vertexArrayObjects[effect.key]) {
  30644. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30645. delete this._vertexArrayObjects[effect.key];
  30646. }
  30647. };
  30648. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30649. var meshes = this._meshes;
  30650. var index = meshes.indexOf(mesh);
  30651. if (index === -1) {
  30652. return;
  30653. }
  30654. meshes.splice(index, 1);
  30655. mesh._geometry = null;
  30656. if (meshes.length === 0 && shouldDispose) {
  30657. this.dispose();
  30658. }
  30659. };
  30660. Geometry.prototype.applyToMesh = function (mesh) {
  30661. if (mesh._geometry === this) {
  30662. return;
  30663. }
  30664. var previousGeometry = mesh._geometry;
  30665. if (previousGeometry) {
  30666. previousGeometry.releaseForMesh(mesh);
  30667. }
  30668. var meshes = this._meshes;
  30669. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30670. mesh._geometry = this;
  30671. this._scene.pushGeometry(this);
  30672. meshes.push(mesh);
  30673. if (this.isReady()) {
  30674. this._applyToMesh(mesh);
  30675. }
  30676. else {
  30677. mesh._boundingInfo = this._boundingInfo;
  30678. }
  30679. };
  30680. Geometry.prototype.updateExtend = function (data, stride) {
  30681. if (data === void 0) { data = null; }
  30682. if (!data) {
  30683. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30684. }
  30685. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30686. };
  30687. Geometry.prototype._applyToMesh = function (mesh) {
  30688. var numOfMeshes = this._meshes.length;
  30689. // vertexBuffers
  30690. for (var kind in this._vertexBuffers) {
  30691. if (numOfMeshes === 1) {
  30692. this._vertexBuffers[kind].create();
  30693. }
  30694. var buffer = this._vertexBuffers[kind].getBuffer();
  30695. if (buffer)
  30696. buffer.references = numOfMeshes;
  30697. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30698. if (!this._extend) {
  30699. this.updateExtend(this._vertexBuffers[kind].getData());
  30700. }
  30701. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30702. mesh._createGlobalSubMesh(false);
  30703. //bounding info was just created again, world matrix should be applied again.
  30704. mesh._updateBoundingInfo();
  30705. }
  30706. }
  30707. // indexBuffer
  30708. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30709. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30710. }
  30711. if (this._indexBuffer) {
  30712. this._indexBuffer.references = numOfMeshes;
  30713. }
  30714. };
  30715. Geometry.prototype.notifyUpdate = function (kind) {
  30716. if (this.onGeometryUpdated) {
  30717. this.onGeometryUpdated(this, kind);
  30718. }
  30719. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30720. var mesh = _a[_i];
  30721. mesh._markSubMeshesAsAttributesDirty();
  30722. }
  30723. };
  30724. Geometry.prototype.load = function (scene, onLoaded) {
  30725. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30726. return;
  30727. }
  30728. if (this.isReady()) {
  30729. if (onLoaded) {
  30730. onLoaded();
  30731. }
  30732. return;
  30733. }
  30734. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30735. this._queueLoad(scene, onLoaded);
  30736. };
  30737. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30738. var _this = this;
  30739. if (!this.delayLoadingFile) {
  30740. return;
  30741. }
  30742. scene._addPendingData(this);
  30743. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30744. if (!_this._delayLoadingFunction) {
  30745. return;
  30746. }
  30747. _this._delayLoadingFunction(JSON.parse(data), _this);
  30748. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30749. _this._delayInfo = [];
  30750. scene._removePendingData(_this);
  30751. var meshes = _this._meshes;
  30752. var numOfMeshes = meshes.length;
  30753. for (var index = 0; index < numOfMeshes; index++) {
  30754. _this._applyToMesh(meshes[index]);
  30755. }
  30756. if (onLoaded) {
  30757. onLoaded();
  30758. }
  30759. }, function () { }, scene.database);
  30760. };
  30761. /**
  30762. * Invert the geometry to move from a right handed system to a left handed one.
  30763. */
  30764. Geometry.prototype.toLeftHanded = function () {
  30765. // Flip faces
  30766. var tIndices = this.getIndices(false);
  30767. if (tIndices != null && tIndices.length > 0) {
  30768. for (var i = 0; i < tIndices.length; i += 3) {
  30769. var tTemp = tIndices[i + 0];
  30770. tIndices[i + 0] = tIndices[i + 2];
  30771. tIndices[i + 2] = tTemp;
  30772. }
  30773. this.setIndices(tIndices);
  30774. }
  30775. // Negate position.z
  30776. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30777. if (tPositions != null && tPositions.length > 0) {
  30778. for (var i = 0; i < tPositions.length; i += 3) {
  30779. tPositions[i + 2] = -tPositions[i + 2];
  30780. }
  30781. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30782. }
  30783. // Negate normal.z
  30784. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30785. if (tNormals != null && tNormals.length > 0) {
  30786. for (var i = 0; i < tNormals.length; i += 3) {
  30787. tNormals[i + 2] = -tNormals[i + 2];
  30788. }
  30789. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30790. }
  30791. };
  30792. // Cache
  30793. Geometry.prototype._resetPointsArrayCache = function () {
  30794. this._positions = null;
  30795. };
  30796. Geometry.prototype._generatePointsArray = function () {
  30797. if (this._positions)
  30798. return true;
  30799. this._positions = [];
  30800. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30801. if (!data) {
  30802. return false;
  30803. }
  30804. for (var index = 0; index < data.length; index += 3) {
  30805. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30806. }
  30807. return true;
  30808. };
  30809. Geometry.prototype.isDisposed = function () {
  30810. return this._isDisposed;
  30811. };
  30812. Geometry.prototype._disposeVertexArrayObjects = function () {
  30813. if (this._vertexArrayObjects) {
  30814. for (var kind in this._vertexArrayObjects) {
  30815. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30816. }
  30817. this._vertexArrayObjects = {};
  30818. }
  30819. };
  30820. Geometry.prototype.dispose = function () {
  30821. var meshes = this._meshes;
  30822. var numOfMeshes = meshes.length;
  30823. var index;
  30824. for (index = 0; index < numOfMeshes; index++) {
  30825. this.releaseForMesh(meshes[index]);
  30826. }
  30827. this._meshes = [];
  30828. this._disposeVertexArrayObjects();
  30829. for (var kind in this._vertexBuffers) {
  30830. this._vertexBuffers[kind].dispose();
  30831. }
  30832. this._vertexBuffers = {};
  30833. this._totalVertices = 0;
  30834. if (this._indexBuffer) {
  30835. this._engine._releaseBuffer(this._indexBuffer);
  30836. }
  30837. this._indexBuffer = null;
  30838. this._indices = [];
  30839. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30840. this.delayLoadingFile = null;
  30841. this._delayLoadingFunction = null;
  30842. this._delayInfo = [];
  30843. this._boundingInfo = null;
  30844. this._scene.removeGeometry(this);
  30845. this._isDisposed = true;
  30846. };
  30847. Geometry.prototype.copy = function (id) {
  30848. var vertexData = new BABYLON.VertexData();
  30849. vertexData.indices = [];
  30850. var indices = this.getIndices();
  30851. if (indices) {
  30852. for (var index = 0; index < indices.length; index++) {
  30853. vertexData.indices.push(indices[index]);
  30854. }
  30855. }
  30856. var updatable = false;
  30857. var stopChecking = false;
  30858. var kind;
  30859. for (kind in this._vertexBuffers) {
  30860. // using slice() to make a copy of the array and not just reference it
  30861. var data = this.getVerticesData(kind);
  30862. if (data instanceof Float32Array) {
  30863. vertexData.set(new Float32Array(data), kind);
  30864. }
  30865. else {
  30866. vertexData.set(data.slice(0), kind);
  30867. }
  30868. if (!stopChecking) {
  30869. var vb = this.getVertexBuffer(kind);
  30870. if (vb) {
  30871. updatable = vb.isUpdatable();
  30872. stopChecking = !updatable;
  30873. }
  30874. }
  30875. }
  30876. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30877. geometry.delayLoadState = this.delayLoadState;
  30878. geometry.delayLoadingFile = this.delayLoadingFile;
  30879. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30880. for (kind in this._delayInfo) {
  30881. geometry._delayInfo = geometry._delayInfo || [];
  30882. geometry._delayInfo.push(kind);
  30883. }
  30884. // Bounding info
  30885. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30886. return geometry;
  30887. };
  30888. Geometry.prototype.serialize = function () {
  30889. var serializationObject = {};
  30890. serializationObject.id = this.id;
  30891. serializationObject.updatable = this._updatable;
  30892. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30893. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30894. }
  30895. return serializationObject;
  30896. };
  30897. Geometry.prototype.toNumberArray = function (origin) {
  30898. if (Array.isArray(origin)) {
  30899. return origin;
  30900. }
  30901. else {
  30902. return Array.prototype.slice.call(origin);
  30903. }
  30904. };
  30905. Geometry.prototype.serializeVerticeData = function () {
  30906. var serializationObject = this.serialize();
  30907. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30908. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30909. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30910. serializationObject.positions._updatable = true;
  30911. }
  30912. }
  30913. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30914. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30915. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30916. serializationObject.normals._updatable = true;
  30917. }
  30918. }
  30919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30920. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30921. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30922. serializationObject.uvs._updatable = true;
  30923. }
  30924. }
  30925. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30926. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30927. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30928. serializationObject.uv2s._updatable = true;
  30929. }
  30930. }
  30931. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30932. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30933. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30934. serializationObject.uv3s._updatable = true;
  30935. }
  30936. }
  30937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30938. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30940. serializationObject.uv4s._updatable = true;
  30941. }
  30942. }
  30943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30944. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30945. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30946. serializationObject.uv5s._updatable = true;
  30947. }
  30948. }
  30949. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30950. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30951. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30952. serializationObject.uv6s._updatable = true;
  30953. }
  30954. }
  30955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30956. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30957. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30958. serializationObject.colors._updatable = true;
  30959. }
  30960. }
  30961. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30962. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30963. serializationObject.matricesIndices._isExpanded = true;
  30964. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30965. serializationObject.matricesIndices._updatable = true;
  30966. }
  30967. }
  30968. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30969. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30970. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30971. serializationObject.matricesWeights._updatable = true;
  30972. }
  30973. }
  30974. serializationObject.indices = this.toNumberArray(this.getIndices());
  30975. return serializationObject;
  30976. };
  30977. // Statics
  30978. Geometry.ExtractFromMesh = function (mesh, id) {
  30979. var geometry = mesh._geometry;
  30980. if (!geometry) {
  30981. return null;
  30982. }
  30983. return geometry.copy(id);
  30984. };
  30985. /**
  30986. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30987. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30988. * Be aware Math.random() could cause collisions, but:
  30989. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  30990. */
  30991. Geometry.RandomId = function () {
  30992. return BABYLON.Tools.RandomId();
  30993. };
  30994. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30995. var scene = mesh.getScene();
  30996. // Geometry
  30997. var geometryId = parsedGeometry.geometryId;
  30998. if (geometryId) {
  30999. var geometry = scene.getGeometryByID(geometryId);
  31000. if (geometry) {
  31001. geometry.applyToMesh(mesh);
  31002. }
  31003. }
  31004. else if (parsedGeometry instanceof ArrayBuffer) {
  31005. var binaryInfo = mesh._binaryInfo;
  31006. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31007. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31008. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31009. }
  31010. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31011. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31012. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31013. }
  31014. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31015. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31016. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31017. }
  31018. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31019. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31020. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31021. }
  31022. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31023. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31024. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31025. }
  31026. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31027. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31028. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31029. }
  31030. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31031. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31032. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31033. }
  31034. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31035. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31036. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31037. }
  31038. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31039. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31040. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31041. }
  31042. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31043. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31044. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31045. }
  31046. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31047. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31048. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31049. }
  31050. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31051. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31052. mesh.setIndices(indicesData, null);
  31053. }
  31054. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31055. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31056. mesh.subMeshes = [];
  31057. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31058. var materialIndex = subMeshesData[(i * 5) + 0];
  31059. var verticesStart = subMeshesData[(i * 5) + 1];
  31060. var verticesCount = subMeshesData[(i * 5) + 2];
  31061. var indexStart = subMeshesData[(i * 5) + 3];
  31062. var indexCount = subMeshesData[(i * 5) + 4];
  31063. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31064. }
  31065. }
  31066. }
  31067. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31068. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31069. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31070. if (parsedGeometry.uvs) {
  31071. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31072. }
  31073. if (parsedGeometry.uvs2) {
  31074. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31075. }
  31076. if (parsedGeometry.uvs3) {
  31077. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31078. }
  31079. if (parsedGeometry.uvs4) {
  31080. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31081. }
  31082. if (parsedGeometry.uvs5) {
  31083. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31084. }
  31085. if (parsedGeometry.uvs6) {
  31086. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31087. }
  31088. if (parsedGeometry.colors) {
  31089. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31090. }
  31091. if (parsedGeometry.matricesIndices) {
  31092. if (!parsedGeometry.matricesIndices._isExpanded) {
  31093. var floatIndices = [];
  31094. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31095. var matricesIndex = parsedGeometry.matricesIndices[i];
  31096. floatIndices.push(matricesIndex & 0x000000FF);
  31097. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31098. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31099. floatIndices.push(matricesIndex >> 24);
  31100. }
  31101. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31102. }
  31103. else {
  31104. delete parsedGeometry.matricesIndices._isExpanded;
  31105. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31106. }
  31107. }
  31108. if (parsedGeometry.matricesIndicesExtra) {
  31109. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31110. var floatIndices = [];
  31111. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31112. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31113. floatIndices.push(matricesIndex & 0x000000FF);
  31114. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31115. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31116. floatIndices.push(matricesIndex >> 24);
  31117. }
  31118. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31119. }
  31120. else {
  31121. delete parsedGeometry.matricesIndices._isExpanded;
  31122. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31123. }
  31124. }
  31125. if (parsedGeometry.matricesWeights) {
  31126. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31127. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31128. }
  31129. if (parsedGeometry.matricesWeightsExtra) {
  31130. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31131. }
  31132. mesh.setIndices(parsedGeometry.indices, null);
  31133. }
  31134. // SubMeshes
  31135. if (parsedGeometry.subMeshes) {
  31136. mesh.subMeshes = [];
  31137. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31138. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31139. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31140. }
  31141. }
  31142. // Flat shading
  31143. if (mesh._shouldGenerateFlatShading) {
  31144. mesh.convertToFlatShadedMesh();
  31145. delete mesh._shouldGenerateFlatShading;
  31146. }
  31147. // Update
  31148. mesh.computeWorldMatrix(true);
  31149. // Octree
  31150. if (scene['_selectionOctree']) {
  31151. scene['_selectionOctree'].addMesh(mesh);
  31152. }
  31153. };
  31154. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31155. var epsilon = 1e-3;
  31156. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31157. return;
  31158. }
  31159. var noInfluenceBoneIndex = 0.0;
  31160. if (parsedGeometry.skeletonId > -1) {
  31161. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31162. if (!skeleton) {
  31163. return;
  31164. }
  31165. noInfluenceBoneIndex = skeleton.bones.length;
  31166. }
  31167. else {
  31168. return;
  31169. }
  31170. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31171. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31172. var matricesWeights = parsedGeometry.matricesWeights;
  31173. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31174. var influencers = parsedGeometry.numBoneInfluencer;
  31175. var size = matricesWeights.length;
  31176. for (var i = 0; i < size; i += 4) {
  31177. var weight = 0.0;
  31178. var firstZeroWeight = -1;
  31179. for (var j = 0; j < 4; j++) {
  31180. var w = matricesWeights[i + j];
  31181. weight += w;
  31182. if (w < epsilon && firstZeroWeight < 0) {
  31183. firstZeroWeight = j;
  31184. }
  31185. }
  31186. if (matricesWeightsExtra) {
  31187. for (var j = 0; j < 4; j++) {
  31188. var w = matricesWeightsExtra[i + j];
  31189. weight += w;
  31190. if (w < epsilon && firstZeroWeight < 0) {
  31191. firstZeroWeight = j + 4;
  31192. }
  31193. }
  31194. }
  31195. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31196. firstZeroWeight = influencers - 1;
  31197. }
  31198. if (weight > epsilon) {
  31199. var mweight = 1.0 / weight;
  31200. for (var j = 0; j < 4; j++) {
  31201. matricesWeights[i + j] *= mweight;
  31202. }
  31203. if (matricesWeightsExtra) {
  31204. for (var j = 0; j < 4; j++) {
  31205. matricesWeightsExtra[i + j] *= mweight;
  31206. }
  31207. }
  31208. }
  31209. else {
  31210. if (firstZeroWeight >= 4) {
  31211. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31212. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31213. }
  31214. else {
  31215. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31216. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31217. }
  31218. }
  31219. }
  31220. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31221. if (parsedGeometry.matricesWeightsExtra) {
  31222. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31223. }
  31224. };
  31225. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31226. if (scene.getGeometryByID(parsedVertexData.id)) {
  31227. return null; // null since geometry could be something else than a box...
  31228. }
  31229. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31230. if (BABYLON.Tags) {
  31231. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31232. }
  31233. if (parsedVertexData.delayLoadingFile) {
  31234. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31235. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31236. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31237. geometry._delayInfo = [];
  31238. if (parsedVertexData.hasUVs) {
  31239. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31240. }
  31241. if (parsedVertexData.hasUVs2) {
  31242. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31243. }
  31244. if (parsedVertexData.hasUVs3) {
  31245. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31246. }
  31247. if (parsedVertexData.hasUVs4) {
  31248. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31249. }
  31250. if (parsedVertexData.hasUVs5) {
  31251. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31252. }
  31253. if (parsedVertexData.hasUVs6) {
  31254. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31255. }
  31256. if (parsedVertexData.hasColors) {
  31257. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31258. }
  31259. if (parsedVertexData.hasMatricesIndices) {
  31260. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31261. }
  31262. if (parsedVertexData.hasMatricesWeights) {
  31263. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31264. }
  31265. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31266. }
  31267. else {
  31268. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31269. }
  31270. scene.pushGeometry(geometry, true);
  31271. return geometry;
  31272. };
  31273. return Geometry;
  31274. }());
  31275. BABYLON.Geometry = Geometry;
  31276. /////// Primitives //////////////////////////////////////////////
  31277. (function (Geometry) {
  31278. var Primitives;
  31279. (function (Primitives) {
  31280. /// Abstract class
  31281. var _Primitive = /** @class */ (function (_super) {
  31282. __extends(_Primitive, _super);
  31283. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31284. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31285. if (mesh === void 0) { mesh = null; }
  31286. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31287. _this._canBeRegenerated = _canBeRegenerated;
  31288. _this._beingRegenerated = true;
  31289. _this.regenerate();
  31290. _this._beingRegenerated = false;
  31291. return _this;
  31292. }
  31293. _Primitive.prototype.canBeRegenerated = function () {
  31294. return this._canBeRegenerated;
  31295. };
  31296. _Primitive.prototype.regenerate = function () {
  31297. if (!this._canBeRegenerated) {
  31298. return;
  31299. }
  31300. this._beingRegenerated = true;
  31301. this.setAllVerticesData(this._regenerateVertexData(), false);
  31302. this._beingRegenerated = false;
  31303. };
  31304. _Primitive.prototype.asNewGeometry = function (id) {
  31305. return _super.prototype.copy.call(this, id);
  31306. };
  31307. // overrides
  31308. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31309. if (!this._beingRegenerated) {
  31310. return;
  31311. }
  31312. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31313. };
  31314. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31315. if (!this._beingRegenerated) {
  31316. return;
  31317. }
  31318. _super.prototype.setVerticesData.call(this, kind, data, false);
  31319. };
  31320. // to override
  31321. // protected
  31322. _Primitive.prototype._regenerateVertexData = function () {
  31323. throw new Error("Abstract method");
  31324. };
  31325. _Primitive.prototype.copy = function (id) {
  31326. throw new Error("Must be overriden in sub-classes.");
  31327. };
  31328. _Primitive.prototype.serialize = function () {
  31329. var serializationObject = _super.prototype.serialize.call(this);
  31330. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31331. return serializationObject;
  31332. };
  31333. return _Primitive;
  31334. }(Geometry));
  31335. Primitives._Primitive = _Primitive;
  31336. var Ribbon = /** @class */ (function (_super) {
  31337. __extends(Ribbon, _super);
  31338. // Members
  31339. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31340. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31341. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31342. _this.pathArray = pathArray;
  31343. _this.closeArray = closeArray;
  31344. _this.closePath = closePath;
  31345. _this.offset = offset;
  31346. _this.side = side;
  31347. return _this;
  31348. }
  31349. Ribbon.prototype._regenerateVertexData = function () {
  31350. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31351. };
  31352. Ribbon.prototype.copy = function (id) {
  31353. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31354. };
  31355. return Ribbon;
  31356. }(_Primitive));
  31357. Primitives.Ribbon = Ribbon;
  31358. var Box = /** @class */ (function (_super) {
  31359. __extends(Box, _super);
  31360. // Members
  31361. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31362. if (mesh === void 0) { mesh = null; }
  31363. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31364. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31365. _this.size = size;
  31366. _this.side = side;
  31367. return _this;
  31368. }
  31369. Box.prototype._regenerateVertexData = function () {
  31370. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31371. };
  31372. Box.prototype.copy = function (id) {
  31373. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31374. };
  31375. Box.prototype.serialize = function () {
  31376. var serializationObject = _super.prototype.serialize.call(this);
  31377. serializationObject.size = this.size;
  31378. return serializationObject;
  31379. };
  31380. Box.Parse = function (parsedBox, scene) {
  31381. if (scene.getGeometryByID(parsedBox.id)) {
  31382. return null; // null since geometry could be something else than a box...
  31383. }
  31384. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31385. if (BABYLON.Tags) {
  31386. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31387. }
  31388. scene.pushGeometry(box, true);
  31389. return box;
  31390. };
  31391. return Box;
  31392. }(_Primitive));
  31393. Primitives.Box = Box;
  31394. var Sphere = /** @class */ (function (_super) {
  31395. __extends(Sphere, _super);
  31396. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31397. if (mesh === void 0) { mesh = null; }
  31398. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31399. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31400. _this.segments = segments;
  31401. _this.diameter = diameter;
  31402. _this.side = side;
  31403. return _this;
  31404. }
  31405. Sphere.prototype._regenerateVertexData = function () {
  31406. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31407. };
  31408. Sphere.prototype.copy = function (id) {
  31409. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31410. };
  31411. Sphere.prototype.serialize = function () {
  31412. var serializationObject = _super.prototype.serialize.call(this);
  31413. serializationObject.segments = this.segments;
  31414. serializationObject.diameter = this.diameter;
  31415. return serializationObject;
  31416. };
  31417. Sphere.Parse = function (parsedSphere, scene) {
  31418. if (scene.getGeometryByID(parsedSphere.id)) {
  31419. return null; // null since geometry could be something else than a sphere...
  31420. }
  31421. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31422. if (BABYLON.Tags) {
  31423. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31424. }
  31425. scene.pushGeometry(sphere, true);
  31426. return sphere;
  31427. };
  31428. return Sphere;
  31429. }(_Primitive));
  31430. Primitives.Sphere = Sphere;
  31431. var Disc = /** @class */ (function (_super) {
  31432. __extends(Disc, _super);
  31433. // Members
  31434. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31435. if (mesh === void 0) { mesh = null; }
  31436. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31437. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31438. _this.radius = radius;
  31439. _this.tessellation = tessellation;
  31440. _this.side = side;
  31441. return _this;
  31442. }
  31443. Disc.prototype._regenerateVertexData = function () {
  31444. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31445. };
  31446. Disc.prototype.copy = function (id) {
  31447. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31448. };
  31449. return Disc;
  31450. }(_Primitive));
  31451. Primitives.Disc = Disc;
  31452. var Cylinder = /** @class */ (function (_super) {
  31453. __extends(Cylinder, _super);
  31454. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31455. if (subdivisions === void 0) { subdivisions = 1; }
  31456. if (mesh === void 0) { mesh = null; }
  31457. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31458. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31459. _this.height = height;
  31460. _this.diameterTop = diameterTop;
  31461. _this.diameterBottom = diameterBottom;
  31462. _this.tessellation = tessellation;
  31463. _this.subdivisions = subdivisions;
  31464. _this.side = side;
  31465. return _this;
  31466. }
  31467. Cylinder.prototype._regenerateVertexData = function () {
  31468. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31469. };
  31470. Cylinder.prototype.copy = function (id) {
  31471. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31472. };
  31473. Cylinder.prototype.serialize = function () {
  31474. var serializationObject = _super.prototype.serialize.call(this);
  31475. serializationObject.height = this.height;
  31476. serializationObject.diameterTop = this.diameterTop;
  31477. serializationObject.diameterBottom = this.diameterBottom;
  31478. serializationObject.tessellation = this.tessellation;
  31479. return serializationObject;
  31480. };
  31481. Cylinder.Parse = function (parsedCylinder, scene) {
  31482. if (scene.getGeometryByID(parsedCylinder.id)) {
  31483. return null; // null since geometry could be something else than a cylinder...
  31484. }
  31485. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31486. if (BABYLON.Tags) {
  31487. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31488. }
  31489. scene.pushGeometry(cylinder, true);
  31490. return cylinder;
  31491. };
  31492. return Cylinder;
  31493. }(_Primitive));
  31494. Primitives.Cylinder = Cylinder;
  31495. var Torus = /** @class */ (function (_super) {
  31496. __extends(Torus, _super);
  31497. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31498. if (mesh === void 0) { mesh = null; }
  31499. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31500. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31501. _this.diameter = diameter;
  31502. _this.thickness = thickness;
  31503. _this.tessellation = tessellation;
  31504. _this.side = side;
  31505. return _this;
  31506. }
  31507. Torus.prototype._regenerateVertexData = function () {
  31508. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31509. };
  31510. Torus.prototype.copy = function (id) {
  31511. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31512. };
  31513. Torus.prototype.serialize = function () {
  31514. var serializationObject = _super.prototype.serialize.call(this);
  31515. serializationObject.diameter = this.diameter;
  31516. serializationObject.thickness = this.thickness;
  31517. serializationObject.tessellation = this.tessellation;
  31518. return serializationObject;
  31519. };
  31520. Torus.Parse = function (parsedTorus, scene) {
  31521. if (scene.getGeometryByID(parsedTorus.id)) {
  31522. return null; // null since geometry could be something else than a torus...
  31523. }
  31524. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31525. if (BABYLON.Tags) {
  31526. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31527. }
  31528. scene.pushGeometry(torus, true);
  31529. return torus;
  31530. };
  31531. return Torus;
  31532. }(_Primitive));
  31533. Primitives.Torus = Torus;
  31534. var Ground = /** @class */ (function (_super) {
  31535. __extends(Ground, _super);
  31536. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31537. if (mesh === void 0) { mesh = null; }
  31538. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31539. _this.width = width;
  31540. _this.height = height;
  31541. _this.subdivisions = subdivisions;
  31542. return _this;
  31543. }
  31544. Ground.prototype._regenerateVertexData = function () {
  31545. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31546. };
  31547. Ground.prototype.copy = function (id) {
  31548. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31549. };
  31550. Ground.prototype.serialize = function () {
  31551. var serializationObject = _super.prototype.serialize.call(this);
  31552. serializationObject.width = this.width;
  31553. serializationObject.height = this.height;
  31554. serializationObject.subdivisions = this.subdivisions;
  31555. return serializationObject;
  31556. };
  31557. Ground.Parse = function (parsedGround, scene) {
  31558. if (scene.getGeometryByID(parsedGround.id)) {
  31559. return null; // null since geometry could be something else than a ground...
  31560. }
  31561. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31562. if (BABYLON.Tags) {
  31563. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31564. }
  31565. scene.pushGeometry(ground, true);
  31566. return ground;
  31567. };
  31568. return Ground;
  31569. }(_Primitive));
  31570. Primitives.Ground = Ground;
  31571. var TiledGround = /** @class */ (function (_super) {
  31572. __extends(TiledGround, _super);
  31573. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31574. if (mesh === void 0) { mesh = null; }
  31575. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31576. _this.xmin = xmin;
  31577. _this.zmin = zmin;
  31578. _this.xmax = xmax;
  31579. _this.zmax = zmax;
  31580. _this.subdivisions = subdivisions;
  31581. _this.precision = precision;
  31582. return _this;
  31583. }
  31584. TiledGround.prototype._regenerateVertexData = function () {
  31585. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31586. };
  31587. TiledGround.prototype.copy = function (id) {
  31588. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31589. };
  31590. return TiledGround;
  31591. }(_Primitive));
  31592. Primitives.TiledGround = TiledGround;
  31593. var Plane = /** @class */ (function (_super) {
  31594. __extends(Plane, _super);
  31595. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31596. if (mesh === void 0) { mesh = null; }
  31597. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31598. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31599. _this.size = size;
  31600. _this.side = side;
  31601. return _this;
  31602. }
  31603. Plane.prototype._regenerateVertexData = function () {
  31604. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31605. };
  31606. Plane.prototype.copy = function (id) {
  31607. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31608. };
  31609. Plane.prototype.serialize = function () {
  31610. var serializationObject = _super.prototype.serialize.call(this);
  31611. serializationObject.size = this.size;
  31612. return serializationObject;
  31613. };
  31614. Plane.Parse = function (parsedPlane, scene) {
  31615. if (scene.getGeometryByID(parsedPlane.id)) {
  31616. return null; // null since geometry could be something else than a ground...
  31617. }
  31618. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31619. if (BABYLON.Tags) {
  31620. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31621. }
  31622. scene.pushGeometry(plane, true);
  31623. return plane;
  31624. };
  31625. return Plane;
  31626. }(_Primitive));
  31627. Primitives.Plane = Plane;
  31628. var TorusKnot = /** @class */ (function (_super) {
  31629. __extends(TorusKnot, _super);
  31630. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31631. if (mesh === void 0) { mesh = null; }
  31632. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31633. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31634. _this.radius = radius;
  31635. _this.tube = tube;
  31636. _this.radialSegments = radialSegments;
  31637. _this.tubularSegments = tubularSegments;
  31638. _this.p = p;
  31639. _this.q = q;
  31640. _this.side = side;
  31641. return _this;
  31642. }
  31643. TorusKnot.prototype._regenerateVertexData = function () {
  31644. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  31645. };
  31646. TorusKnot.prototype.copy = function (id) {
  31647. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31648. };
  31649. TorusKnot.prototype.serialize = function () {
  31650. var serializationObject = _super.prototype.serialize.call(this);
  31651. serializationObject.radius = this.radius;
  31652. serializationObject.tube = this.tube;
  31653. serializationObject.radialSegments = this.radialSegments;
  31654. serializationObject.tubularSegments = this.tubularSegments;
  31655. serializationObject.p = this.p;
  31656. serializationObject.q = this.q;
  31657. return serializationObject;
  31658. };
  31659. ;
  31660. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31661. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31662. return null; // null since geometry could be something else than a ground...
  31663. }
  31664. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31665. if (BABYLON.Tags) {
  31666. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31667. }
  31668. scene.pushGeometry(torusKnot, true);
  31669. return torusKnot;
  31670. };
  31671. return TorusKnot;
  31672. }(_Primitive));
  31673. Primitives.TorusKnot = TorusKnot;
  31674. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31675. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31676. })(BABYLON || (BABYLON = {}));
  31677. //# sourceMappingURL=babylon.geometry.js.map
  31678. var BABYLON;
  31679. (function (BABYLON) {
  31680. var PostProcessManager = /** @class */ (function () {
  31681. function PostProcessManager(scene) {
  31682. this._vertexBuffers = {};
  31683. this._scene = scene;
  31684. }
  31685. PostProcessManager.prototype._prepareBuffers = function () {
  31686. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31687. return;
  31688. }
  31689. // VBO
  31690. var vertices = [];
  31691. vertices.push(1, 1);
  31692. vertices.push(-1, 1);
  31693. vertices.push(-1, -1);
  31694. vertices.push(1, -1);
  31695. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31696. this._buildIndexBuffer();
  31697. };
  31698. PostProcessManager.prototype._buildIndexBuffer = function () {
  31699. // Indices
  31700. var indices = [];
  31701. indices.push(0);
  31702. indices.push(1);
  31703. indices.push(2);
  31704. indices.push(0);
  31705. indices.push(2);
  31706. indices.push(3);
  31707. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31708. };
  31709. PostProcessManager.prototype._rebuild = function () {
  31710. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31711. if (!vb) {
  31712. return;
  31713. }
  31714. vb._rebuild();
  31715. this._buildIndexBuffer();
  31716. };
  31717. // Methods
  31718. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31719. if (sourceTexture === void 0) { sourceTexture = null; }
  31720. if (postProcesses === void 0) { postProcesses = null; }
  31721. var camera = this._scene.activeCamera;
  31722. if (!camera) {
  31723. return false;
  31724. }
  31725. var postProcesses = postProcesses || camera._postProcesses;
  31726. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31727. return false;
  31728. }
  31729. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31730. return true;
  31731. };
  31732. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31733. if (targetTexture === void 0) { targetTexture = null; }
  31734. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31735. if (!this._scene.activeCamera) {
  31736. return;
  31737. }
  31738. var engine = this._scene.getEngine();
  31739. for (var index = 0; index < postProcesses.length; index++) {
  31740. if (index < postProcesses.length - 1) {
  31741. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31742. }
  31743. else {
  31744. if (targetTexture) {
  31745. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31746. }
  31747. else {
  31748. engine.restoreDefaultFramebuffer();
  31749. }
  31750. }
  31751. var pp = postProcesses[index];
  31752. var effect = pp.apply();
  31753. if (effect) {
  31754. pp.onBeforeRenderObservable.notifyObservers(effect);
  31755. // VBOs
  31756. this._prepareBuffers();
  31757. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31758. // Draw order
  31759. engine.draw(true, 0, 6);
  31760. pp.onAfterRenderObservable.notifyObservers(effect);
  31761. }
  31762. }
  31763. // Restore depth buffer
  31764. engine.setDepthBuffer(true);
  31765. engine.setDepthWrite(true);
  31766. };
  31767. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31768. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31769. var camera = this._scene.activeCamera;
  31770. if (!camera) {
  31771. return;
  31772. }
  31773. postProcesses = postProcesses || camera._postProcesses;
  31774. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31775. return;
  31776. }
  31777. var engine = this._scene.getEngine();
  31778. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31779. if (index < len - 1) {
  31780. postProcesses[index + 1].activate(camera, targetTexture);
  31781. }
  31782. else {
  31783. if (targetTexture) {
  31784. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31785. }
  31786. else {
  31787. engine.restoreDefaultFramebuffer();
  31788. }
  31789. }
  31790. if (doNotPresent) {
  31791. break;
  31792. }
  31793. var pp = postProcesses[index];
  31794. var effect = pp.apply();
  31795. if (effect) {
  31796. pp.onBeforeRenderObservable.notifyObservers(effect);
  31797. // VBOs
  31798. this._prepareBuffers();
  31799. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31800. // Draw order
  31801. engine.draw(true, 0, 6);
  31802. pp.onAfterRenderObservable.notifyObservers(effect);
  31803. }
  31804. }
  31805. // Restore states
  31806. engine.setDepthBuffer(true);
  31807. engine.setDepthWrite(true);
  31808. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31809. };
  31810. PostProcessManager.prototype.dispose = function () {
  31811. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31812. if (buffer) {
  31813. buffer.dispose();
  31814. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31815. }
  31816. if (this._indexBuffer) {
  31817. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31818. this._indexBuffer = null;
  31819. }
  31820. };
  31821. return PostProcessManager;
  31822. }());
  31823. BABYLON.PostProcessManager = PostProcessManager;
  31824. })(BABYLON || (BABYLON = {}));
  31825. //# sourceMappingURL=babylon.postProcessManager.js.map
  31826. var BABYLON;
  31827. (function (BABYLON) {
  31828. /**
  31829. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31830. */
  31831. var PerformanceMonitor = /** @class */ (function () {
  31832. /**
  31833. * constructor
  31834. * @param frameSampleSize The number of samples required to saturate the sliding window
  31835. */
  31836. function PerformanceMonitor(frameSampleSize) {
  31837. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31838. this._enabled = true;
  31839. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31840. }
  31841. /**
  31842. * Samples current frame
  31843. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31844. */
  31845. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31846. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31847. if (!this._enabled)
  31848. return;
  31849. if (this._lastFrameTimeMs != null) {
  31850. var dt = timeMs - this._lastFrameTimeMs;
  31851. this._rollingFrameTime.add(dt);
  31852. }
  31853. this._lastFrameTimeMs = timeMs;
  31854. };
  31855. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31856. /**
  31857. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31858. * @return Average frame time in milliseconds
  31859. */
  31860. get: function () {
  31861. return this._rollingFrameTime.average;
  31862. },
  31863. enumerable: true,
  31864. configurable: true
  31865. });
  31866. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31867. /**
  31868. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31869. * @return Frame time variance in milliseconds squared
  31870. */
  31871. get: function () {
  31872. return this._rollingFrameTime.variance;
  31873. },
  31874. enumerable: true,
  31875. configurable: true
  31876. });
  31877. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31878. /**
  31879. * Returns the frame time of the most recent frame
  31880. * @return Frame time in milliseconds
  31881. */
  31882. get: function () {
  31883. return this._rollingFrameTime.history(0);
  31884. },
  31885. enumerable: true,
  31886. configurable: true
  31887. });
  31888. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31889. /**
  31890. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31891. * @return Framerate in frames per second
  31892. */
  31893. get: function () {
  31894. return 1000.0 / this._rollingFrameTime.average;
  31895. },
  31896. enumerable: true,
  31897. configurable: true
  31898. });
  31899. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31900. /**
  31901. * Returns the average framerate in frames per second using the most recent frame time
  31902. * @return Framerate in frames per second
  31903. */
  31904. get: function () {
  31905. var history = this._rollingFrameTime.history(0);
  31906. if (history === 0) {
  31907. return 0;
  31908. }
  31909. return 1000.0 / history;
  31910. },
  31911. enumerable: true,
  31912. configurable: true
  31913. });
  31914. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31915. /**
  31916. * Returns true if enough samples have been taken to completely fill the sliding window
  31917. * @return true if saturated
  31918. */
  31919. get: function () {
  31920. return this._rollingFrameTime.isSaturated();
  31921. },
  31922. enumerable: true,
  31923. configurable: true
  31924. });
  31925. /**
  31926. * Enables contributions to the sliding window sample set
  31927. */
  31928. PerformanceMonitor.prototype.enable = function () {
  31929. this._enabled = true;
  31930. };
  31931. /**
  31932. * Disables contributions to the sliding window sample set
  31933. * Samples will not be interpolated over the disabled period
  31934. */
  31935. PerformanceMonitor.prototype.disable = function () {
  31936. this._enabled = false;
  31937. //clear last sample to avoid interpolating over the disabled period when next enabled
  31938. this._lastFrameTimeMs = null;
  31939. this._lastChangeTimeMs = null;
  31940. };
  31941. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31942. /**
  31943. * Returns true if sampling is enabled
  31944. * @return true if enabled
  31945. */
  31946. get: function () {
  31947. return this._enabled;
  31948. },
  31949. enumerable: true,
  31950. configurable: true
  31951. });
  31952. /**
  31953. * Resets performance monitor
  31954. */
  31955. PerformanceMonitor.prototype.reset = function () {
  31956. //clear last sample to avoid interpolating over the disabled period when next enabled
  31957. this._lastFrameTimeMs = null;
  31958. this._lastChangeTimeMs = null;
  31959. //wipe record
  31960. this._rollingFrameTime.reset();
  31961. };
  31962. return PerformanceMonitor;
  31963. }());
  31964. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31965. /**
  31966. * RollingAverage
  31967. *
  31968. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31969. */
  31970. var RollingAverage = /** @class */ (function () {
  31971. /**
  31972. * constructor
  31973. * @param length The number of samples required to saturate the sliding window
  31974. */
  31975. function RollingAverage(length) {
  31976. this._samples = new Array(length);
  31977. this.reset();
  31978. }
  31979. /**
  31980. * Adds a sample to the sample set
  31981. * @param v The sample value
  31982. */
  31983. RollingAverage.prototype.add = function (v) {
  31984. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31985. var delta;
  31986. //we need to check if we've already wrapped round
  31987. if (this.isSaturated()) {
  31988. //remove bottom of stack from mean
  31989. var bottomValue = this._samples[this._pos];
  31990. delta = bottomValue - this.average;
  31991. this.average -= delta / (this._sampleCount - 1);
  31992. this._m2 -= delta * (bottomValue - this.average);
  31993. }
  31994. else {
  31995. this._sampleCount++;
  31996. }
  31997. //add new value to mean
  31998. delta = v - this.average;
  31999. this.average += delta / (this._sampleCount);
  32000. this._m2 += delta * (v - this.average);
  32001. //set the new variance
  32002. this.variance = this._m2 / (this._sampleCount - 1);
  32003. this._samples[this._pos] = v;
  32004. this._pos++;
  32005. this._pos %= this._samples.length; //positive wrap around
  32006. };
  32007. /**
  32008. * Returns previously added values or null if outside of history or outside the sliding window domain
  32009. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32010. * @return Value previously recorded with add() or null if outside of range
  32011. */
  32012. RollingAverage.prototype.history = function (i) {
  32013. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32014. return 0;
  32015. }
  32016. var i0 = this._wrapPosition(this._pos - 1.0);
  32017. return this._samples[this._wrapPosition(i0 - i)];
  32018. };
  32019. /**
  32020. * Returns true if enough samples have been taken to completely fill the sliding window
  32021. * @return true if sample-set saturated
  32022. */
  32023. RollingAverage.prototype.isSaturated = function () {
  32024. return this._sampleCount >= this._samples.length;
  32025. };
  32026. /**
  32027. * Resets the rolling average (equivalent to 0 samples taken so far)
  32028. */
  32029. RollingAverage.prototype.reset = function () {
  32030. this.average = 0;
  32031. this.variance = 0;
  32032. this._sampleCount = 0;
  32033. this._pos = 0;
  32034. this._m2 = 0;
  32035. };
  32036. /**
  32037. * Wraps a value around the sample range boundaries
  32038. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32039. * @return Wrapped position in sample range
  32040. */
  32041. RollingAverage.prototype._wrapPosition = function (i) {
  32042. var max = this._samples.length;
  32043. return ((i % max) + max) % max;
  32044. };
  32045. return RollingAverage;
  32046. }());
  32047. BABYLON.RollingAverage = RollingAverage;
  32048. })(BABYLON || (BABYLON = {}));
  32049. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32050. var BABYLON;
  32051. (function (BABYLON) {
  32052. /**
  32053. * This groups together the common properties used for image processing either in direct forward pass
  32054. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32055. * or not.
  32056. */
  32057. var ImageProcessingConfiguration = /** @class */ (function () {
  32058. function ImageProcessingConfiguration() {
  32059. /**
  32060. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32061. */
  32062. this.colorCurves = new BABYLON.ColorCurves();
  32063. this._colorCurvesEnabled = false;
  32064. this._colorGradingEnabled = false;
  32065. this._colorGradingWithGreenDepth = true;
  32066. this._colorGradingBGR = true;
  32067. this._exposure = 1.0;
  32068. this._toneMappingEnabled = false;
  32069. this._contrast = 1.0;
  32070. /**
  32071. * Vignette stretch size.
  32072. */
  32073. this.vignetteStretch = 0;
  32074. /**
  32075. * Vignette centre X Offset.
  32076. */
  32077. this.vignetteCentreX = 0;
  32078. /**
  32079. * Vignette centre Y Offset.
  32080. */
  32081. this.vignetteCentreY = 0;
  32082. /**
  32083. * Vignette weight or intensity of the vignette effect.
  32084. */
  32085. this.vignetteWeight = 1.5;
  32086. /**
  32087. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32088. * if vignetteEnabled is set to true.
  32089. */
  32090. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32091. /**
  32092. * Camera field of view used by the Vignette effect.
  32093. */
  32094. this.vignetteCameraFov = 0.5;
  32095. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32096. this._vignetteEnabled = false;
  32097. this._applyByPostProcess = false;
  32098. /**
  32099. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32100. * @type {BABYLON.Observable}
  32101. */
  32102. this.onUpdateParameters = new BABYLON.Observable();
  32103. }
  32104. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32105. /**
  32106. * Gets wether the color curves effect is enabled.
  32107. */
  32108. get: function () {
  32109. return this._colorCurvesEnabled;
  32110. },
  32111. /**
  32112. * Sets wether the color curves effect is enabled.
  32113. */
  32114. set: function (value) {
  32115. if (this._colorCurvesEnabled === value) {
  32116. return;
  32117. }
  32118. this._colorCurvesEnabled = value;
  32119. this._updateParameters();
  32120. },
  32121. enumerable: true,
  32122. configurable: true
  32123. });
  32124. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32125. /**
  32126. * Gets wether the color grading effect is enabled.
  32127. */
  32128. get: function () {
  32129. return this._colorGradingEnabled;
  32130. },
  32131. /**
  32132. * Sets wether the color grading effect is enabled.
  32133. */
  32134. set: function (value) {
  32135. if (this._colorGradingEnabled === value) {
  32136. return;
  32137. }
  32138. this._colorGradingEnabled = value;
  32139. this._updateParameters();
  32140. },
  32141. enumerable: true,
  32142. configurable: true
  32143. });
  32144. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32145. /**
  32146. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32147. */
  32148. get: function () {
  32149. return this._colorGradingWithGreenDepth;
  32150. },
  32151. /**
  32152. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32153. */
  32154. set: function (value) {
  32155. if (this._colorGradingWithGreenDepth === value) {
  32156. return;
  32157. }
  32158. this._colorGradingWithGreenDepth = value;
  32159. this._updateParameters();
  32160. },
  32161. enumerable: true,
  32162. configurable: true
  32163. });
  32164. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32165. /**
  32166. * Gets wether the color grading texture contains BGR values.
  32167. */
  32168. get: function () {
  32169. return this._colorGradingBGR;
  32170. },
  32171. /**
  32172. * Sets wether the color grading texture contains BGR values.
  32173. */
  32174. set: function (value) {
  32175. if (this._colorGradingBGR === value) {
  32176. return;
  32177. }
  32178. this._colorGradingBGR = value;
  32179. this._updateParameters();
  32180. },
  32181. enumerable: true,
  32182. configurable: true
  32183. });
  32184. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32185. /**
  32186. * Gets the Exposure used in the effect.
  32187. */
  32188. get: function () {
  32189. return this._exposure;
  32190. },
  32191. /**
  32192. * Sets the Exposure used in the effect.
  32193. */
  32194. set: function (value) {
  32195. if (this._exposure === value) {
  32196. return;
  32197. }
  32198. this._exposure = value;
  32199. this._updateParameters();
  32200. },
  32201. enumerable: true,
  32202. configurable: true
  32203. });
  32204. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32205. /**
  32206. * Gets wether the tone mapping effect is enabled.
  32207. */
  32208. get: function () {
  32209. return this._toneMappingEnabled;
  32210. },
  32211. /**
  32212. * Sets wether the tone mapping effect is enabled.
  32213. */
  32214. set: function (value) {
  32215. if (this._toneMappingEnabled === value) {
  32216. return;
  32217. }
  32218. this._toneMappingEnabled = value;
  32219. this._updateParameters();
  32220. },
  32221. enumerable: true,
  32222. configurable: true
  32223. });
  32224. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32225. /**
  32226. * Gets the contrast used in the effect.
  32227. */
  32228. get: function () {
  32229. return this._contrast;
  32230. },
  32231. /**
  32232. * Sets the contrast used in the effect.
  32233. */
  32234. set: function (value) {
  32235. if (this._contrast === value) {
  32236. return;
  32237. }
  32238. this._contrast = value;
  32239. this._updateParameters();
  32240. },
  32241. enumerable: true,
  32242. configurable: true
  32243. });
  32244. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32245. /**
  32246. * Gets the vignette blend mode allowing different kind of effect.
  32247. */
  32248. get: function () {
  32249. return this._vignetteBlendMode;
  32250. },
  32251. /**
  32252. * Sets the vignette blend mode allowing different kind of effect.
  32253. */
  32254. set: function (value) {
  32255. if (this._vignetteBlendMode === value) {
  32256. return;
  32257. }
  32258. this._vignetteBlendMode = value;
  32259. this._updateParameters();
  32260. },
  32261. enumerable: true,
  32262. configurable: true
  32263. });
  32264. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32265. /**
  32266. * Gets wether the vignette effect is enabled.
  32267. */
  32268. get: function () {
  32269. return this._vignetteEnabled;
  32270. },
  32271. /**
  32272. * Sets wether the vignette effect is enabled.
  32273. */
  32274. set: function (value) {
  32275. if (this._vignetteEnabled === value) {
  32276. return;
  32277. }
  32278. this._vignetteEnabled = value;
  32279. this._updateParameters();
  32280. },
  32281. enumerable: true,
  32282. configurable: true
  32283. });
  32284. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32285. /**
  32286. * Gets wether the image processing is applied through a post process or not.
  32287. */
  32288. get: function () {
  32289. return this._applyByPostProcess;
  32290. },
  32291. /**
  32292. * Sets wether the image processing is applied through a post process or not.
  32293. */
  32294. set: function (value) {
  32295. if (this._applyByPostProcess === value) {
  32296. return;
  32297. }
  32298. this._applyByPostProcess = value;
  32299. this._updateParameters();
  32300. },
  32301. enumerable: true,
  32302. configurable: true
  32303. });
  32304. /**
  32305. * Method called each time the image processing information changes requires to recompile the effect.
  32306. */
  32307. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32308. this.onUpdateParameters.notifyObservers(this);
  32309. };
  32310. ImageProcessingConfiguration.prototype.getClassName = function () {
  32311. return "ImageProcessingConfiguration";
  32312. };
  32313. /**
  32314. * Prepare the list of uniforms associated with the Image Processing effects.
  32315. * @param uniformsList The list of uniforms used in the effect
  32316. * @param defines the list of defines currently in use
  32317. */
  32318. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32319. if (defines.EXPOSURE) {
  32320. uniforms.push("exposureLinear");
  32321. }
  32322. if (defines.CONTRAST) {
  32323. uniforms.push("contrast");
  32324. }
  32325. if (defines.COLORGRADING) {
  32326. uniforms.push("colorTransformSettings");
  32327. }
  32328. if (defines.VIGNETTE) {
  32329. uniforms.push("vInverseScreenSize");
  32330. uniforms.push("vignetteSettings1");
  32331. uniforms.push("vignetteSettings2");
  32332. }
  32333. if (defines.COLORCURVES) {
  32334. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32335. }
  32336. };
  32337. /**
  32338. * Prepare the list of samplers associated with the Image Processing effects.
  32339. * @param uniformsList The list of uniforms used in the effect
  32340. * @param defines the list of defines currently in use
  32341. */
  32342. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32343. if (defines.COLORGRADING) {
  32344. samplersList.push("txColorTransform");
  32345. }
  32346. };
  32347. /**
  32348. * Prepare the list of defines associated to the shader.
  32349. * @param defines the list of defines to complete
  32350. */
  32351. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32352. if (forPostProcess === void 0) { forPostProcess = false; }
  32353. if (forPostProcess !== this.applyByPostProcess) {
  32354. defines.VIGNETTE = false;
  32355. defines.TONEMAPPING = false;
  32356. defines.CONTRAST = false;
  32357. defines.EXPOSURE = false;
  32358. defines.COLORCURVES = false;
  32359. defines.COLORGRADING = false;
  32360. defines.COLORGRADING3D = false;
  32361. defines.IMAGEPROCESSING = false;
  32362. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32363. return;
  32364. }
  32365. defines.VIGNETTE = this.vignetteEnabled;
  32366. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32367. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32368. defines.TONEMAPPING = this.toneMappingEnabled;
  32369. defines.CONTRAST = (this.contrast !== 1.0);
  32370. defines.EXPOSURE = (this.exposure !== 1.0);
  32371. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32372. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32373. if (defines.COLORGRADING) {
  32374. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32375. }
  32376. else {
  32377. defines.COLORGRADING3D = false;
  32378. }
  32379. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32380. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32381. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32382. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32383. };
  32384. /**
  32385. * Returns true if all the image processing information are ready.
  32386. */
  32387. ImageProcessingConfiguration.prototype.isReady = function () {
  32388. // Color Grading texure can not be none blocking.
  32389. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32390. };
  32391. /**
  32392. * Binds the image processing to the shader.
  32393. * @param effect The effect to bind to
  32394. */
  32395. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32396. if (aspectRatio === void 0) { aspectRatio = 1; }
  32397. // Color Curves
  32398. if (this._colorCurvesEnabled && this.colorCurves) {
  32399. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32400. }
  32401. // Vignette
  32402. if (this._vignetteEnabled) {
  32403. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32404. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32405. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32406. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32407. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32408. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32409. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32410. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32411. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32412. var vignettePower = -2.0 * this.vignetteWeight;
  32413. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32414. }
  32415. // Exposure
  32416. effect.setFloat("exposureLinear", this.exposure);
  32417. // Contrast
  32418. effect.setFloat("contrast", this.contrast);
  32419. // Color transform settings
  32420. if (this.colorGradingTexture) {
  32421. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32422. var textureSize = this.colorGradingTexture.getSize().height;
  32423. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32424. 0.5 / textureSize, // textureOffset
  32425. textureSize, // textureSize
  32426. this.colorGradingTexture.level // weight
  32427. );
  32428. }
  32429. };
  32430. /**
  32431. * Clones the current image processing instance.
  32432. * @return The cloned image processing
  32433. */
  32434. ImageProcessingConfiguration.prototype.clone = function () {
  32435. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32436. };
  32437. /**
  32438. * Serializes the current image processing instance to a json representation.
  32439. * @return a JSON representation
  32440. */
  32441. ImageProcessingConfiguration.prototype.serialize = function () {
  32442. return BABYLON.SerializationHelper.Serialize(this);
  32443. };
  32444. /**
  32445. * Parses the image processing from a json representation.
  32446. * @param source the JSON source to parse
  32447. * @return The parsed image processing
  32448. */
  32449. ImageProcessingConfiguration.Parse = function (source) {
  32450. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32451. };
  32452. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32453. /**
  32454. * Used to apply the vignette as a mix with the pixel color.
  32455. */
  32456. get: function () {
  32457. return this._VIGNETTEMODE_MULTIPLY;
  32458. },
  32459. enumerable: true,
  32460. configurable: true
  32461. });
  32462. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32463. /**
  32464. * Used to apply the vignette as a replacement of the pixel color.
  32465. */
  32466. get: function () {
  32467. return this._VIGNETTEMODE_OPAQUE;
  32468. },
  32469. enumerable: true,
  32470. configurable: true
  32471. });
  32472. // Static constants associated to the image processing.
  32473. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32474. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32475. __decorate([
  32476. BABYLON.serializeAsColorCurves()
  32477. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32478. __decorate([
  32479. BABYLON.serialize()
  32480. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32481. __decorate([
  32482. BABYLON.serializeAsTexture()
  32483. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32484. __decorate([
  32485. BABYLON.serialize()
  32486. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32487. __decorate([
  32488. BABYLON.serialize()
  32489. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32490. __decorate([
  32491. BABYLON.serialize()
  32492. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32493. __decorate([
  32494. BABYLON.serialize()
  32495. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32496. __decorate([
  32497. BABYLON.serialize()
  32498. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32499. __decorate([
  32500. BABYLON.serialize()
  32501. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32502. __decorate([
  32503. BABYLON.serialize()
  32504. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32505. __decorate([
  32506. BABYLON.serialize()
  32507. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32508. __decorate([
  32509. BABYLON.serialize()
  32510. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32511. __decorate([
  32512. BABYLON.serialize()
  32513. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32514. __decorate([
  32515. BABYLON.serializeAsColor4()
  32516. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32517. __decorate([
  32518. BABYLON.serialize()
  32519. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32520. __decorate([
  32521. BABYLON.serialize()
  32522. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32523. __decorate([
  32524. BABYLON.serialize()
  32525. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32526. __decorate([
  32527. BABYLON.serialize()
  32528. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32529. return ImageProcessingConfiguration;
  32530. }());
  32531. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32532. })(BABYLON || (BABYLON = {}));
  32533. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32534. var BABYLON;
  32535. (function (BABYLON) {
  32536. /**
  32537. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32538. * It can help converting any input color in a desired output one. This can then be used to create effects
  32539. * from sepia, black and white to sixties or futuristic rendering...
  32540. *
  32541. * The only supported format is currently 3dl.
  32542. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32543. */
  32544. var ColorGradingTexture = /** @class */ (function (_super) {
  32545. __extends(ColorGradingTexture, _super);
  32546. /**
  32547. * Instantiates a ColorGradingTexture from the following parameters.
  32548. *
  32549. * @param url The location of the color gradind data (currently only supporting 3dl)
  32550. * @param scene The scene the texture will be used in
  32551. */
  32552. function ColorGradingTexture(url, scene) {
  32553. var _this = _super.call(this, scene) || this;
  32554. if (!url) {
  32555. return _this;
  32556. }
  32557. _this._engine = scene.getEngine();
  32558. _this._textureMatrix = BABYLON.Matrix.Identity();
  32559. _this.name = url;
  32560. _this.url = url;
  32561. _this.hasAlpha = false;
  32562. _this.isCube = false;
  32563. _this.is3D = _this._engine.webGLVersion > 1;
  32564. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32565. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32566. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32567. _this.anisotropicFilteringLevel = 1;
  32568. _this._texture = _this._getFromCache(url, true);
  32569. if (!_this._texture) {
  32570. if (!scene.useDelayedTextureLoading) {
  32571. _this.loadTexture();
  32572. }
  32573. else {
  32574. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32575. }
  32576. }
  32577. return _this;
  32578. }
  32579. /**
  32580. * Returns the texture matrix used in most of the material.
  32581. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32582. */
  32583. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32584. return this._textureMatrix;
  32585. };
  32586. /**
  32587. * Occurs when the file being loaded is a .3dl LUT file.
  32588. */
  32589. ColorGradingTexture.prototype.load3dlTexture = function () {
  32590. var engine = this._engine;
  32591. var texture;
  32592. if (engine.webGLVersion === 1) {
  32593. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32594. }
  32595. else {
  32596. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32597. }
  32598. this._texture = texture;
  32599. var callback = function (text) {
  32600. var data = null;
  32601. var tempData = null;
  32602. var line;
  32603. var lines = text.split('\n');
  32604. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32605. var maxColor = 0;
  32606. for (var i = 0; i < lines.length; i++) {
  32607. line = lines[i];
  32608. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32609. continue;
  32610. if (line.indexOf('#') === 0)
  32611. continue;
  32612. var words = line.split(" ");
  32613. if (size === 0) {
  32614. // Number of space + one
  32615. size = words.length;
  32616. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32617. tempData = new Float32Array(size * size * size * 4);
  32618. continue;
  32619. }
  32620. if (size != 0) {
  32621. var r = Math.max(parseInt(words[0]), 0);
  32622. var g = Math.max(parseInt(words[1]), 0);
  32623. var b = Math.max(parseInt(words[2]), 0);
  32624. maxColor = Math.max(r, maxColor);
  32625. maxColor = Math.max(g, maxColor);
  32626. maxColor = Math.max(b, maxColor);
  32627. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32628. if (tempData) {
  32629. tempData[pixelStorageIndex + 0] = r;
  32630. tempData[pixelStorageIndex + 1] = g;
  32631. tempData[pixelStorageIndex + 2] = b;
  32632. }
  32633. pixelIndexSlice++;
  32634. if (pixelIndexSlice % size == 0) {
  32635. pixelIndexH++;
  32636. pixelIndexSlice = 0;
  32637. if (pixelIndexH % size == 0) {
  32638. pixelIndexW++;
  32639. pixelIndexH = 0;
  32640. }
  32641. }
  32642. }
  32643. }
  32644. if (tempData && data) {
  32645. for (var i = 0; i < tempData.length; i++) {
  32646. if (i > 0 && (i + 1) % 4 === 0) {
  32647. data[i] = 255;
  32648. }
  32649. else {
  32650. var value = tempData[i];
  32651. data[i] = (value / maxColor * 255);
  32652. }
  32653. }
  32654. }
  32655. if (texture.is3D) {
  32656. texture.updateSize(size, size, size);
  32657. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32658. }
  32659. else {
  32660. texture.updateSize(size * size, size);
  32661. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32662. }
  32663. };
  32664. BABYLON.Tools.LoadFile(this.url, callback);
  32665. return this._texture;
  32666. };
  32667. /**
  32668. * Starts the loading process of the texture.
  32669. */
  32670. ColorGradingTexture.prototype.loadTexture = function () {
  32671. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32672. this.load3dlTexture();
  32673. }
  32674. };
  32675. /**
  32676. * Clones the color gradind texture.
  32677. */
  32678. ColorGradingTexture.prototype.clone = function () {
  32679. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32680. // Base texture
  32681. newTexture.level = this.level;
  32682. return newTexture;
  32683. };
  32684. /**
  32685. * Called during delayed load for textures.
  32686. */
  32687. ColorGradingTexture.prototype.delayLoad = function () {
  32688. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32689. return;
  32690. }
  32691. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32692. this._texture = this._getFromCache(this.url, true);
  32693. if (!this._texture) {
  32694. this.loadTexture();
  32695. }
  32696. };
  32697. /**
  32698. * Parses a color grading texture serialized by Babylon.
  32699. * @param parsedTexture The texture information being parsedTexture
  32700. * @param scene The scene to load the texture in
  32701. * @param rootUrl The root url of the data assets to load
  32702. * @return A color gradind texture
  32703. */
  32704. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32705. var texture = null;
  32706. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32707. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32708. texture.name = parsedTexture.name;
  32709. texture.level = parsedTexture.level;
  32710. }
  32711. return texture;
  32712. };
  32713. /**
  32714. * Serializes the LUT texture to json format.
  32715. */
  32716. ColorGradingTexture.prototype.serialize = function () {
  32717. if (!this.name) {
  32718. return null;
  32719. }
  32720. var serializationObject = {};
  32721. serializationObject.name = this.name;
  32722. serializationObject.level = this.level;
  32723. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32724. return serializationObject;
  32725. };
  32726. /**
  32727. * Empty line regex stored for GC.
  32728. */
  32729. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32730. return ColorGradingTexture;
  32731. }(BABYLON.BaseTexture));
  32732. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32733. })(BABYLON || (BABYLON = {}));
  32734. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32735. var BABYLON;
  32736. (function (BABYLON) {
  32737. /**
  32738. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32739. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32740. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  32741. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32742. */
  32743. var ColorCurves = /** @class */ (function () {
  32744. function ColorCurves() {
  32745. this._dirty = true;
  32746. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32747. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32748. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32749. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32750. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32751. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32752. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32753. this._globalHue = 30;
  32754. this._globalDensity = 0;
  32755. this._globalSaturation = 0;
  32756. this._globalExposure = 0;
  32757. this._highlightsHue = 30;
  32758. this._highlightsDensity = 0;
  32759. this._highlightsSaturation = 0;
  32760. this._highlightsExposure = 0;
  32761. this._midtonesHue = 30;
  32762. this._midtonesDensity = 0;
  32763. this._midtonesSaturation = 0;
  32764. this._midtonesExposure = 0;
  32765. this._shadowsHue = 30;
  32766. this._shadowsDensity = 0;
  32767. this._shadowsSaturation = 0;
  32768. this._shadowsExposure = 0;
  32769. }
  32770. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32771. /**
  32772. * Gets the global Hue value.
  32773. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  32774. */
  32775. get: function () {
  32776. return this._globalHue;
  32777. },
  32778. /**
  32779. * Sets the global Hue value.
  32780. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  32781. */
  32782. set: function (value) {
  32783. this._globalHue = value;
  32784. this._dirty = true;
  32785. },
  32786. enumerable: true,
  32787. configurable: true
  32788. });
  32789. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32790. /**
  32791. * Gets the global Density value.
  32792. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  32793. * Values less than zero provide a filter of opposite hue.
  32794. */
  32795. get: function () {
  32796. return this._globalDensity;
  32797. },
  32798. /**
  32799. * Sets the global Density value.
  32800. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  32801. * Values less than zero provide a filter of opposite hue.
  32802. */
  32803. set: function (value) {
  32804. this._globalDensity = value;
  32805. this._dirty = true;
  32806. },
  32807. enumerable: true,
  32808. configurable: true
  32809. });
  32810. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32811. /**
  32812. * Gets the global Saturation value.
  32813. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  32814. */
  32815. get: function () {
  32816. return this._globalSaturation;
  32817. },
  32818. /**
  32819. * Sets the global Saturation value.
  32820. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  32821. */
  32822. set: function (value) {
  32823. this._globalSaturation = value;
  32824. this._dirty = true;
  32825. },
  32826. enumerable: true,
  32827. configurable: true
  32828. });
  32829. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32830. /**
  32831. * Gets the highlights Hue value.
  32832. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  32833. */
  32834. get: function () {
  32835. return this._highlightsHue;
  32836. },
  32837. /**
  32838. * Sets the highlights Hue value.
  32839. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  32840. */
  32841. set: function (value) {
  32842. this._highlightsHue = value;
  32843. this._dirty = true;
  32844. },
  32845. enumerable: true,
  32846. configurable: true
  32847. });
  32848. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32849. /**
  32850. * Gets the highlights Density value.
  32851. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  32852. * Values less than zero provide a filter of opposite hue.
  32853. */
  32854. get: function () {
  32855. return this._highlightsDensity;
  32856. },
  32857. /**
  32858. * Sets the highlights Density value.
  32859. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  32860. * Values less than zero provide a filter of opposite hue.
  32861. */
  32862. set: function (value) {
  32863. this._highlightsDensity = value;
  32864. this._dirty = true;
  32865. },
  32866. enumerable: true,
  32867. configurable: true
  32868. });
  32869. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32870. /**
  32871. * Gets the highlights Saturation value.
  32872. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  32873. */
  32874. get: function () {
  32875. return this._highlightsSaturation;
  32876. },
  32877. /**
  32878. * Sets the highlights Saturation value.
  32879. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  32880. */
  32881. set: function (value) {
  32882. this._highlightsSaturation = value;
  32883. this._dirty = true;
  32884. },
  32885. enumerable: true,
  32886. configurable: true
  32887. });
  32888. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32889. /**
  32890. * Gets the highlights Exposure value.
  32891. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  32892. */
  32893. get: function () {
  32894. return this._highlightsExposure;
  32895. },
  32896. /**
  32897. * Sets the highlights Exposure value.
  32898. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  32899. */
  32900. set: function (value) {
  32901. this._highlightsExposure = value;
  32902. this._dirty = true;
  32903. },
  32904. enumerable: true,
  32905. configurable: true
  32906. });
  32907. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32908. /**
  32909. * Gets the midtones Hue value.
  32910. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  32911. */
  32912. get: function () {
  32913. return this._midtonesHue;
  32914. },
  32915. /**
  32916. * Sets the midtones Hue value.
  32917. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  32918. */
  32919. set: function (value) {
  32920. this._midtonesHue = value;
  32921. this._dirty = true;
  32922. },
  32923. enumerable: true,
  32924. configurable: true
  32925. });
  32926. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32927. /**
  32928. * Gets the midtones Density value.
  32929. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  32930. * Values less than zero provide a filter of opposite hue.
  32931. */
  32932. get: function () {
  32933. return this._midtonesDensity;
  32934. },
  32935. /**
  32936. * Sets the midtones Density value.
  32937. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  32938. * Values less than zero provide a filter of opposite hue.
  32939. */
  32940. set: function (value) {
  32941. this._midtonesDensity = value;
  32942. this._dirty = true;
  32943. },
  32944. enumerable: true,
  32945. configurable: true
  32946. });
  32947. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32948. /**
  32949. * Gets the midtones Saturation value.
  32950. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  32951. */
  32952. get: function () {
  32953. return this._midtonesSaturation;
  32954. },
  32955. /**
  32956. * Sets the midtones Saturation value.
  32957. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  32958. */
  32959. set: function (value) {
  32960. this._midtonesSaturation = value;
  32961. this._dirty = true;
  32962. },
  32963. enumerable: true,
  32964. configurable: true
  32965. });
  32966. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32967. /**
  32968. * Gets the midtones Exposure value.
  32969. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  32970. */
  32971. get: function () {
  32972. return this._midtonesExposure;
  32973. },
  32974. /**
  32975. * Sets the midtones Exposure value.
  32976. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  32977. */
  32978. set: function (value) {
  32979. this._midtonesExposure = value;
  32980. this._dirty = true;
  32981. },
  32982. enumerable: true,
  32983. configurable: true
  32984. });
  32985. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32986. /**
  32987. * Gets the shadows Hue value.
  32988. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  32989. */
  32990. get: function () {
  32991. return this._shadowsHue;
  32992. },
  32993. /**
  32994. * Sets the shadows Hue value.
  32995. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  32996. */
  32997. set: function (value) {
  32998. this._shadowsHue = value;
  32999. this._dirty = true;
  33000. },
  33001. enumerable: true,
  33002. configurable: true
  33003. });
  33004. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33005. /**
  33006. * Gets the shadows Density value.
  33007. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33008. * Values less than zero provide a filter of opposite hue.
  33009. */
  33010. get: function () {
  33011. return this._shadowsDensity;
  33012. },
  33013. /**
  33014. * Sets the shadows Density value.
  33015. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33016. * Values less than zero provide a filter of opposite hue.
  33017. */
  33018. set: function (value) {
  33019. this._shadowsDensity = value;
  33020. this._dirty = true;
  33021. },
  33022. enumerable: true,
  33023. configurable: true
  33024. });
  33025. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33026. /**
  33027. * Gets the shadows Saturation value.
  33028. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33029. */
  33030. get: function () {
  33031. return this._shadowsSaturation;
  33032. },
  33033. /**
  33034. * Sets the shadows Saturation value.
  33035. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33036. */
  33037. set: function (value) {
  33038. this._shadowsSaturation = value;
  33039. this._dirty = true;
  33040. },
  33041. enumerable: true,
  33042. configurable: true
  33043. });
  33044. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33045. /**
  33046. * Gets the shadows Exposure value.
  33047. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  33048. */
  33049. get: function () {
  33050. return this._shadowsExposure;
  33051. },
  33052. /**
  33053. * Sets the shadows Exposure value.
  33054. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  33055. */
  33056. set: function (value) {
  33057. this._shadowsExposure = value;
  33058. this._dirty = true;
  33059. },
  33060. enumerable: true,
  33061. configurable: true
  33062. });
  33063. ColorCurves.prototype.getClassName = function () {
  33064. return "ColorCurves";
  33065. };
  33066. /**
  33067. * Binds the color curves to the shader.
  33068. * @param colorCurves The color curve to bind
  33069. * @param effect The effect to bind to
  33070. */
  33071. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33072. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33073. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33074. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33075. if (colorCurves._dirty) {
  33076. colorCurves._dirty = false;
  33077. // Fill in global info.
  33078. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33079. // Compute highlights info.
  33080. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33081. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33082. // Compute midtones info.
  33083. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33084. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33085. // Compute shadows info.
  33086. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33087. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33088. // Compute deltas (neutral is midtones).
  33089. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33090. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33091. }
  33092. if (effect) {
  33093. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33094. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33095. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33096. }
  33097. };
  33098. /**
  33099. * Prepare the list of uniforms associated with the ColorCurves effects.
  33100. * @param uniformsList The list of uniforms used in the effect
  33101. */
  33102. ColorCurves.PrepareUniforms = function (uniformsList) {
  33103. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33104. };
  33105. /**
  33106. * Returns color grading data based on a hue, density, saturation and exposure value.
  33107. * @param filterHue The hue of the color filter.
  33108. * @param filterDensity The density of the color filter.
  33109. * @param saturation The saturation.
  33110. * @param exposure The exposure.
  33111. * @param result The result data container.
  33112. */
  33113. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33114. if (hue == null) {
  33115. return;
  33116. }
  33117. hue = ColorCurves.clamp(hue, 0, 360);
  33118. density = ColorCurves.clamp(density, -100, 100);
  33119. saturation = ColorCurves.clamp(saturation, -100, 100);
  33120. exposure = ColorCurves.clamp(exposure, -100, 100);
  33121. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33122. // so that the maximum filter density is only 50% control. This provides fine control
  33123. // for small values and reasonable range.
  33124. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33125. density *= 0.5;
  33126. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33127. if (density < 0) {
  33128. density *= -1;
  33129. hue = (hue + 180) % 360;
  33130. }
  33131. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33132. result.scaleToRef(2, result);
  33133. result.a = 1 + 0.01 * saturation;
  33134. };
  33135. /**
  33136. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33137. * @param value The input slider value in range [-100,100].
  33138. * @returns Adjusted value.
  33139. */
  33140. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33141. value /= 100;
  33142. var x = Math.abs(value);
  33143. x = Math.pow(x, 2);
  33144. if (value < 0) {
  33145. x *= -1;
  33146. }
  33147. x *= 100;
  33148. return x;
  33149. };
  33150. /**
  33151. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33152. * @param hue The hue (H) input.
  33153. * @param saturation The saturation (S) input.
  33154. * @param brightness The brightness (B) input.
  33155. * @result An RGBA color represented as Vector4.
  33156. */
  33157. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33158. var h = ColorCurves.clamp(hue, 0, 360);
  33159. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33160. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33161. if (s === 0) {
  33162. result.r = v;
  33163. result.g = v;
  33164. result.b = v;
  33165. }
  33166. else {
  33167. // sector 0 to 5
  33168. h /= 60;
  33169. var i = Math.floor(h);
  33170. // fractional part of h
  33171. var f = h - i;
  33172. var p = v * (1 - s);
  33173. var q = v * (1 - s * f);
  33174. var t = v * (1 - s * (1 - f));
  33175. switch (i) {
  33176. case 0:
  33177. result.r = v;
  33178. result.g = t;
  33179. result.b = p;
  33180. break;
  33181. case 1:
  33182. result.r = q;
  33183. result.g = v;
  33184. result.b = p;
  33185. break;
  33186. case 2:
  33187. result.r = p;
  33188. result.g = v;
  33189. result.b = t;
  33190. break;
  33191. case 3:
  33192. result.r = p;
  33193. result.g = q;
  33194. result.b = v;
  33195. break;
  33196. case 4:
  33197. result.r = t;
  33198. result.g = p;
  33199. result.b = v;
  33200. break;
  33201. default:// case 5:
  33202. result.r = v;
  33203. result.g = p;
  33204. result.b = q;
  33205. break;
  33206. }
  33207. }
  33208. result.a = 1;
  33209. };
  33210. /**
  33211. * Returns a value clamped between min and max
  33212. * @param value The value to clamp
  33213. * @param min The minimum of value
  33214. * @param max The maximum of value
  33215. * @returns The clamped value.
  33216. */
  33217. ColorCurves.clamp = function (value, min, max) {
  33218. return Math.min(Math.max(value, min), max);
  33219. };
  33220. /**
  33221. * Clones the current color curve instance.
  33222. * @return The cloned curves
  33223. */
  33224. ColorCurves.prototype.clone = function () {
  33225. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33226. };
  33227. /**
  33228. * Serializes the current color curve instance to a json representation.
  33229. * @return a JSON representation
  33230. */
  33231. ColorCurves.prototype.serialize = function () {
  33232. return BABYLON.SerializationHelper.Serialize(this);
  33233. };
  33234. /**
  33235. * Parses the color curve from a json representation.
  33236. * @param source the JSON source to parse
  33237. * @return The parsed curves
  33238. */
  33239. ColorCurves.Parse = function (source) {
  33240. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33241. };
  33242. __decorate([
  33243. BABYLON.serialize()
  33244. ], ColorCurves.prototype, "_globalHue", void 0);
  33245. __decorate([
  33246. BABYLON.serialize()
  33247. ], ColorCurves.prototype, "_globalDensity", void 0);
  33248. __decorate([
  33249. BABYLON.serialize()
  33250. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33251. __decorate([
  33252. BABYLON.serialize()
  33253. ], ColorCurves.prototype, "_globalExposure", void 0);
  33254. __decorate([
  33255. BABYLON.serialize()
  33256. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33257. __decorate([
  33258. BABYLON.serialize()
  33259. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33260. __decorate([
  33261. BABYLON.serialize()
  33262. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33263. __decorate([
  33264. BABYLON.serialize()
  33265. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33266. __decorate([
  33267. BABYLON.serialize()
  33268. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33269. __decorate([
  33270. BABYLON.serialize()
  33271. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33272. __decorate([
  33273. BABYLON.serialize()
  33274. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33275. __decorate([
  33276. BABYLON.serialize()
  33277. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33278. return ColorCurves;
  33279. }());
  33280. BABYLON.ColorCurves = ColorCurves;
  33281. })(BABYLON || (BABYLON = {}));
  33282. //# sourceMappingURL=babylon.colorCurves.js.map
  33283. var BABYLON;
  33284. (function (BABYLON) {
  33285. var StandardMaterialDefines = /** @class */ (function (_super) {
  33286. __extends(StandardMaterialDefines, _super);
  33287. function StandardMaterialDefines() {
  33288. var _this = _super.call(this) || this;
  33289. _this.MAINUV1 = false;
  33290. _this.MAINUV2 = false;
  33291. _this.DIFFUSE = false;
  33292. _this.DIFFUSEDIRECTUV = 0;
  33293. _this.AMBIENT = false;
  33294. _this.AMBIENTDIRECTUV = 0;
  33295. _this.OPACITY = false;
  33296. _this.OPACITYDIRECTUV = 0;
  33297. _this.OPACITYRGB = false;
  33298. _this.REFLECTION = false;
  33299. _this.EMISSIVE = false;
  33300. _this.EMISSIVEDIRECTUV = 0;
  33301. _this.SPECULAR = false;
  33302. _this.SPECULARDIRECTUV = 0;
  33303. _this.BUMP = false;
  33304. _this.BUMPDIRECTUV = 0;
  33305. _this.PARALLAX = false;
  33306. _this.PARALLAXOCCLUSION = false;
  33307. _this.SPECULAROVERALPHA = false;
  33308. _this.CLIPPLANE = false;
  33309. _this.ALPHATEST = false;
  33310. _this.DEPTHPREPASS = false;
  33311. _this.ALPHAFROMDIFFUSE = false;
  33312. _this.POINTSIZE = false;
  33313. _this.FOG = false;
  33314. _this.SPECULARTERM = false;
  33315. _this.DIFFUSEFRESNEL = false;
  33316. _this.OPACITYFRESNEL = false;
  33317. _this.REFLECTIONFRESNEL = false;
  33318. _this.REFRACTIONFRESNEL = false;
  33319. _this.EMISSIVEFRESNEL = false;
  33320. _this.FRESNEL = false;
  33321. _this.NORMAL = false;
  33322. _this.UV1 = false;
  33323. _this.UV2 = false;
  33324. _this.VERTEXCOLOR = false;
  33325. _this.VERTEXALPHA = false;
  33326. _this.NUM_BONE_INFLUENCERS = 0;
  33327. _this.BonesPerMesh = 0;
  33328. _this.INSTANCES = false;
  33329. _this.GLOSSINESS = false;
  33330. _this.ROUGHNESS = false;
  33331. _this.EMISSIVEASILLUMINATION = false;
  33332. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33333. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33334. _this.LIGHTMAP = false;
  33335. _this.LIGHTMAPDIRECTUV = 0;
  33336. _this.USELIGHTMAPASSHADOWMAP = false;
  33337. _this.REFLECTIONMAP_3D = false;
  33338. _this.REFLECTIONMAP_SPHERICAL = false;
  33339. _this.REFLECTIONMAP_PLANAR = false;
  33340. _this.REFLECTIONMAP_CUBIC = false;
  33341. _this.REFLECTIONMAP_PROJECTION = false;
  33342. _this.REFLECTIONMAP_SKYBOX = false;
  33343. _this.REFLECTIONMAP_EXPLICIT = false;
  33344. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33345. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33346. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33347. _this.INVERTCUBICMAP = false;
  33348. _this.LOGARITHMICDEPTH = false;
  33349. _this.REFRACTION = false;
  33350. _this.REFRACTIONMAP_3D = false;
  33351. _this.REFLECTIONOVERALPHA = false;
  33352. _this.TWOSIDEDLIGHTING = false;
  33353. _this.SHADOWFLOAT = false;
  33354. _this.MORPHTARGETS = false;
  33355. _this.MORPHTARGETS_NORMAL = false;
  33356. _this.MORPHTARGETS_TANGENT = false;
  33357. _this.NUM_MORPH_INFLUENCERS = 0;
  33358. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33359. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33360. _this.IMAGEPROCESSING = false;
  33361. _this.VIGNETTE = false;
  33362. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33363. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33364. _this.TONEMAPPING = false;
  33365. _this.CONTRAST = false;
  33366. _this.COLORCURVES = false;
  33367. _this.COLORGRADING = false;
  33368. _this.COLORGRADING3D = false;
  33369. _this.SAMPLER3DGREENDEPTH = false;
  33370. _this.SAMPLER3DBGRMAP = false;
  33371. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33372. _this.EXPOSURE = false;
  33373. _this.rebuild();
  33374. return _this;
  33375. }
  33376. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33377. var modes = [
  33378. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33379. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33380. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33381. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33382. ];
  33383. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33384. var mode = modes_1[_i];
  33385. this[mode] = (mode === modeToEnable);
  33386. }
  33387. };
  33388. return StandardMaterialDefines;
  33389. }(BABYLON.MaterialDefines));
  33390. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33391. var StandardMaterial = /** @class */ (function (_super) {
  33392. __extends(StandardMaterial, _super);
  33393. function StandardMaterial(name, scene) {
  33394. var _this = _super.call(this, name, scene) || this;
  33395. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33396. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33397. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33398. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33399. _this.specularPower = 64;
  33400. _this._useAlphaFromDiffuseTexture = false;
  33401. _this._useEmissiveAsIllumination = false;
  33402. _this._linkEmissiveWithDiffuse = false;
  33403. _this._useSpecularOverAlpha = false;
  33404. _this._useReflectionOverAlpha = false;
  33405. _this._disableLighting = false;
  33406. _this._useParallax = false;
  33407. _this._useParallaxOcclusion = false;
  33408. _this.parallaxScaleBias = 0.05;
  33409. _this._roughness = 0;
  33410. _this.indexOfRefraction = 0.98;
  33411. _this.invertRefractionY = true;
  33412. _this._useLightmapAsShadowmap = false;
  33413. _this._useReflectionFresnelFromSpecular = false;
  33414. _this._useGlossinessFromSpecularMapAlpha = false;
  33415. _this._maxSimultaneousLights = 4;
  33416. /**
  33417. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33418. */
  33419. _this._invertNormalMapX = false;
  33420. /**
  33421. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33422. */
  33423. _this._invertNormalMapY = false;
  33424. /**
  33425. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33426. */
  33427. _this._twoSidedLighting = false;
  33428. _this._renderTargets = new BABYLON.SmartArray(16);
  33429. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33430. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33431. // Setup the default processing configuration to the scene.
  33432. _this._attachImageProcessingConfiguration(null);
  33433. _this.getRenderTargetTextures = function () {
  33434. _this._renderTargets.reset();
  33435. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33436. _this._renderTargets.push(_this._reflectionTexture);
  33437. }
  33438. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33439. _this._renderTargets.push(_this._refractionTexture);
  33440. }
  33441. return _this._renderTargets;
  33442. };
  33443. return _this;
  33444. }
  33445. ;
  33446. ;
  33447. ;
  33448. ;
  33449. ;
  33450. ;
  33451. ;
  33452. ;
  33453. ;
  33454. ;
  33455. ;
  33456. ;
  33457. ;
  33458. ;
  33459. ;
  33460. ;
  33461. ;
  33462. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33463. /**
  33464. * Gets the image processing configuration used either in this material.
  33465. */
  33466. get: function () {
  33467. return this._imageProcessingConfiguration;
  33468. },
  33469. /**
  33470. * Sets the Default image processing configuration used either in the this material.
  33471. *
  33472. * If sets to null, the scene one is in use.
  33473. */
  33474. set: function (value) {
  33475. this._attachImageProcessingConfiguration(value);
  33476. // Ensure the effect will be rebuilt.
  33477. this._markAllSubMeshesAsTexturesDirty();
  33478. },
  33479. enumerable: true,
  33480. configurable: true
  33481. });
  33482. /**
  33483. * Attaches a new image processing configuration to the Standard Material.
  33484. * @param configuration
  33485. */
  33486. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33487. var _this = this;
  33488. if (configuration === this._imageProcessingConfiguration) {
  33489. return;
  33490. }
  33491. // Detaches observer.
  33492. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33493. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33494. }
  33495. // Pick the scene configuration if needed.
  33496. if (!configuration) {
  33497. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33498. }
  33499. else {
  33500. this._imageProcessingConfiguration = configuration;
  33501. }
  33502. // Attaches observer.
  33503. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33504. _this._markAllSubMeshesAsImageProcessingDirty();
  33505. });
  33506. };
  33507. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33508. /**
  33509. * Gets wether the color curves effect is enabled.
  33510. */
  33511. get: function () {
  33512. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33513. },
  33514. /**
  33515. * Sets wether the color curves effect is enabled.
  33516. */
  33517. set: function (value) {
  33518. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33519. },
  33520. enumerable: true,
  33521. configurable: true
  33522. });
  33523. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33524. /**
  33525. * Gets wether the color grading effect is enabled.
  33526. */
  33527. get: function () {
  33528. return this.imageProcessingConfiguration.colorGradingEnabled;
  33529. },
  33530. /**
  33531. * Gets wether the color grading effect is enabled.
  33532. */
  33533. set: function (value) {
  33534. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33535. },
  33536. enumerable: true,
  33537. configurable: true
  33538. });
  33539. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33540. /**
  33541. * Gets wether tonemapping is enabled or not.
  33542. */
  33543. get: function () {
  33544. return this._imageProcessingConfiguration.toneMappingEnabled;
  33545. },
  33546. /**
  33547. * Sets wether tonemapping is enabled or not
  33548. */
  33549. set: function (value) {
  33550. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33551. },
  33552. enumerable: true,
  33553. configurable: true
  33554. });
  33555. ;
  33556. ;
  33557. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33558. /**
  33559. * The camera exposure used on this material.
  33560. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33561. * This corresponds to a photographic exposure.
  33562. */
  33563. get: function () {
  33564. return this._imageProcessingConfiguration.exposure;
  33565. },
  33566. /**
  33567. * The camera exposure used on this material.
  33568. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33569. * This corresponds to a photographic exposure.
  33570. */
  33571. set: function (value) {
  33572. this._imageProcessingConfiguration.exposure = value;
  33573. },
  33574. enumerable: true,
  33575. configurable: true
  33576. });
  33577. ;
  33578. ;
  33579. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33580. /**
  33581. * Gets The camera contrast used on this material.
  33582. */
  33583. get: function () {
  33584. return this._imageProcessingConfiguration.contrast;
  33585. },
  33586. /**
  33587. * Sets The camera contrast used on this material.
  33588. */
  33589. set: function (value) {
  33590. this._imageProcessingConfiguration.contrast = value;
  33591. },
  33592. enumerable: true,
  33593. configurable: true
  33594. });
  33595. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33596. /**
  33597. * Gets the Color Grading 2D Lookup Texture.
  33598. */
  33599. get: function () {
  33600. return this._imageProcessingConfiguration.colorGradingTexture;
  33601. },
  33602. /**
  33603. * Sets the Color Grading 2D Lookup Texture.
  33604. */
  33605. set: function (value) {
  33606. this._imageProcessingConfiguration.colorGradingTexture = value;
  33607. },
  33608. enumerable: true,
  33609. configurable: true
  33610. });
  33611. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33612. /**
  33613. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33614. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33615. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  33616. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33617. */
  33618. get: function () {
  33619. return this._imageProcessingConfiguration.colorCurves;
  33620. },
  33621. /**
  33622. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33623. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33624. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  33625. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33626. */
  33627. set: function (value) {
  33628. this._imageProcessingConfiguration.colorCurves = value;
  33629. },
  33630. enumerable: true,
  33631. configurable: true
  33632. });
  33633. StandardMaterial.prototype.getClassName = function () {
  33634. return "StandardMaterial";
  33635. };
  33636. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33637. get: function () {
  33638. return this._useLogarithmicDepth;
  33639. },
  33640. set: function (value) {
  33641. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33642. this._markAllSubMeshesAsMiscDirty();
  33643. },
  33644. enumerable: true,
  33645. configurable: true
  33646. });
  33647. StandardMaterial.prototype.needAlphaBlending = function () {
  33648. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33649. };
  33650. StandardMaterial.prototype.needAlphaTesting = function () {
  33651. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33652. };
  33653. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33654. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33655. };
  33656. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33657. return this._diffuseTexture;
  33658. };
  33659. /**
  33660. * Child classes can use it to update shaders
  33661. */
  33662. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33663. if (useInstances === void 0) { useInstances = false; }
  33664. if (subMesh.effect && this.isFrozen) {
  33665. if (this._wasPreviouslyReady && subMesh.effect) {
  33666. return true;
  33667. }
  33668. }
  33669. if (!subMesh._materialDefines) {
  33670. subMesh._materialDefines = new StandardMaterialDefines();
  33671. }
  33672. var scene = this.getScene();
  33673. var defines = subMesh._materialDefines;
  33674. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33675. if (defines._renderId === scene.getRenderId()) {
  33676. return true;
  33677. }
  33678. }
  33679. var engine = scene.getEngine();
  33680. // Lights
  33681. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33682. // Textures
  33683. if (defines._areTexturesDirty) {
  33684. defines._needUVs = false;
  33685. defines.MAINUV1 = false;
  33686. defines.MAINUV2 = false;
  33687. if (scene.texturesEnabled) {
  33688. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33689. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33690. return false;
  33691. }
  33692. else {
  33693. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33694. }
  33695. }
  33696. else {
  33697. defines.DIFFUSE = false;
  33698. }
  33699. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33700. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33701. return false;
  33702. }
  33703. else {
  33704. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33705. }
  33706. }
  33707. else {
  33708. defines.AMBIENT = false;
  33709. }
  33710. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33711. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33712. return false;
  33713. }
  33714. else {
  33715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33716. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33717. }
  33718. }
  33719. else {
  33720. defines.OPACITY = false;
  33721. }
  33722. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33723. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33724. return false;
  33725. }
  33726. else {
  33727. defines._needNormals = true;
  33728. defines.REFLECTION = true;
  33729. defines.ROUGHNESS = (this._roughness > 0);
  33730. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33731. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33732. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33733. switch (this._reflectionTexture.coordinatesMode) {
  33734. case BABYLON.Texture.CUBIC_MODE:
  33735. case BABYLON.Texture.INVCUBIC_MODE:
  33736. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33737. break;
  33738. case BABYLON.Texture.EXPLICIT_MODE:
  33739. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33740. break;
  33741. case BABYLON.Texture.PLANAR_MODE:
  33742. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33743. break;
  33744. case BABYLON.Texture.PROJECTION_MODE:
  33745. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33746. break;
  33747. case BABYLON.Texture.SKYBOX_MODE:
  33748. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33749. break;
  33750. case BABYLON.Texture.SPHERICAL_MODE:
  33751. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33752. break;
  33753. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33754. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33755. break;
  33756. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33757. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33758. break;
  33759. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33760. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33761. break;
  33762. }
  33763. }
  33764. }
  33765. else {
  33766. defines.REFLECTION = false;
  33767. }
  33768. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33769. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33770. return false;
  33771. }
  33772. else {
  33773. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33774. }
  33775. }
  33776. else {
  33777. defines.EMISSIVE = false;
  33778. }
  33779. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33780. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33781. return false;
  33782. }
  33783. else {
  33784. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33785. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33786. }
  33787. }
  33788. else {
  33789. defines.LIGHTMAP = false;
  33790. }
  33791. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33792. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33793. return false;
  33794. }
  33795. else {
  33796. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33797. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33798. }
  33799. }
  33800. else {
  33801. defines.SPECULAR = false;
  33802. }
  33803. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33804. // Bump texure can not be not blocking.
  33805. if (!this._bumpTexture.isReady()) {
  33806. return false;
  33807. }
  33808. else {
  33809. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33810. defines.PARALLAX = this._useParallax;
  33811. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33812. }
  33813. }
  33814. else {
  33815. defines.BUMP = false;
  33816. }
  33817. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33818. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33819. return false;
  33820. }
  33821. else {
  33822. defines._needUVs = true;
  33823. defines.REFRACTION = true;
  33824. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33825. }
  33826. }
  33827. else {
  33828. defines.REFRACTION = false;
  33829. }
  33830. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33831. }
  33832. else {
  33833. defines.DIFFUSE = false;
  33834. defines.AMBIENT = false;
  33835. defines.OPACITY = false;
  33836. defines.REFLECTION = false;
  33837. defines.EMISSIVE = false;
  33838. defines.LIGHTMAP = false;
  33839. defines.BUMP = false;
  33840. defines.REFRACTION = false;
  33841. }
  33842. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33843. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33844. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33845. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33846. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33847. }
  33848. if (defines._areImageProcessingDirty) {
  33849. if (!this._imageProcessingConfiguration.isReady()) {
  33850. return false;
  33851. }
  33852. this._imageProcessingConfiguration.prepareDefines(defines);
  33853. }
  33854. if (defines._areFresnelDirty) {
  33855. if (StandardMaterial.FresnelEnabled) {
  33856. // Fresnel
  33857. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33858. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33859. this._reflectionFresnelParameters) {
  33860. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33861. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33862. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33863. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33864. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33865. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33866. defines._needNormals = true;
  33867. defines.FRESNEL = true;
  33868. }
  33869. }
  33870. else {
  33871. defines.FRESNEL = false;
  33872. }
  33873. }
  33874. // Misc.
  33875. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33876. // Attribs
  33877. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33878. // Values that need to be evaluated on every frame
  33879. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33880. // Get correct effect
  33881. if (defines.isDirty) {
  33882. defines.markAsProcessed();
  33883. scene.resetCachedMaterial();
  33884. // Fallbacks
  33885. var fallbacks = new BABYLON.EffectFallbacks();
  33886. if (defines.REFLECTION) {
  33887. fallbacks.addFallback(0, "REFLECTION");
  33888. }
  33889. if (defines.SPECULAR) {
  33890. fallbacks.addFallback(0, "SPECULAR");
  33891. }
  33892. if (defines.BUMP) {
  33893. fallbacks.addFallback(0, "BUMP");
  33894. }
  33895. if (defines.PARALLAX) {
  33896. fallbacks.addFallback(1, "PARALLAX");
  33897. }
  33898. if (defines.PARALLAXOCCLUSION) {
  33899. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33900. }
  33901. if (defines.SPECULAROVERALPHA) {
  33902. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33903. }
  33904. if (defines.FOG) {
  33905. fallbacks.addFallback(1, "FOG");
  33906. }
  33907. if (defines.POINTSIZE) {
  33908. fallbacks.addFallback(0, "POINTSIZE");
  33909. }
  33910. if (defines.LOGARITHMICDEPTH) {
  33911. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33912. }
  33913. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33914. if (defines.SPECULARTERM) {
  33915. fallbacks.addFallback(0, "SPECULARTERM");
  33916. }
  33917. if (defines.DIFFUSEFRESNEL) {
  33918. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33919. }
  33920. if (defines.OPACITYFRESNEL) {
  33921. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33922. }
  33923. if (defines.REFLECTIONFRESNEL) {
  33924. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33925. }
  33926. if (defines.EMISSIVEFRESNEL) {
  33927. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33928. }
  33929. if (defines.FRESNEL) {
  33930. fallbacks.addFallback(4, "FRESNEL");
  33931. }
  33932. //Attributes
  33933. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33934. if (defines.NORMAL) {
  33935. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33936. }
  33937. if (defines.UV1) {
  33938. attribs.push(BABYLON.VertexBuffer.UVKind);
  33939. }
  33940. if (defines.UV2) {
  33941. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33942. }
  33943. if (defines.VERTEXCOLOR) {
  33944. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33945. }
  33946. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33947. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33948. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33949. var shaderName = "default";
  33950. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33951. "vFogInfos", "vFogColor", "pointSize",
  33952. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33953. "mBones",
  33954. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33955. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33956. "logarithmicDepthConstant", "vTangentSpaceParams"
  33957. ];
  33958. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33959. var uniformBuffers = ["Material", "Scene"];
  33960. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33961. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33962. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33963. uniformsNames: uniforms,
  33964. uniformBuffersNames: uniformBuffers,
  33965. samplers: samplers,
  33966. defines: defines,
  33967. maxSimultaneousLights: this._maxSimultaneousLights
  33968. });
  33969. if (this.customShaderNameResolve) {
  33970. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33971. }
  33972. var join = defines.toString();
  33973. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33974. attributes: attribs,
  33975. uniformsNames: uniforms,
  33976. uniformBuffersNames: uniformBuffers,
  33977. samplers: samplers,
  33978. defines: join,
  33979. fallbacks: fallbacks,
  33980. onCompiled: this.onCompiled,
  33981. onError: this.onError,
  33982. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33983. }, engine), defines);
  33984. this.buildUniformLayout();
  33985. }
  33986. if (!subMesh.effect || !subMesh.effect.isReady()) {
  33987. return false;
  33988. }
  33989. defines._renderId = scene.getRenderId();
  33990. this._wasPreviouslyReady = true;
  33991. return true;
  33992. };
  33993. StandardMaterial.prototype.buildUniformLayout = function () {
  33994. // Order is important !
  33995. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33996. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33997. this._uniformBuffer.addUniform("opacityParts", 4);
  33998. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33999. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34000. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34001. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34002. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34003. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34004. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34005. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34006. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34007. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34008. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34009. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34010. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34011. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34012. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34013. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34014. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34015. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34016. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34017. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34018. this._uniformBuffer.addUniform("specularMatrix", 16);
  34019. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34020. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34021. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34022. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34023. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34024. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34025. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34026. this._uniformBuffer.addUniform("pointSize", 1);
  34027. this._uniformBuffer.create();
  34028. };
  34029. StandardMaterial.prototype.unbind = function () {
  34030. if (this._activeEffect) {
  34031. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34032. this._activeEffect.setTexture("reflection2DSampler", null);
  34033. }
  34034. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34035. this._activeEffect.setTexture("refraction2DSampler", null);
  34036. }
  34037. }
  34038. _super.prototype.unbind.call(this);
  34039. };
  34040. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34041. var scene = this.getScene();
  34042. var defines = subMesh._materialDefines;
  34043. if (!defines) {
  34044. return;
  34045. }
  34046. var effect = subMesh.effect;
  34047. if (!effect) {
  34048. return;
  34049. }
  34050. this._activeEffect = effect;
  34051. // Matrices
  34052. this.bindOnlyWorldMatrix(world);
  34053. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34054. // Bones
  34055. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34056. if (mustRebind) {
  34057. this._uniformBuffer.bindToEffect(effect, "Material");
  34058. this.bindViewProjection(effect);
  34059. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34060. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34061. // Fresnel
  34062. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34063. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34064. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34065. }
  34066. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34067. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34068. }
  34069. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34070. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34071. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34072. }
  34073. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34074. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34075. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34076. }
  34077. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34078. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34079. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34080. }
  34081. }
  34082. // Textures
  34083. if (scene.texturesEnabled) {
  34084. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34085. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34086. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34087. }
  34088. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34089. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34090. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34091. }
  34092. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34093. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34094. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34095. }
  34096. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34097. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34098. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34099. }
  34100. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34101. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34102. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34103. }
  34104. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34105. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34106. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34107. }
  34108. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34109. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34110. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34111. }
  34112. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34113. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34114. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34115. if (scene._mirroredCameraPosition) {
  34116. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34117. }
  34118. else {
  34119. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34120. }
  34121. }
  34122. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34123. var depth = 1.0;
  34124. if (!this._refractionTexture.isCube) {
  34125. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34126. if (this._refractionTexture.depth) {
  34127. depth = this._refractionTexture.depth;
  34128. }
  34129. }
  34130. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34131. }
  34132. }
  34133. // Point size
  34134. if (this.pointsCloud) {
  34135. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34136. }
  34137. if (defines.SPECULARTERM) {
  34138. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34139. }
  34140. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34141. // Diffuse
  34142. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34143. }
  34144. // Textures
  34145. if (scene.texturesEnabled) {
  34146. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34147. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34148. }
  34149. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34150. effect.setTexture("ambientSampler", this._ambientTexture);
  34151. }
  34152. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34153. effect.setTexture("opacitySampler", this._opacityTexture);
  34154. }
  34155. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34156. if (this._reflectionTexture.isCube) {
  34157. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34158. }
  34159. else {
  34160. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34161. }
  34162. }
  34163. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34164. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34165. }
  34166. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34167. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34168. }
  34169. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34170. effect.setTexture("specularSampler", this._specularTexture);
  34171. }
  34172. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34173. effect.setTexture("bumpSampler", this._bumpTexture);
  34174. }
  34175. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34176. var depth = 1.0;
  34177. if (this._refractionTexture.isCube) {
  34178. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34179. }
  34180. else {
  34181. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34182. }
  34183. }
  34184. }
  34185. // Clip plane
  34186. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34187. // Colors
  34188. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34189. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34190. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34191. }
  34192. if (mustRebind || !this.isFrozen) {
  34193. // Lights
  34194. if (scene.lightsEnabled && !this._disableLighting) {
  34195. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34196. }
  34197. // View
  34198. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34199. this.bindView(effect);
  34200. }
  34201. // Fog
  34202. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34203. // Morph targets
  34204. if (defines.NUM_MORPH_INFLUENCERS) {
  34205. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34206. }
  34207. // Log. depth
  34208. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34209. // image processing
  34210. this._imageProcessingConfiguration.bind(this._activeEffect);
  34211. }
  34212. this._uniformBuffer.update();
  34213. this._afterBind(mesh, this._activeEffect);
  34214. };
  34215. StandardMaterial.prototype.getAnimatables = function () {
  34216. var results = [];
  34217. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34218. results.push(this._diffuseTexture);
  34219. }
  34220. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34221. results.push(this._ambientTexture);
  34222. }
  34223. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34224. results.push(this._opacityTexture);
  34225. }
  34226. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34227. results.push(this._reflectionTexture);
  34228. }
  34229. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34230. results.push(this._emissiveTexture);
  34231. }
  34232. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34233. results.push(this._specularTexture);
  34234. }
  34235. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34236. results.push(this._bumpTexture);
  34237. }
  34238. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34239. results.push(this._lightmapTexture);
  34240. }
  34241. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34242. results.push(this._refractionTexture);
  34243. }
  34244. return results;
  34245. };
  34246. StandardMaterial.prototype.getActiveTextures = function () {
  34247. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34248. if (this._diffuseTexture) {
  34249. activeTextures.push(this._diffuseTexture);
  34250. }
  34251. if (this._ambientTexture) {
  34252. activeTextures.push(this._ambientTexture);
  34253. }
  34254. if (this._opacityTexture) {
  34255. activeTextures.push(this._opacityTexture);
  34256. }
  34257. if (this._reflectionTexture) {
  34258. activeTextures.push(this._reflectionTexture);
  34259. }
  34260. if (this._emissiveTexture) {
  34261. activeTextures.push(this._emissiveTexture);
  34262. }
  34263. if (this._specularTexture) {
  34264. activeTextures.push(this._specularTexture);
  34265. }
  34266. if (this._bumpTexture) {
  34267. activeTextures.push(this._bumpTexture);
  34268. }
  34269. if (this._lightmapTexture) {
  34270. activeTextures.push(this._lightmapTexture);
  34271. }
  34272. if (this._refractionTexture) {
  34273. activeTextures.push(this._refractionTexture);
  34274. }
  34275. return activeTextures;
  34276. };
  34277. StandardMaterial.prototype.hasTexture = function (texture) {
  34278. if (_super.prototype.hasTexture.call(this, texture)) {
  34279. return true;
  34280. }
  34281. if (this._diffuseTexture === texture) {
  34282. return true;
  34283. }
  34284. if (this._ambientTexture === texture) {
  34285. return true;
  34286. }
  34287. if (this._opacityTexture === texture) {
  34288. return true;
  34289. }
  34290. if (this._reflectionTexture === texture) {
  34291. return true;
  34292. }
  34293. if (this._emissiveTexture === texture) {
  34294. return true;
  34295. }
  34296. if (this._specularTexture === texture) {
  34297. return true;
  34298. }
  34299. if (this._bumpTexture === texture) {
  34300. return true;
  34301. }
  34302. if (this._lightmapTexture === texture) {
  34303. return true;
  34304. }
  34305. if (this._refractionTexture === texture) {
  34306. return true;
  34307. }
  34308. return false;
  34309. };
  34310. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34311. if (forceDisposeTextures) {
  34312. if (this._diffuseTexture) {
  34313. this._diffuseTexture.dispose();
  34314. }
  34315. if (this._ambientTexture) {
  34316. this._ambientTexture.dispose();
  34317. }
  34318. if (this._opacityTexture) {
  34319. this._opacityTexture.dispose();
  34320. }
  34321. if (this._reflectionTexture) {
  34322. this._reflectionTexture.dispose();
  34323. }
  34324. if (this._emissiveTexture) {
  34325. this._emissiveTexture.dispose();
  34326. }
  34327. if (this._specularTexture) {
  34328. this._specularTexture.dispose();
  34329. }
  34330. if (this._bumpTexture) {
  34331. this._bumpTexture.dispose();
  34332. }
  34333. if (this._lightmapTexture) {
  34334. this._lightmapTexture.dispose();
  34335. }
  34336. if (this._refractionTexture) {
  34337. this._refractionTexture.dispose();
  34338. }
  34339. }
  34340. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34341. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34342. }
  34343. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34344. };
  34345. StandardMaterial.prototype.clone = function (name) {
  34346. var _this = this;
  34347. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34348. result.name = name;
  34349. result.id = name;
  34350. return result;
  34351. };
  34352. StandardMaterial.prototype.serialize = function () {
  34353. return BABYLON.SerializationHelper.Serialize(this);
  34354. };
  34355. // Statics
  34356. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34357. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34358. };
  34359. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34360. get: function () {
  34361. return StandardMaterial._DiffuseTextureEnabled;
  34362. },
  34363. set: function (value) {
  34364. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34365. return;
  34366. }
  34367. StandardMaterial._DiffuseTextureEnabled = value;
  34368. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34369. },
  34370. enumerable: true,
  34371. configurable: true
  34372. });
  34373. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34374. get: function () {
  34375. return StandardMaterial._AmbientTextureEnabled;
  34376. },
  34377. set: function (value) {
  34378. if (StandardMaterial._AmbientTextureEnabled === value) {
  34379. return;
  34380. }
  34381. StandardMaterial._AmbientTextureEnabled = value;
  34382. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34383. },
  34384. enumerable: true,
  34385. configurable: true
  34386. });
  34387. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34388. get: function () {
  34389. return StandardMaterial._OpacityTextureEnabled;
  34390. },
  34391. set: function (value) {
  34392. if (StandardMaterial._OpacityTextureEnabled === value) {
  34393. return;
  34394. }
  34395. StandardMaterial._OpacityTextureEnabled = value;
  34396. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34397. },
  34398. enumerable: true,
  34399. configurable: true
  34400. });
  34401. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34402. get: function () {
  34403. return StandardMaterial._ReflectionTextureEnabled;
  34404. },
  34405. set: function (value) {
  34406. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34407. return;
  34408. }
  34409. StandardMaterial._ReflectionTextureEnabled = value;
  34410. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34411. },
  34412. enumerable: true,
  34413. configurable: true
  34414. });
  34415. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34416. get: function () {
  34417. return StandardMaterial._EmissiveTextureEnabled;
  34418. },
  34419. set: function (value) {
  34420. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34421. return;
  34422. }
  34423. StandardMaterial._EmissiveTextureEnabled = value;
  34424. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34425. },
  34426. enumerable: true,
  34427. configurable: true
  34428. });
  34429. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34430. get: function () {
  34431. return StandardMaterial._SpecularTextureEnabled;
  34432. },
  34433. set: function (value) {
  34434. if (StandardMaterial._SpecularTextureEnabled === value) {
  34435. return;
  34436. }
  34437. StandardMaterial._SpecularTextureEnabled = value;
  34438. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34439. },
  34440. enumerable: true,
  34441. configurable: true
  34442. });
  34443. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34444. get: function () {
  34445. return StandardMaterial._BumpTextureEnabled;
  34446. },
  34447. set: function (value) {
  34448. if (StandardMaterial._BumpTextureEnabled === value) {
  34449. return;
  34450. }
  34451. StandardMaterial._BumpTextureEnabled = value;
  34452. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34453. },
  34454. enumerable: true,
  34455. configurable: true
  34456. });
  34457. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34458. get: function () {
  34459. return StandardMaterial._LightmapTextureEnabled;
  34460. },
  34461. set: function (value) {
  34462. if (StandardMaterial._LightmapTextureEnabled === value) {
  34463. return;
  34464. }
  34465. StandardMaterial._LightmapTextureEnabled = value;
  34466. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34467. },
  34468. enumerable: true,
  34469. configurable: true
  34470. });
  34471. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34472. get: function () {
  34473. return StandardMaterial._RefractionTextureEnabled;
  34474. },
  34475. set: function (value) {
  34476. if (StandardMaterial._RefractionTextureEnabled === value) {
  34477. return;
  34478. }
  34479. StandardMaterial._RefractionTextureEnabled = value;
  34480. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34481. },
  34482. enumerable: true,
  34483. configurable: true
  34484. });
  34485. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34486. get: function () {
  34487. return StandardMaterial._ColorGradingTextureEnabled;
  34488. },
  34489. set: function (value) {
  34490. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34491. return;
  34492. }
  34493. StandardMaterial._ColorGradingTextureEnabled = value;
  34494. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34495. },
  34496. enumerable: true,
  34497. configurable: true
  34498. });
  34499. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34500. get: function () {
  34501. return StandardMaterial._FresnelEnabled;
  34502. },
  34503. set: function (value) {
  34504. if (StandardMaterial._FresnelEnabled === value) {
  34505. return;
  34506. }
  34507. StandardMaterial._FresnelEnabled = value;
  34508. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34509. },
  34510. enumerable: true,
  34511. configurable: true
  34512. });
  34513. // Flags used to enable or disable a type of texture for all Standard Materials
  34514. StandardMaterial._DiffuseTextureEnabled = true;
  34515. StandardMaterial._AmbientTextureEnabled = true;
  34516. StandardMaterial._OpacityTextureEnabled = true;
  34517. StandardMaterial._ReflectionTextureEnabled = true;
  34518. StandardMaterial._EmissiveTextureEnabled = true;
  34519. StandardMaterial._SpecularTextureEnabled = true;
  34520. StandardMaterial._BumpTextureEnabled = true;
  34521. StandardMaterial._LightmapTextureEnabled = true;
  34522. StandardMaterial._RefractionTextureEnabled = true;
  34523. StandardMaterial._ColorGradingTextureEnabled = true;
  34524. StandardMaterial._FresnelEnabled = true;
  34525. __decorate([
  34526. BABYLON.serializeAsTexture("diffuseTexture")
  34527. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34528. __decorate([
  34529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34530. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34531. __decorate([
  34532. BABYLON.serializeAsTexture("ambientTexture")
  34533. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34534. __decorate([
  34535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34536. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34537. __decorate([
  34538. BABYLON.serializeAsTexture("opacityTexture")
  34539. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34540. __decorate([
  34541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34542. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34543. __decorate([
  34544. BABYLON.serializeAsTexture("reflectionTexture")
  34545. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34546. __decorate([
  34547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34548. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34549. __decorate([
  34550. BABYLON.serializeAsTexture("emissiveTexture")
  34551. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34552. __decorate([
  34553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34554. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34555. __decorate([
  34556. BABYLON.serializeAsTexture("specularTexture")
  34557. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34558. __decorate([
  34559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34560. ], StandardMaterial.prototype, "specularTexture", void 0);
  34561. __decorate([
  34562. BABYLON.serializeAsTexture("bumpTexture")
  34563. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34564. __decorate([
  34565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34566. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34567. __decorate([
  34568. BABYLON.serializeAsTexture("lightmapTexture")
  34569. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34570. __decorate([
  34571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34572. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34573. __decorate([
  34574. BABYLON.serializeAsTexture("refractionTexture")
  34575. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34576. __decorate([
  34577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34578. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34579. __decorate([
  34580. BABYLON.serializeAsColor3("ambient")
  34581. ], StandardMaterial.prototype, "ambientColor", void 0);
  34582. __decorate([
  34583. BABYLON.serializeAsColor3("diffuse")
  34584. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34585. __decorate([
  34586. BABYLON.serializeAsColor3("specular")
  34587. ], StandardMaterial.prototype, "specularColor", void 0);
  34588. __decorate([
  34589. BABYLON.serializeAsColor3("emissive")
  34590. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34591. __decorate([
  34592. BABYLON.serialize()
  34593. ], StandardMaterial.prototype, "specularPower", void 0);
  34594. __decorate([
  34595. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34596. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34597. __decorate([
  34598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34599. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34600. __decorate([
  34601. BABYLON.serialize("useEmissiveAsIllumination")
  34602. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34603. __decorate([
  34604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34605. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34606. __decorate([
  34607. BABYLON.serialize("linkEmissiveWithDiffuse")
  34608. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34609. __decorate([
  34610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34611. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34612. __decorate([
  34613. BABYLON.serialize("useSpecularOverAlpha")
  34614. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34615. __decorate([
  34616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34617. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34618. __decorate([
  34619. BABYLON.serialize("useReflectionOverAlpha")
  34620. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34621. __decorate([
  34622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34623. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34624. __decorate([
  34625. BABYLON.serialize("disableLighting")
  34626. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34627. __decorate([
  34628. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34629. ], StandardMaterial.prototype, "disableLighting", void 0);
  34630. __decorate([
  34631. BABYLON.serialize("useParallax")
  34632. ], StandardMaterial.prototype, "_useParallax", void 0);
  34633. __decorate([
  34634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34635. ], StandardMaterial.prototype, "useParallax", void 0);
  34636. __decorate([
  34637. BABYLON.serialize("useParallaxOcclusion")
  34638. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34639. __decorate([
  34640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34641. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34642. __decorate([
  34643. BABYLON.serialize()
  34644. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34645. __decorate([
  34646. BABYLON.serialize("roughness")
  34647. ], StandardMaterial.prototype, "_roughness", void 0);
  34648. __decorate([
  34649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34650. ], StandardMaterial.prototype, "roughness", void 0);
  34651. __decorate([
  34652. BABYLON.serialize()
  34653. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34654. __decorate([
  34655. BABYLON.serialize()
  34656. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34657. __decorate([
  34658. BABYLON.serialize("useLightmapAsShadowmap")
  34659. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34660. __decorate([
  34661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34662. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34663. __decorate([
  34664. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34665. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34666. __decorate([
  34667. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34668. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34669. __decorate([
  34670. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34671. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34672. __decorate([
  34673. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34674. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34675. __decorate([
  34676. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34677. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34678. __decorate([
  34679. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34680. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34681. __decorate([
  34682. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34683. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34684. __decorate([
  34685. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34686. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34687. __decorate([
  34688. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34689. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34690. __decorate([
  34691. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34692. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34693. __decorate([
  34694. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34695. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34696. __decorate([
  34697. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34698. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34699. __decorate([
  34700. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34701. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34702. __decorate([
  34703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34704. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34705. __decorate([
  34706. BABYLON.serialize("maxSimultaneousLights")
  34707. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34708. __decorate([
  34709. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34710. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34711. __decorate([
  34712. BABYLON.serialize("invertNormalMapX")
  34713. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34714. __decorate([
  34715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34716. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34717. __decorate([
  34718. BABYLON.serialize("invertNormalMapY")
  34719. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34720. __decorate([
  34721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34722. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34723. __decorate([
  34724. BABYLON.serialize("twoSidedLighting")
  34725. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34726. __decorate([
  34727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34728. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34729. __decorate([
  34730. BABYLON.serialize()
  34731. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34732. return StandardMaterial;
  34733. }(BABYLON.PushMaterial));
  34734. BABYLON.StandardMaterial = StandardMaterial;
  34735. })(BABYLON || (BABYLON = {}));
  34736. //# sourceMappingURL=babylon.standardMaterial.js.map
  34737. var BABYLON;
  34738. (function (BABYLON) {
  34739. var PBRMaterialDefines = /** @class */ (function (_super) {
  34740. __extends(PBRMaterialDefines, _super);
  34741. function PBRMaterialDefines() {
  34742. var _this = _super.call(this) || this;
  34743. _this.PBR = true;
  34744. _this.MAINUV1 = false;
  34745. _this.MAINUV2 = false;
  34746. _this.UV1 = false;
  34747. _this.UV2 = false;
  34748. _this.ALBEDO = false;
  34749. _this.ALBEDODIRECTUV = 0;
  34750. _this.VERTEXCOLOR = false;
  34751. _this.AMBIENT = false;
  34752. _this.AMBIENTDIRECTUV = 0;
  34753. _this.AMBIENTINGRAYSCALE = false;
  34754. _this.OPACITY = false;
  34755. _this.VERTEXALPHA = false;
  34756. _this.OPACITYDIRECTUV = 0;
  34757. _this.OPACITYRGB = false;
  34758. _this.ALPHATEST = false;
  34759. _this.DEPTHPREPASS = false;
  34760. _this.ALPHABLEND = false;
  34761. _this.ALPHAFROMALBEDO = false;
  34762. _this.ALPHATESTVALUE = 0.5;
  34763. _this.SPECULAROVERALPHA = false;
  34764. _this.RADIANCEOVERALPHA = false;
  34765. _this.ALPHAFRESNEL = false;
  34766. _this.PREMULTIPLYALPHA = false;
  34767. _this.EMISSIVE = false;
  34768. _this.EMISSIVEDIRECTUV = 0;
  34769. _this.REFLECTIVITY = false;
  34770. _this.REFLECTIVITYDIRECTUV = 0;
  34771. _this.SPECULARTERM = false;
  34772. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34773. _this.MICROSURFACEAUTOMATIC = false;
  34774. _this.LODBASEDMICROSFURACE = false;
  34775. _this.MICROSURFACEMAP = false;
  34776. _this.MICROSURFACEMAPDIRECTUV = 0;
  34777. _this.METALLICWORKFLOW = false;
  34778. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34779. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34780. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34781. _this.AOSTOREINMETALMAPRED = false;
  34782. _this.ENVIRONMENTBRDF = false;
  34783. _this.NORMAL = false;
  34784. _this.TANGENT = false;
  34785. _this.BUMP = false;
  34786. _this.BUMPDIRECTUV = 0;
  34787. _this.PARALLAX = false;
  34788. _this.PARALLAXOCCLUSION = false;
  34789. _this.NORMALXYSCALE = true;
  34790. _this.LIGHTMAP = false;
  34791. _this.LIGHTMAPDIRECTUV = 0;
  34792. _this.USELIGHTMAPASSHADOWMAP = false;
  34793. _this.REFLECTION = false;
  34794. _this.REFLECTIONMAP_3D = false;
  34795. _this.REFLECTIONMAP_SPHERICAL = false;
  34796. _this.REFLECTIONMAP_PLANAR = false;
  34797. _this.REFLECTIONMAP_CUBIC = false;
  34798. _this.REFLECTIONMAP_PROJECTION = false;
  34799. _this.REFLECTIONMAP_SKYBOX = false;
  34800. _this.REFLECTIONMAP_EXPLICIT = false;
  34801. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34802. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34803. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34804. _this.INVERTCUBICMAP = false;
  34805. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34806. _this.USESPHERICALINVERTEX = false;
  34807. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34808. _this.LODINREFLECTIONALPHA = false;
  34809. _this.GAMMAREFLECTION = false;
  34810. _this.REFRACTION = false;
  34811. _this.REFRACTIONMAP_3D = false;
  34812. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34813. _this.LODINREFRACTIONALPHA = false;
  34814. _this.GAMMAREFRACTION = false;
  34815. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34816. _this.INSTANCES = false;
  34817. _this.NUM_BONE_INFLUENCERS = 0;
  34818. _this.BonesPerMesh = 0;
  34819. _this.NONUNIFORMSCALING = false;
  34820. _this.MORPHTARGETS = false;
  34821. _this.MORPHTARGETS_NORMAL = false;
  34822. _this.MORPHTARGETS_TANGENT = false;
  34823. _this.NUM_MORPH_INFLUENCERS = 0;
  34824. _this.IMAGEPROCESSING = false;
  34825. _this.VIGNETTE = false;
  34826. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34827. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34828. _this.TONEMAPPING = false;
  34829. _this.CONTRAST = false;
  34830. _this.COLORCURVES = false;
  34831. _this.COLORGRADING = false;
  34832. _this.COLORGRADING3D = false;
  34833. _this.SAMPLER3DGREENDEPTH = false;
  34834. _this.SAMPLER3DBGRMAP = false;
  34835. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34836. _this.EXPOSURE = false;
  34837. _this.USEPHYSICALLIGHTFALLOFF = false;
  34838. _this.TWOSIDEDLIGHTING = false;
  34839. _this.SHADOWFLOAT = false;
  34840. _this.CLIPPLANE = false;
  34841. _this.POINTSIZE = false;
  34842. _this.FOG = false;
  34843. _this.LOGARITHMICDEPTH = false;
  34844. _this.FORCENORMALFORWARD = false;
  34845. _this.rebuild();
  34846. return _this;
  34847. }
  34848. PBRMaterialDefines.prototype.reset = function () {
  34849. _super.prototype.reset.call(this);
  34850. this.ALPHATESTVALUE = 0.5;
  34851. this.PBR = true;
  34852. };
  34853. return PBRMaterialDefines;
  34854. }(BABYLON.MaterialDefines));
  34855. /**
  34856. * The Physically based material base class of BJS.
  34857. *
  34858. * This offers the main features of a standard PBR material.
  34859. * For more information, please refer to the documentation :
  34860. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34861. */
  34862. var PBRBaseMaterial = /** @class */ (function (_super) {
  34863. __extends(PBRBaseMaterial, _super);
  34864. /**
  34865. * Instantiates a new PBRMaterial instance.
  34866. *
  34867. * @param name The material name
  34868. * @param scene The scene the material will be use in.
  34869. */
  34870. function PBRBaseMaterial(name, scene) {
  34871. var _this = _super.call(this, name, scene) || this;
  34872. /**
  34873. * Intensity of the direct lights e.g. the four lights available in your scene.
  34874. * This impacts both the direct diffuse and specular highlights.
  34875. */
  34876. _this._directIntensity = 1.0;
  34877. /**
  34878. * Intensity of the emissive part of the material.
  34879. * This helps controlling the emissive effect without modifying the emissive color.
  34880. */
  34881. _this._emissiveIntensity = 1.0;
  34882. /**
  34883. * Intensity of the environment e.g. how much the environment will light the object
  34884. * either through harmonics for rough material or through the refelction for shiny ones.
  34885. */
  34886. _this._environmentIntensity = 1.0;
  34887. /**
  34888. * This is a special control allowing the reduction of the specular highlights coming from the
  34889. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34890. */
  34891. _this._specularIntensity = 1.0;
  34892. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34893. /**
  34894. * Debug Control allowing disabling the bump map on this material.
  34895. */
  34896. _this._disableBumpMap = false;
  34897. /**
  34898. * AKA Occlusion Texture Intensity in other nomenclature.
  34899. */
  34900. _this._ambientTextureStrength = 1.0;
  34901. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34902. /**
  34903. * AKA Diffuse Color in other nomenclature.
  34904. */
  34905. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34906. /**
  34907. * AKA Specular Color in other nomenclature.
  34908. */
  34909. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34910. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34911. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34912. /**
  34913. * AKA Glossiness in other nomenclature.
  34914. */
  34915. _this._microSurface = 0.9;
  34916. /**
  34917. * source material index of refraction (IOR)' / 'destination material IOR.
  34918. */
  34919. _this._indexOfRefraction = 0.66;
  34920. /**
  34921. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34922. */
  34923. _this._invertRefractionY = false;
  34924. /**
  34925. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34926. * Materials half opaque for instance using refraction could benefit from this control.
  34927. */
  34928. _this._linkRefractionWithTransparency = false;
  34929. _this._useLightmapAsShadowmap = false;
  34930. /**
  34931. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  34932. */
  34933. _this._useAlphaFromAlbedoTexture = false;
  34934. /**
  34935. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34936. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34937. */
  34938. _this._useSpecularOverAlpha = true;
  34939. /**
  34940. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34941. */
  34942. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34943. /**
  34944. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34945. */
  34946. _this._useRoughnessFromMetallicTextureAlpha = true;
  34947. /**
  34948. * Specifies if the metallic texture contains the roughness information in its green channel.
  34949. */
  34950. _this._useRoughnessFromMetallicTextureGreen = false;
  34951. /**
  34952. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34953. */
  34954. _this._useMetallnessFromMetallicTextureBlue = false;
  34955. /**
  34956. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34957. */
  34958. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34959. /**
  34960. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34961. */
  34962. _this._useAmbientInGrayScale = false;
  34963. /**
  34964. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34965. * The material will try to infer what glossiness each pixel should be.
  34966. */
  34967. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34968. /**
  34969. * BJS is using an harcoded light falloff based on a manually sets up range.
  34970. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34971. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34972. */
  34973. _this._usePhysicalLightFalloff = true;
  34974. /**
  34975. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34976. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34977. */
  34978. _this._useRadianceOverAlpha = true;
  34979. /**
  34980. * Allows using the bump map in parallax mode.
  34981. */
  34982. _this._useParallax = false;
  34983. /**
  34984. * Allows using the bump map in parallax occlusion mode.
  34985. */
  34986. _this._useParallaxOcclusion = false;
  34987. /**
  34988. * Controls the scale bias of the parallax mode.
  34989. */
  34990. _this._parallaxScaleBias = 0.05;
  34991. /**
  34992. * If sets to true, disables all the lights affecting the material.
  34993. */
  34994. _this._disableLighting = false;
  34995. /**
  34996. * Number of Simultaneous lights allowed on the material.
  34997. */
  34998. _this._maxSimultaneousLights = 4;
  34999. /**
  35000. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35001. */
  35002. _this._invertNormalMapX = false;
  35003. /**
  35004. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35005. */
  35006. _this._invertNormalMapY = false;
  35007. /**
  35008. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35009. */
  35010. _this._twoSidedLighting = false;
  35011. /**
  35012. * Defines the alpha limits in alpha test mode.
  35013. */
  35014. _this._alphaCutOff = 0.4;
  35015. /**
  35016. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35017. */
  35018. _this._forceAlphaTest = false;
  35019. /**
  35020. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35021. * And/Or occlude the blended part.
  35022. */
  35023. _this._useAlphaFresnel = false;
  35024. /**
  35025. * The transparency mode of the material.
  35026. */
  35027. _this._transparencyMode = null;
  35028. /**
  35029. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35030. * from cos thetav and roughness:
  35031. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35032. */
  35033. _this._environmentBRDFTexture = null;
  35034. /**
  35035. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35036. */
  35037. _this._forceIrradianceInFragment = false;
  35038. /**
  35039. * Force normal to face away from face.
  35040. * (Temporary internal fix to remove before 3.1)
  35041. */
  35042. _this._forceNormalForward = false;
  35043. _this._renderTargets = new BABYLON.SmartArray(16);
  35044. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35045. // Setup the default processing configuration to the scene.
  35046. _this._attachImageProcessingConfiguration(null);
  35047. _this.getRenderTargetTextures = function () {
  35048. _this._renderTargets.reset();
  35049. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35050. _this._renderTargets.push(_this._reflectionTexture);
  35051. }
  35052. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35053. _this._renderTargets.push(_this._refractionTexture);
  35054. }
  35055. return _this._renderTargets;
  35056. };
  35057. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35058. return _this;
  35059. }
  35060. /**
  35061. * Attaches a new image processing configuration to the PBR Material.
  35062. * @param configuration
  35063. */
  35064. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35065. var _this = this;
  35066. if (configuration === this._imageProcessingConfiguration) {
  35067. return;
  35068. }
  35069. // Detaches observer.
  35070. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35071. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35072. }
  35073. // Pick the scene configuration if needed.
  35074. if (!configuration) {
  35075. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35076. }
  35077. else {
  35078. this._imageProcessingConfiguration = configuration;
  35079. }
  35080. // Attaches observer.
  35081. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35082. _this._markAllSubMeshesAsImageProcessingDirty();
  35083. });
  35084. };
  35085. PBRBaseMaterial.prototype.getClassName = function () {
  35086. return "PBRBaseMaterial";
  35087. };
  35088. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35089. get: function () {
  35090. return this._useLogarithmicDepth;
  35091. },
  35092. set: function (value) {
  35093. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35094. },
  35095. enumerable: true,
  35096. configurable: true
  35097. });
  35098. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  35099. /**
  35100. * Gets the current transparency mode.
  35101. */
  35102. get: function () {
  35103. return this._transparencyMode;
  35104. },
  35105. /**
  35106. * Sets the transparency mode of the material.
  35107. */
  35108. set: function (value) {
  35109. if (this._transparencyMode === value) {
  35110. return;
  35111. }
  35112. this._transparencyMode = value;
  35113. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  35114. this._markAllSubMeshesAsTexturesDirty();
  35115. },
  35116. enumerable: true,
  35117. configurable: true
  35118. });
  35119. /**
  35120. * Specifies whether or not the meshes using this material should be rendered in alpha blend mode.
  35121. */
  35122. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35123. if (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35124. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST) {
  35125. return false;
  35126. }
  35127. return _super.prototype.needAlphaBlending.call(this);
  35128. };
  35129. /**
  35130. * Specifies whether or not the meshes using this material should be rendered in alpha blend mode.
  35131. */
  35132. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  35133. if (this._linkRefractionWithTransparency) {
  35134. return false;
  35135. }
  35136. if (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35137. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST) {
  35138. return false;
  35139. }
  35140. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35141. };
  35142. /**
  35143. * Specifies whether or not the meshes using this material should be rendered in alpha test mode.
  35144. */
  35145. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35146. if (this._forceAlphaTest) {
  35147. return true;
  35148. }
  35149. if (this._linkRefractionWithTransparency) {
  35150. return false;
  35151. }
  35152. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35153. };
  35154. /**
  35155. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  35156. */
  35157. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35158. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35159. };
  35160. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35161. return this._albedoTexture;
  35162. };
  35163. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35164. var _this = this;
  35165. if (subMesh.effect && this.isFrozen) {
  35166. if (this._wasPreviouslyReady) {
  35167. return true;
  35168. }
  35169. }
  35170. if (!subMesh._materialDefines) {
  35171. subMesh._materialDefines = new PBRMaterialDefines();
  35172. }
  35173. var scene = this.getScene();
  35174. var defines = subMesh._materialDefines;
  35175. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35176. if (defines._renderId === scene.getRenderId()) {
  35177. return true;
  35178. }
  35179. }
  35180. var engine = scene.getEngine();
  35181. // Lights
  35182. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35183. defines._needNormals = true;
  35184. // Textures
  35185. if (defines._areTexturesDirty) {
  35186. defines._needUVs = false;
  35187. if (scene.texturesEnabled) {
  35188. if (scene.getEngine().getCaps().textureLOD) {
  35189. defines.LODBASEDMICROSFURACE = true;
  35190. }
  35191. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35192. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35193. return false;
  35194. }
  35195. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35196. }
  35197. else {
  35198. defines.ALBEDO = false;
  35199. }
  35200. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35201. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35202. return false;
  35203. }
  35204. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35205. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35206. }
  35207. else {
  35208. defines.AMBIENT = false;
  35209. }
  35210. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35211. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35212. return false;
  35213. }
  35214. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35215. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35216. }
  35217. else {
  35218. defines.OPACITY = false;
  35219. }
  35220. var reflectionTexture = this._getReflectionTexture();
  35221. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35222. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35223. return false;
  35224. }
  35225. defines.REFLECTION = true;
  35226. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35227. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35228. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35229. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35230. defines.INVERTCUBICMAP = true;
  35231. }
  35232. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35233. switch (reflectionTexture.coordinatesMode) {
  35234. case BABYLON.Texture.CUBIC_MODE:
  35235. case BABYLON.Texture.INVCUBIC_MODE:
  35236. defines.REFLECTIONMAP_CUBIC = true;
  35237. break;
  35238. case BABYLON.Texture.EXPLICIT_MODE:
  35239. defines.REFLECTIONMAP_EXPLICIT = true;
  35240. break;
  35241. case BABYLON.Texture.PLANAR_MODE:
  35242. defines.REFLECTIONMAP_PLANAR = true;
  35243. break;
  35244. case BABYLON.Texture.PROJECTION_MODE:
  35245. defines.REFLECTIONMAP_PROJECTION = true;
  35246. break;
  35247. case BABYLON.Texture.SKYBOX_MODE:
  35248. defines.REFLECTIONMAP_SKYBOX = true;
  35249. break;
  35250. case BABYLON.Texture.SPHERICAL_MODE:
  35251. defines.REFLECTIONMAP_SPHERICAL = true;
  35252. break;
  35253. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35254. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35255. break;
  35256. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35257. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35258. break;
  35259. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35260. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35261. break;
  35262. }
  35263. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35264. if (reflectionTexture.sphericalPolynomial) {
  35265. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35266. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35267. defines.USESPHERICALINVERTEX = false;
  35268. }
  35269. else {
  35270. defines.USESPHERICALINVERTEX = true;
  35271. }
  35272. }
  35273. }
  35274. }
  35275. else {
  35276. defines.REFLECTION = false;
  35277. defines.REFLECTIONMAP_3D = false;
  35278. defines.REFLECTIONMAP_SPHERICAL = false;
  35279. defines.REFLECTIONMAP_PLANAR = false;
  35280. defines.REFLECTIONMAP_CUBIC = false;
  35281. defines.REFLECTIONMAP_PROJECTION = false;
  35282. defines.REFLECTIONMAP_SKYBOX = false;
  35283. defines.REFLECTIONMAP_EXPLICIT = false;
  35284. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35285. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35286. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35287. defines.INVERTCUBICMAP = false;
  35288. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35289. defines.USESPHERICALINVERTEX = false;
  35290. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35291. defines.LODINREFLECTIONALPHA = false;
  35292. defines.GAMMAREFLECTION = false;
  35293. }
  35294. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35295. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35296. return false;
  35297. }
  35298. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35299. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35300. }
  35301. else {
  35302. defines.LIGHTMAP = false;
  35303. }
  35304. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35305. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35306. return false;
  35307. }
  35308. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35309. }
  35310. else {
  35311. defines.EMISSIVE = false;
  35312. }
  35313. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35314. if (this._metallicTexture) {
  35315. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35316. return false;
  35317. }
  35318. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35319. defines.METALLICWORKFLOW = true;
  35320. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35321. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35322. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35323. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35324. }
  35325. else if (this._reflectivityTexture) {
  35326. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35327. return false;
  35328. }
  35329. defines.METALLICWORKFLOW = false;
  35330. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35331. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35332. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35333. }
  35334. else {
  35335. defines.METALLICWORKFLOW = false;
  35336. defines.REFLECTIVITY = false;
  35337. }
  35338. if (this._microSurfaceTexture) {
  35339. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35340. return false;
  35341. }
  35342. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35343. }
  35344. else {
  35345. defines.MICROSURFACEMAP = false;
  35346. }
  35347. }
  35348. else {
  35349. defines.REFLECTIVITY = false;
  35350. defines.MICROSURFACEMAP = false;
  35351. }
  35352. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35353. // Bump texure can not be none blocking.
  35354. if (!this._bumpTexture.isReady()) {
  35355. return false;
  35356. }
  35357. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35358. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35359. defines.PARALLAX = true;
  35360. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35361. }
  35362. else {
  35363. defines.PARALLAX = false;
  35364. }
  35365. }
  35366. else {
  35367. defines.BUMP = false;
  35368. }
  35369. var refractionTexture = this._getRefractionTexture();
  35370. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35371. if (!refractionTexture.isReadyOrNotBlocking()) {
  35372. return false;
  35373. }
  35374. defines.REFRACTION = true;
  35375. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35376. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35377. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35378. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35379. if (this._linkRefractionWithTransparency) {
  35380. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35381. }
  35382. }
  35383. else {
  35384. defines.REFRACTION = false;
  35385. }
  35386. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35387. // This is blocking.
  35388. if (!this._environmentBRDFTexture.isReady()) {
  35389. return false;
  35390. }
  35391. defines.ENVIRONMENTBRDF = true;
  35392. }
  35393. else {
  35394. defines.ENVIRONMENTBRDF = false;
  35395. }
  35396. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35397. defines.ALPHAFROMALBEDO = true;
  35398. }
  35399. else {
  35400. defines.ALPHAFROMALBEDO = false;
  35401. }
  35402. }
  35403. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35404. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35405. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35406. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35407. defines.METALLICWORKFLOW = true;
  35408. }
  35409. else {
  35410. defines.METALLICWORKFLOW = false;
  35411. }
  35412. if (!this.backFaceCulling && this._twoSidedLighting) {
  35413. defines.TWOSIDEDLIGHTING = true;
  35414. }
  35415. else {
  35416. defines.TWOSIDEDLIGHTING = false;
  35417. }
  35418. defines.ALPHATESTVALUE = this._alphaCutOff;
  35419. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35420. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  35421. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35422. }
  35423. if (defines._areImageProcessingDirty) {
  35424. if (!this._imageProcessingConfiguration.isReady()) {
  35425. return false;
  35426. }
  35427. this._imageProcessingConfiguration.prepareDefines(defines);
  35428. }
  35429. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35430. // Misc.
  35431. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35432. // Values that need to be evaluated on every frame
  35433. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35434. // Attribs
  35435. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE)) {
  35436. if (mesh) {
  35437. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35438. mesh.createNormals(true);
  35439. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35440. }
  35441. }
  35442. }
  35443. // Get correct effect
  35444. if (defines.isDirty) {
  35445. defines.markAsProcessed();
  35446. scene.resetCachedMaterial();
  35447. // Fallbacks
  35448. var fallbacks = new BABYLON.EffectFallbacks();
  35449. var fallbackRank = 0;
  35450. if (defines.USESPHERICALINVERTEX) {
  35451. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  35452. }
  35453. if (defines.FOG) {
  35454. fallbacks.addFallback(fallbackRank, "FOG");
  35455. }
  35456. if (defines.POINTSIZE) {
  35457. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  35458. }
  35459. if (defines.LOGARITHMICDEPTH) {
  35460. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  35461. }
  35462. if (defines.PARALLAX) {
  35463. fallbacks.addFallback(fallbackRank, "PARALLAX");
  35464. }
  35465. if (defines.PARALLAXOCCLUSION) {
  35466. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  35467. }
  35468. if (defines.ENVIRONMENTBRDF) {
  35469. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  35470. }
  35471. if (defines.TANGENT) {
  35472. fallbacks.addFallback(fallbackRank++, "TANGENT");
  35473. }
  35474. if (defines.BUMP) {
  35475. fallbacks.addFallback(fallbackRank++, "BUMP");
  35476. }
  35477. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  35478. if (defines.SPECULARTERM) {
  35479. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  35480. }
  35481. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35482. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  35483. }
  35484. if (defines.LIGHTMAP) {
  35485. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  35486. }
  35487. if (defines.NORMAL) {
  35488. fallbacks.addFallback(fallbackRank++, "NORMAL");
  35489. }
  35490. if (defines.AMBIENT) {
  35491. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  35492. }
  35493. if (defines.EMISSIVE) {
  35494. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  35495. }
  35496. if (defines.VERTEXCOLOR) {
  35497. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  35498. }
  35499. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35500. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  35501. }
  35502. if (defines.MORPHTARGETS) {
  35503. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  35504. }
  35505. //Attributes
  35506. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35507. if (defines.NORMAL) {
  35508. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35509. }
  35510. if (defines.TANGENT) {
  35511. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35512. }
  35513. if (defines.UV1) {
  35514. attribs.push(BABYLON.VertexBuffer.UVKind);
  35515. }
  35516. if (defines.UV2) {
  35517. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35518. }
  35519. if (defines.VERTEXCOLOR) {
  35520. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35521. }
  35522. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35523. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35524. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35525. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35526. "vFogInfos", "vFogColor", "pointSize",
  35527. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35528. "mBones",
  35529. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35530. "vLightingIntensity",
  35531. "logarithmicDepthConstant",
  35532. "vSphericalX", "vSphericalY", "vSphericalZ",
  35533. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35534. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35535. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35536. "vTangentSpaceParams"
  35537. ];
  35538. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35539. "bumpSampler", "lightmapSampler", "opacitySampler",
  35540. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35541. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35542. "microSurfaceSampler", "environmentBrdfSampler"];
  35543. var uniformBuffers = ["Material", "Scene"];
  35544. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35545. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35546. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35547. uniformsNames: uniforms,
  35548. uniformBuffersNames: uniformBuffers,
  35549. samplers: samplers,
  35550. defines: defines,
  35551. maxSimultaneousLights: this._maxSimultaneousLights
  35552. });
  35553. var onCompiled = function (effect) {
  35554. if (_this.onCompiled) {
  35555. _this.onCompiled(effect);
  35556. }
  35557. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35558. };
  35559. var join = defines.toString();
  35560. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35561. attributes: attribs,
  35562. uniformsNames: uniforms,
  35563. uniformBuffersNames: uniformBuffers,
  35564. samplers: samplers,
  35565. defines: join,
  35566. fallbacks: fallbacks,
  35567. onCompiled: onCompiled,
  35568. onError: this.onError,
  35569. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35570. }, engine), defines);
  35571. this.buildUniformLayout();
  35572. }
  35573. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35574. return false;
  35575. }
  35576. defines._renderId = scene.getRenderId();
  35577. this._wasPreviouslyReady = true;
  35578. return true;
  35579. };
  35580. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35581. // Order is important !
  35582. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35583. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35584. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35585. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35586. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35587. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35588. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35589. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35590. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35591. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35592. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35593. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35594. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35595. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35596. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35597. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35598. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35599. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35600. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35601. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35602. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35603. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35604. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35605. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35606. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35607. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35608. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35609. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35610. this._uniformBuffer.addUniform("pointSize", 1);
  35611. this._uniformBuffer.create();
  35612. };
  35613. PBRBaseMaterial.prototype.unbind = function () {
  35614. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35615. this._uniformBuffer.setTexture("reflectionSampler", null);
  35616. }
  35617. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35618. this._uniformBuffer.setTexture("refractionSampler", null);
  35619. }
  35620. _super.prototype.unbind.call(this);
  35621. };
  35622. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35623. this._activeEffect.setMatrix("world", world);
  35624. };
  35625. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35626. var scene = this.getScene();
  35627. var defines = subMesh._materialDefines;
  35628. if (!defines) {
  35629. return;
  35630. }
  35631. var effect = subMesh.effect;
  35632. if (!effect) {
  35633. return;
  35634. }
  35635. this._activeEffect = effect;
  35636. // Matrices
  35637. this.bindOnlyWorldMatrix(world);
  35638. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35639. // Bones
  35640. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35641. var reflectionTexture = null;
  35642. if (mustRebind) {
  35643. this._uniformBuffer.bindToEffect(effect, "Material");
  35644. this.bindViewProjection(effect);
  35645. reflectionTexture = this._getReflectionTexture();
  35646. var refractionTexture = this._getRefractionTexture();
  35647. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35648. // Texture uniforms
  35649. if (scene.texturesEnabled) {
  35650. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35651. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35652. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35653. }
  35654. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35655. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35656. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35657. }
  35658. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35659. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35660. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35661. }
  35662. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35663. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35664. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35665. var polynomials = reflectionTexture.sphericalPolynomial;
  35666. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35667. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35668. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35669. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35670. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35671. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35672. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35673. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35674. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35675. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35676. }
  35677. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35678. }
  35679. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35680. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35681. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35682. }
  35683. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35684. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35685. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35686. }
  35687. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35688. if (this._metallicTexture) {
  35689. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35690. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35691. }
  35692. else if (this._reflectivityTexture) {
  35693. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35694. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35695. }
  35696. if (this._microSurfaceTexture) {
  35697. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35698. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35699. }
  35700. }
  35701. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35702. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35703. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35704. if (scene._mirroredCameraPosition) {
  35705. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35706. }
  35707. else {
  35708. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35709. }
  35710. }
  35711. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35712. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35713. var depth = 1.0;
  35714. if (!refractionTexture.isCube) {
  35715. if (refractionTexture.depth) {
  35716. depth = refractionTexture.depth;
  35717. }
  35718. }
  35719. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35720. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35721. }
  35722. }
  35723. // Point size
  35724. if (this.pointsCloud) {
  35725. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35726. }
  35727. // Colors
  35728. if (defines.METALLICWORKFLOW) {
  35729. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35730. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35731. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35732. }
  35733. else {
  35734. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35735. }
  35736. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35737. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35738. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35739. // Misc
  35740. this._lightingInfos.x = this._directIntensity;
  35741. this._lightingInfos.y = this._emissiveIntensity;
  35742. this._lightingInfos.z = this._environmentIntensity;
  35743. this._lightingInfos.w = this._specularIntensity;
  35744. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35745. }
  35746. // Textures
  35747. if (scene.texturesEnabled) {
  35748. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35749. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35750. }
  35751. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35752. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35753. }
  35754. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35755. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35756. }
  35757. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35758. if (defines.LODBASEDMICROSFURACE) {
  35759. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35760. }
  35761. else {
  35762. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35763. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35764. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35765. }
  35766. }
  35767. if (defines.ENVIRONMENTBRDF) {
  35768. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35769. }
  35770. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35771. if (defines.LODBASEDMICROSFURACE) {
  35772. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35773. }
  35774. else {
  35775. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35776. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35777. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35778. }
  35779. }
  35780. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35781. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35782. }
  35783. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35784. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35785. }
  35786. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35787. if (this._metallicTexture) {
  35788. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35789. }
  35790. else if (this._reflectivityTexture) {
  35791. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35792. }
  35793. if (this._microSurfaceTexture) {
  35794. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35795. }
  35796. }
  35797. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35798. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35799. }
  35800. }
  35801. // Clip plane
  35802. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35803. // Colors
  35804. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35805. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35806. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35807. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35808. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35809. }
  35810. if (mustRebind || !this.isFrozen) {
  35811. // Lights
  35812. if (scene.lightsEnabled && !this._disableLighting) {
  35813. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35814. }
  35815. // View
  35816. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35817. this.bindView(effect);
  35818. }
  35819. // Fog
  35820. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35821. // Morph targets
  35822. if (defines.NUM_MORPH_INFLUENCERS) {
  35823. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35824. }
  35825. // image processing
  35826. this._imageProcessingConfiguration.bind(this._activeEffect);
  35827. // Log. depth
  35828. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35829. }
  35830. this._uniformBuffer.update();
  35831. this._afterBind(mesh);
  35832. };
  35833. PBRBaseMaterial.prototype.getAnimatables = function () {
  35834. var results = [];
  35835. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35836. results.push(this._albedoTexture);
  35837. }
  35838. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35839. results.push(this._ambientTexture);
  35840. }
  35841. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35842. results.push(this._opacityTexture);
  35843. }
  35844. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35845. results.push(this._reflectionTexture);
  35846. }
  35847. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35848. results.push(this._emissiveTexture);
  35849. }
  35850. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35851. results.push(this._metallicTexture);
  35852. }
  35853. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35854. results.push(this._reflectivityTexture);
  35855. }
  35856. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35857. results.push(this._bumpTexture);
  35858. }
  35859. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35860. results.push(this._lightmapTexture);
  35861. }
  35862. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35863. results.push(this._refractionTexture);
  35864. }
  35865. return results;
  35866. };
  35867. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35868. if (this._reflectionTexture) {
  35869. return this._reflectionTexture;
  35870. }
  35871. return this.getScene().environmentTexture;
  35872. };
  35873. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35874. if (this._refractionTexture) {
  35875. return this._refractionTexture;
  35876. }
  35877. if (this._linkRefractionWithTransparency) {
  35878. return this.getScene().environmentTexture;
  35879. }
  35880. return null;
  35881. };
  35882. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35883. if (forceDisposeTextures) {
  35884. if (this._albedoTexture) {
  35885. this._albedoTexture.dispose();
  35886. }
  35887. if (this._ambientTexture) {
  35888. this._ambientTexture.dispose();
  35889. }
  35890. if (this._opacityTexture) {
  35891. this._opacityTexture.dispose();
  35892. }
  35893. if (this._reflectionTexture) {
  35894. this._reflectionTexture.dispose();
  35895. }
  35896. if (this._environmentBRDFTexture) {
  35897. this._environmentBRDFTexture.dispose();
  35898. }
  35899. if (this._emissiveTexture) {
  35900. this._emissiveTexture.dispose();
  35901. }
  35902. if (this._metallicTexture) {
  35903. this._metallicTexture.dispose();
  35904. }
  35905. if (this._reflectivityTexture) {
  35906. this._reflectivityTexture.dispose();
  35907. }
  35908. if (this._bumpTexture) {
  35909. this._bumpTexture.dispose();
  35910. }
  35911. if (this._lightmapTexture) {
  35912. this._lightmapTexture.dispose();
  35913. }
  35914. if (this._refractionTexture) {
  35915. this._refractionTexture.dispose();
  35916. }
  35917. }
  35918. this._renderTargets.dispose();
  35919. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35920. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35921. }
  35922. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35923. };
  35924. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35925. __decorate([
  35926. BABYLON.serializeAsImageProcessingConfiguration()
  35927. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35928. __decorate([
  35929. BABYLON.serialize()
  35930. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35931. __decorate([
  35932. BABYLON.serialize()
  35933. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  35934. return PBRBaseMaterial;
  35935. }(BABYLON.PushMaterial));
  35936. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35937. })(BABYLON || (BABYLON = {}));
  35938. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35939. var BABYLON;
  35940. (function (BABYLON) {
  35941. var Internals;
  35942. (function (Internals) {
  35943. /**
  35944. * The Physically based simple base material of BJS.
  35945. *
  35946. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35947. * It is used as the base class for both the specGloss and metalRough conventions.
  35948. */
  35949. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35950. __extends(PBRBaseSimpleMaterial, _super);
  35951. /**
  35952. * Instantiates a new PBRMaterial instance.
  35953. *
  35954. * @param name The material name
  35955. * @param scene The scene the material will be use in.
  35956. */
  35957. function PBRBaseSimpleMaterial(name, scene) {
  35958. var _this = _super.call(this, name, scene) || this;
  35959. /**
  35960. * Number of Simultaneous lights allowed on the material.
  35961. */
  35962. _this.maxSimultaneousLights = 4;
  35963. /**
  35964. * If sets to true, disables all the lights affecting the material.
  35965. */
  35966. _this.disableLighting = false;
  35967. /**
  35968. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35969. */
  35970. _this.invertNormalMapX = false;
  35971. /**
  35972. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35973. */
  35974. _this.invertNormalMapY = false;
  35975. /**
  35976. * Emissivie color used to self-illuminate the model.
  35977. */
  35978. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35979. /**
  35980. * Occlusion Channel Strenght.
  35981. */
  35982. _this.occlusionStrength = 1.0;
  35983. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35984. _this._useAlphaFromAlbedoTexture = true;
  35985. _this._useAmbientInGrayScale = true;
  35986. return _this;
  35987. }
  35988. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35989. /**
  35990. * Gets the current double sided mode.
  35991. */
  35992. get: function () {
  35993. return this._twoSidedLighting;
  35994. },
  35995. /**
  35996. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35997. */
  35998. set: function (value) {
  35999. if (this._twoSidedLighting === value) {
  36000. return;
  36001. }
  36002. this._twoSidedLighting = value;
  36003. this.backFaceCulling = !value;
  36004. this._markAllSubMeshesAsTexturesDirty();
  36005. },
  36006. enumerable: true,
  36007. configurable: true
  36008. });
  36009. /**
  36010. * Return the active textures of the material.
  36011. */
  36012. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  36013. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36014. if (this.environmentTexture) {
  36015. activeTextures.push(this.environmentTexture);
  36016. }
  36017. if (this.normalTexture) {
  36018. activeTextures.push(this.normalTexture);
  36019. }
  36020. if (this.emissiveTexture) {
  36021. activeTextures.push(this.emissiveTexture);
  36022. }
  36023. if (this.occlusionTexture) {
  36024. activeTextures.push(this.occlusionTexture);
  36025. }
  36026. return activeTextures;
  36027. };
  36028. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  36029. return "PBRBaseSimpleMaterial";
  36030. };
  36031. __decorate([
  36032. BABYLON.serialize(),
  36033. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36034. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36035. __decorate([
  36036. BABYLON.serialize(),
  36037. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36038. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36039. __decorate([
  36040. BABYLON.serializeAsTexture(),
  36041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36042. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36043. __decorate([
  36044. BABYLON.serialize(),
  36045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36046. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36047. __decorate([
  36048. BABYLON.serialize(),
  36049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36050. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36051. __decorate([
  36052. BABYLON.serializeAsTexture(),
  36053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36054. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36055. __decorate([
  36056. BABYLON.serializeAsColor3("emissive"),
  36057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36058. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36059. __decorate([
  36060. BABYLON.serializeAsTexture(),
  36061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36062. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36063. __decorate([
  36064. BABYLON.serialize(),
  36065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36066. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36067. __decorate([
  36068. BABYLON.serializeAsTexture(),
  36069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36070. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36071. __decorate([
  36072. BABYLON.serialize(),
  36073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36074. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36075. __decorate([
  36076. BABYLON.serialize()
  36077. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36078. return PBRBaseSimpleMaterial;
  36079. }(BABYLON.PBRBaseMaterial));
  36080. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36081. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36082. })(BABYLON || (BABYLON = {}));
  36083. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36084. var BABYLON;
  36085. (function (BABYLON) {
  36086. /**
  36087. * The Physically based material of BJS.
  36088. *
  36089. * This offers the main features of a standard PBR material.
  36090. * For more information, please refer to the documentation :
  36091. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36092. */
  36093. var PBRMaterial = /** @class */ (function (_super) {
  36094. __extends(PBRMaterial, _super);
  36095. /**
  36096. * Instantiates a new PBRMaterial instance.
  36097. *
  36098. * @param name The material name
  36099. * @param scene The scene the material will be use in.
  36100. */
  36101. function PBRMaterial(name, scene) {
  36102. var _this = _super.call(this, name, scene) || this;
  36103. /**
  36104. * Intensity of the direct lights e.g. the four lights available in your scene.
  36105. * This impacts both the direct diffuse and specular highlights.
  36106. */
  36107. _this.directIntensity = 1.0;
  36108. /**
  36109. * Intensity of the emissive part of the material.
  36110. * This helps controlling the emissive effect without modifying the emissive color.
  36111. */
  36112. _this.emissiveIntensity = 1.0;
  36113. /**
  36114. * Intensity of the environment e.g. how much the environment will light the object
  36115. * either through harmonics for rough material or through the refelction for shiny ones.
  36116. */
  36117. _this.environmentIntensity = 1.0;
  36118. /**
  36119. * This is a special control allowing the reduction of the specular highlights coming from the
  36120. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36121. */
  36122. _this.specularIntensity = 1.0;
  36123. /**
  36124. * Debug Control allowing disabling the bump map on this material.
  36125. */
  36126. _this.disableBumpMap = false;
  36127. /**
  36128. * AKA Occlusion Texture Intensity in other nomenclature.
  36129. */
  36130. _this.ambientTextureStrength = 1.0;
  36131. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36132. /**
  36133. * AKA Diffuse Color in other nomenclature.
  36134. */
  36135. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36136. /**
  36137. * AKA Specular Color in other nomenclature.
  36138. */
  36139. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36140. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36141. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36142. /**
  36143. * AKA Glossiness in other nomenclature.
  36144. */
  36145. _this.microSurface = 1.0;
  36146. /**
  36147. * source material index of refraction (IOR)' / 'destination material IOR.
  36148. */
  36149. _this.indexOfRefraction = 0.66;
  36150. /**
  36151. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36152. */
  36153. _this.invertRefractionY = false;
  36154. /**
  36155. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36156. * Materials half opaque for instance using refraction could benefit from this control.
  36157. */
  36158. _this.linkRefractionWithTransparency = false;
  36159. _this.useLightmapAsShadowmap = false;
  36160. /**
  36161. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36162. */
  36163. _this.useAlphaFromAlbedoTexture = false;
  36164. /**
  36165. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36166. */
  36167. _this.forceAlphaTest = false;
  36168. /**
  36169. * Defines the alpha limits in alpha test mode.
  36170. */
  36171. _this.alphaCutOff = 0.4;
  36172. /**
  36173. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36174. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36175. */
  36176. _this.useSpecularOverAlpha = true;
  36177. /**
  36178. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36179. */
  36180. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36181. /**
  36182. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36183. */
  36184. _this.useRoughnessFromMetallicTextureAlpha = true;
  36185. /**
  36186. * Specifies if the metallic texture contains the roughness information in its green channel.
  36187. */
  36188. _this.useRoughnessFromMetallicTextureGreen = false;
  36189. /**
  36190. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36191. */
  36192. _this.useMetallnessFromMetallicTextureBlue = false;
  36193. /**
  36194. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36195. */
  36196. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36197. /**
  36198. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36199. */
  36200. _this.useAmbientInGrayScale = false;
  36201. /**
  36202. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36203. * The material will try to infer what glossiness each pixel should be.
  36204. */
  36205. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36206. /**
  36207. * BJS is using an harcoded light falloff based on a manually sets up range.
  36208. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36209. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36210. */
  36211. _this.usePhysicalLightFalloff = true;
  36212. /**
  36213. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36214. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36215. */
  36216. _this.useRadianceOverAlpha = true;
  36217. /**
  36218. * Allows using the bump map in parallax mode.
  36219. */
  36220. _this.useParallax = false;
  36221. /**
  36222. * Allows using the bump map in parallax occlusion mode.
  36223. */
  36224. _this.useParallaxOcclusion = false;
  36225. /**
  36226. * Controls the scale bias of the parallax mode.
  36227. */
  36228. _this.parallaxScaleBias = 0.05;
  36229. /**
  36230. * If sets to true, disables all the lights affecting the material.
  36231. */
  36232. _this.disableLighting = false;
  36233. /**
  36234. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36235. */
  36236. _this.forceIrradianceInFragment = false;
  36237. /**
  36238. * Number of Simultaneous lights allowed on the material.
  36239. */
  36240. _this.maxSimultaneousLights = 4;
  36241. /**
  36242. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36243. */
  36244. _this.invertNormalMapX = false;
  36245. /**
  36246. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36247. */
  36248. _this.invertNormalMapY = false;
  36249. /**
  36250. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36251. */
  36252. _this.twoSidedLighting = false;
  36253. /**
  36254. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36255. * And/Or occlude the blended part.
  36256. */
  36257. _this.useAlphaFresnel = false;
  36258. /**
  36259. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36260. * And/Or occlude the blended part.
  36261. */
  36262. _this.environmentBRDFTexture = null;
  36263. /**
  36264. * Force normal to face away from face.
  36265. * (Temporary internal fix to remove before 3.1)
  36266. */
  36267. _this.forceNormalForward = false;
  36268. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36269. return _this;
  36270. }
  36271. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36272. /**
  36273. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36274. */
  36275. get: function () {
  36276. return this._PBRMATERIAL_OPAQUE;
  36277. },
  36278. enumerable: true,
  36279. configurable: true
  36280. });
  36281. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36282. /**
  36283. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36284. */
  36285. get: function () {
  36286. return this._PBRMATERIAL_ALPHATEST;
  36287. },
  36288. enumerable: true,
  36289. configurable: true
  36290. });
  36291. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36292. /**
  36293. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36294. */
  36295. get: function () {
  36296. return this._PBRMATERIAL_ALPHABLEND;
  36297. },
  36298. enumerable: true,
  36299. configurable: true
  36300. });
  36301. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36302. /**
  36303. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36304. * They are also discarded below the alpha cutoff threshold to improve performances.
  36305. */
  36306. get: function () {
  36307. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36308. },
  36309. enumerable: true,
  36310. configurable: true
  36311. });
  36312. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36313. /**
  36314. * Gets the image processing configuration used either in this material.
  36315. */
  36316. get: function () {
  36317. return this._imageProcessingConfiguration;
  36318. },
  36319. /**
  36320. * Sets the Default image processing configuration used either in the this material.
  36321. *
  36322. * If sets to null, the scene one is in use.
  36323. */
  36324. set: function (value) {
  36325. this._attachImageProcessingConfiguration(value);
  36326. // Ensure the effect will be rebuilt.
  36327. this._markAllSubMeshesAsTexturesDirty();
  36328. },
  36329. enumerable: true,
  36330. configurable: true
  36331. });
  36332. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36333. /**
  36334. * Gets wether the color curves effect is enabled.
  36335. */
  36336. get: function () {
  36337. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36338. },
  36339. /**
  36340. * Sets wether the color curves effect is enabled.
  36341. */
  36342. set: function (value) {
  36343. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36344. },
  36345. enumerable: true,
  36346. configurable: true
  36347. });
  36348. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36349. /**
  36350. * Gets wether the color grading effect is enabled.
  36351. */
  36352. get: function () {
  36353. return this.imageProcessingConfiguration.colorGradingEnabled;
  36354. },
  36355. /**
  36356. * Gets wether the color grading effect is enabled.
  36357. */
  36358. set: function (value) {
  36359. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36360. },
  36361. enumerable: true,
  36362. configurable: true
  36363. });
  36364. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36365. /**
  36366. * Gets wether tonemapping is enabled or not.
  36367. */
  36368. get: function () {
  36369. return this._imageProcessingConfiguration.toneMappingEnabled;
  36370. },
  36371. /**
  36372. * Sets wether tonemapping is enabled or not
  36373. */
  36374. set: function (value) {
  36375. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36376. },
  36377. enumerable: true,
  36378. configurable: true
  36379. });
  36380. ;
  36381. ;
  36382. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36383. /**
  36384. * The camera exposure used on this material.
  36385. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36386. * This corresponds to a photographic exposure.
  36387. */
  36388. get: function () {
  36389. return this._imageProcessingConfiguration.exposure;
  36390. },
  36391. /**
  36392. * The camera exposure used on this material.
  36393. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36394. * This corresponds to a photographic exposure.
  36395. */
  36396. set: function (value) {
  36397. this._imageProcessingConfiguration.exposure = value;
  36398. },
  36399. enumerable: true,
  36400. configurable: true
  36401. });
  36402. ;
  36403. ;
  36404. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36405. /**
  36406. * Gets The camera contrast used on this material.
  36407. */
  36408. get: function () {
  36409. return this._imageProcessingConfiguration.contrast;
  36410. },
  36411. /**
  36412. * Sets The camera contrast used on this material.
  36413. */
  36414. set: function (value) {
  36415. this._imageProcessingConfiguration.contrast = value;
  36416. },
  36417. enumerable: true,
  36418. configurable: true
  36419. });
  36420. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36421. /**
  36422. * Gets the Color Grading 2D Lookup Texture.
  36423. */
  36424. get: function () {
  36425. return this._imageProcessingConfiguration.colorGradingTexture;
  36426. },
  36427. /**
  36428. * Sets the Color Grading 2D Lookup Texture.
  36429. */
  36430. set: function (value) {
  36431. this._imageProcessingConfiguration.colorGradingTexture = value;
  36432. },
  36433. enumerable: true,
  36434. configurable: true
  36435. });
  36436. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36437. /**
  36438. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36439. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36440. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  36441. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36442. */
  36443. get: function () {
  36444. return this._imageProcessingConfiguration.colorCurves;
  36445. },
  36446. /**
  36447. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36448. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36449. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  36450. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36451. */
  36452. set: function (value) {
  36453. this._imageProcessingConfiguration.colorCurves = value;
  36454. },
  36455. enumerable: true,
  36456. configurable: true
  36457. });
  36458. PBRMaterial.prototype.getClassName = function () {
  36459. return "PBRMaterial";
  36460. };
  36461. PBRMaterial.prototype.getActiveTextures = function () {
  36462. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36463. if (this._albedoTexture) {
  36464. activeTextures.push(this._albedoTexture);
  36465. }
  36466. if (this._ambientTexture) {
  36467. activeTextures.push(this._ambientTexture);
  36468. }
  36469. if (this._opacityTexture) {
  36470. activeTextures.push(this._opacityTexture);
  36471. }
  36472. if (this._reflectionTexture) {
  36473. activeTextures.push(this._reflectionTexture);
  36474. }
  36475. if (this._emissiveTexture) {
  36476. activeTextures.push(this._emissiveTexture);
  36477. }
  36478. if (this._reflectivityTexture) {
  36479. activeTextures.push(this._reflectivityTexture);
  36480. }
  36481. if (this._metallicTexture) {
  36482. activeTextures.push(this._metallicTexture);
  36483. }
  36484. if (this._microSurfaceTexture) {
  36485. activeTextures.push(this._microSurfaceTexture);
  36486. }
  36487. if (this._bumpTexture) {
  36488. activeTextures.push(this._bumpTexture);
  36489. }
  36490. if (this._lightmapTexture) {
  36491. activeTextures.push(this._lightmapTexture);
  36492. }
  36493. if (this._refractionTexture) {
  36494. activeTextures.push(this._refractionTexture);
  36495. }
  36496. return activeTextures;
  36497. };
  36498. PBRMaterial.prototype.hasTexture = function (texture) {
  36499. if (_super.prototype.hasTexture.call(this, texture)) {
  36500. return true;
  36501. }
  36502. if (this._albedoTexture === texture) {
  36503. return true;
  36504. }
  36505. if (this._ambientTexture === texture) {
  36506. return true;
  36507. }
  36508. if (this._opacityTexture === texture) {
  36509. return true;
  36510. }
  36511. if (this._reflectionTexture === texture) {
  36512. return true;
  36513. }
  36514. if (this._reflectivityTexture === texture) {
  36515. return true;
  36516. }
  36517. if (this._metallicTexture === texture) {
  36518. return true;
  36519. }
  36520. if (this._microSurfaceTexture === texture) {
  36521. return true;
  36522. }
  36523. if (this._bumpTexture === texture) {
  36524. return true;
  36525. }
  36526. if (this._lightmapTexture === texture) {
  36527. return true;
  36528. }
  36529. if (this._refractionTexture === texture) {
  36530. return true;
  36531. }
  36532. return false;
  36533. };
  36534. PBRMaterial.prototype.clone = function (name) {
  36535. var _this = this;
  36536. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36537. clone.id = name;
  36538. clone.name = name;
  36539. return clone;
  36540. };
  36541. PBRMaterial.prototype.serialize = function () {
  36542. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36543. serializationObject.customType = "BABYLON.PBRMaterial";
  36544. return serializationObject;
  36545. };
  36546. // Statics
  36547. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36548. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36549. };
  36550. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36551. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36552. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36553. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36554. __decorate([
  36555. BABYLON.serialize(),
  36556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36557. ], PBRMaterial.prototype, "directIntensity", void 0);
  36558. __decorate([
  36559. BABYLON.serialize(),
  36560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36561. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36562. __decorate([
  36563. BABYLON.serialize(),
  36564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36565. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36566. __decorate([
  36567. BABYLON.serialize(),
  36568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36569. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36570. __decorate([
  36571. BABYLON.serialize(),
  36572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36573. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36574. __decorate([
  36575. BABYLON.serializeAsTexture(),
  36576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36577. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36578. __decorate([
  36579. BABYLON.serializeAsTexture(),
  36580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36581. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36582. __decorate([
  36583. BABYLON.serialize(),
  36584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36585. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36586. __decorate([
  36587. BABYLON.serializeAsTexture(),
  36588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36589. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36590. __decorate([
  36591. BABYLON.serializeAsTexture(),
  36592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36593. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36594. __decorate([
  36595. BABYLON.serializeAsTexture(),
  36596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36597. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36598. __decorate([
  36599. BABYLON.serializeAsTexture(),
  36600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36601. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36602. __decorate([
  36603. BABYLON.serializeAsTexture(),
  36604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36605. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36606. __decorate([
  36607. BABYLON.serialize(),
  36608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36609. ], PBRMaterial.prototype, "metallic", void 0);
  36610. __decorate([
  36611. BABYLON.serialize(),
  36612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36613. ], PBRMaterial.prototype, "roughness", void 0);
  36614. __decorate([
  36615. BABYLON.serializeAsTexture(),
  36616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36617. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36618. __decorate([
  36619. BABYLON.serializeAsTexture(),
  36620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36621. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36622. __decorate([
  36623. BABYLON.serializeAsTexture(),
  36624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36625. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36626. __decorate([
  36627. BABYLON.serializeAsTexture(),
  36628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36629. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36630. __decorate([
  36631. BABYLON.serializeAsColor3("ambient"),
  36632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36633. ], PBRMaterial.prototype, "ambientColor", void 0);
  36634. __decorate([
  36635. BABYLON.serializeAsColor3("albedo"),
  36636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36637. ], PBRMaterial.prototype, "albedoColor", void 0);
  36638. __decorate([
  36639. BABYLON.serializeAsColor3("reflectivity"),
  36640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36641. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36642. __decorate([
  36643. BABYLON.serializeAsColor3("reflection"),
  36644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36645. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36646. __decorate([
  36647. BABYLON.serializeAsColor3("emissive"),
  36648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36649. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36650. __decorate([
  36651. BABYLON.serialize(),
  36652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36653. ], PBRMaterial.prototype, "microSurface", void 0);
  36654. __decorate([
  36655. BABYLON.serialize(),
  36656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36657. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36658. __decorate([
  36659. BABYLON.serialize(),
  36660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36661. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36662. __decorate([
  36663. BABYLON.serialize(),
  36664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36665. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36666. __decorate([
  36667. BABYLON.serialize(),
  36668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36669. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36670. __decorate([
  36671. BABYLON.serialize(),
  36672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36673. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36674. __decorate([
  36675. BABYLON.serialize(),
  36676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36677. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36678. __decorate([
  36679. BABYLON.serialize(),
  36680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36681. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36682. __decorate([
  36683. BABYLON.serialize(),
  36684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36685. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36686. __decorate([
  36687. BABYLON.serialize(),
  36688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36689. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36690. __decorate([
  36691. BABYLON.serialize(),
  36692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36693. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36694. __decorate([
  36695. BABYLON.serialize(),
  36696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36697. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36698. __decorate([
  36699. BABYLON.serialize(),
  36700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36701. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36702. __decorate([
  36703. BABYLON.serialize(),
  36704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36705. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36706. __decorate([
  36707. BABYLON.serialize(),
  36708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36709. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36710. __decorate([
  36711. BABYLON.serialize(),
  36712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36713. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36714. __decorate([
  36715. BABYLON.serialize(),
  36716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36717. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36718. __decorate([
  36719. BABYLON.serialize(),
  36720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36721. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36722. __decorate([
  36723. BABYLON.serialize(),
  36724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36725. ], PBRMaterial.prototype, "useParallax", void 0);
  36726. __decorate([
  36727. BABYLON.serialize(),
  36728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36729. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36730. __decorate([
  36731. BABYLON.serialize(),
  36732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36733. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36734. __decorate([
  36735. BABYLON.serialize(),
  36736. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36737. ], PBRMaterial.prototype, "disableLighting", void 0);
  36738. __decorate([
  36739. BABYLON.serialize(),
  36740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36741. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36742. __decorate([
  36743. BABYLON.serialize(),
  36744. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36745. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36746. __decorate([
  36747. BABYLON.serialize(),
  36748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36749. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36750. __decorate([
  36751. BABYLON.serialize(),
  36752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36753. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36754. __decorate([
  36755. BABYLON.serialize(),
  36756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36757. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36758. __decorate([
  36759. BABYLON.serialize(),
  36760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36761. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36762. __decorate([
  36763. BABYLON.serializeAsTexture(),
  36764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36765. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36766. __decorate([
  36767. BABYLON.serialize(),
  36768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36769. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36770. return PBRMaterial;
  36771. }(BABYLON.PBRBaseMaterial));
  36772. BABYLON.PBRMaterial = PBRMaterial;
  36773. })(BABYLON || (BABYLON = {}));
  36774. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36775. var BABYLON;
  36776. (function (BABYLON) {
  36777. /**
  36778. * The PBR material of BJS following the metal roughness convention.
  36779. *
  36780. * This fits to the PBR convention in the GLTF definition:
  36781. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36782. */
  36783. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36784. __extends(PBRMetallicRoughnessMaterial, _super);
  36785. /**
  36786. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36787. *
  36788. * @param name The material name
  36789. * @param scene The scene the material will be use in.
  36790. */
  36791. function PBRMetallicRoughnessMaterial(name, scene) {
  36792. var _this = _super.call(this, name, scene) || this;
  36793. _this._useRoughnessFromMetallicTextureAlpha = false;
  36794. _this._useRoughnessFromMetallicTextureGreen = true;
  36795. _this._useMetallnessFromMetallicTextureBlue = true;
  36796. return _this;
  36797. }
  36798. /**
  36799. * Return the currrent class name of the material.
  36800. */
  36801. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36802. return "PBRMetallicRoughnessMaterial";
  36803. };
  36804. /**
  36805. * Return the active textures of the material.
  36806. */
  36807. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36808. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36809. if (this.baseTexture) {
  36810. activeTextures.push(this.baseTexture);
  36811. }
  36812. if (this.metallicRoughnessTexture) {
  36813. activeTextures.push(this.metallicRoughnessTexture);
  36814. }
  36815. return activeTextures;
  36816. };
  36817. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36818. if (_super.prototype.hasTexture.call(this, texture)) {
  36819. return true;
  36820. }
  36821. if (this.baseTexture === texture) {
  36822. return true;
  36823. }
  36824. if (this.metallicRoughnessTexture === texture) {
  36825. return true;
  36826. }
  36827. return false;
  36828. };
  36829. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36830. var _this = this;
  36831. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36832. clone.id = name;
  36833. clone.name = name;
  36834. return clone;
  36835. };
  36836. /**
  36837. * Serialize the material to a parsable JSON object.
  36838. */
  36839. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36840. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36841. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36842. return serializationObject;
  36843. };
  36844. /**
  36845. * Parses a JSON object correponding to the serialize function.
  36846. */
  36847. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36848. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36849. };
  36850. __decorate([
  36851. BABYLON.serializeAsColor3(),
  36852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36853. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36854. __decorate([
  36855. BABYLON.serializeAsTexture(),
  36856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36857. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36858. __decorate([
  36859. BABYLON.serialize(),
  36860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36861. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36862. __decorate([
  36863. BABYLON.serialize(),
  36864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36865. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36866. __decorate([
  36867. BABYLON.serializeAsTexture(),
  36868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36869. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36870. return PBRMetallicRoughnessMaterial;
  36871. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36872. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36873. })(BABYLON || (BABYLON = {}));
  36874. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36875. var BABYLON;
  36876. (function (BABYLON) {
  36877. /**
  36878. * The PBR material of BJS following the specular glossiness convention.
  36879. *
  36880. * This fits to the PBR convention in the GLTF definition:
  36881. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36882. */
  36883. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36884. __extends(PBRSpecularGlossinessMaterial, _super);
  36885. /**
  36886. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36887. *
  36888. * @param name The material name
  36889. * @param scene The scene the material will be use in.
  36890. */
  36891. function PBRSpecularGlossinessMaterial(name, scene) {
  36892. var _this = _super.call(this, name, scene) || this;
  36893. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36894. return _this;
  36895. }
  36896. /**
  36897. * Return the currrent class name of the material.
  36898. */
  36899. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36900. return "PBRSpecularGlossinessMaterial";
  36901. };
  36902. /**
  36903. * Return the active textures of the material.
  36904. */
  36905. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36906. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36907. if (this.diffuseTexture) {
  36908. activeTextures.push(this.diffuseTexture);
  36909. }
  36910. if (this.specularGlossinessTexture) {
  36911. activeTextures.push(this.specularGlossinessTexture);
  36912. }
  36913. return activeTextures;
  36914. };
  36915. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36916. if (_super.prototype.hasTexture.call(this, texture)) {
  36917. return true;
  36918. }
  36919. if (this.diffuseTexture === texture) {
  36920. return true;
  36921. }
  36922. if (this.specularGlossinessTexture === texture) {
  36923. return true;
  36924. }
  36925. return false;
  36926. };
  36927. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36928. var _this = this;
  36929. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36930. clone.id = name;
  36931. clone.name = name;
  36932. return clone;
  36933. };
  36934. /**
  36935. * Serialize the material to a parsable JSON object.
  36936. */
  36937. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36938. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36939. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36940. return serializationObject;
  36941. };
  36942. /**
  36943. * Parses a JSON object correponding to the serialize function.
  36944. */
  36945. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36946. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36947. };
  36948. __decorate([
  36949. BABYLON.serializeAsColor3("diffuse"),
  36950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36951. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36952. __decorate([
  36953. BABYLON.serializeAsTexture(),
  36954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36955. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36956. __decorate([
  36957. BABYLON.serializeAsColor3("specular"),
  36958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36959. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36960. __decorate([
  36961. BABYLON.serialize(),
  36962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36963. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36964. __decorate([
  36965. BABYLON.serializeAsTexture(),
  36966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36967. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36968. return PBRSpecularGlossinessMaterial;
  36969. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36970. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36971. })(BABYLON || (BABYLON = {}));
  36972. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36973. var BABYLON;
  36974. (function (BABYLON) {
  36975. BABYLON.CameraInputTypes = {};
  36976. var CameraInputsManager = /** @class */ (function () {
  36977. function CameraInputsManager(camera) {
  36978. this.attached = {};
  36979. this.camera = camera;
  36980. this.checkInputs = function () { };
  36981. }
  36982. CameraInputsManager.prototype.add = function (input) {
  36983. var type = input.getSimpleName();
  36984. if (this.attached[type]) {
  36985. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36986. return;
  36987. }
  36988. this.attached[type] = input;
  36989. input.camera = this.camera;
  36990. //for checkInputs, we are dynamically creating a function
  36991. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36992. if (input.checkInputs) {
  36993. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36994. }
  36995. if (this.attachedElement) {
  36996. input.attachControl(this.attachedElement);
  36997. }
  36998. };
  36999. CameraInputsManager.prototype.remove = function (inputToRemove) {
  37000. for (var cam in this.attached) {
  37001. var input = this.attached[cam];
  37002. if (input === inputToRemove) {
  37003. input.detachControl(this.attachedElement);
  37004. input.camera = null;
  37005. delete this.attached[cam];
  37006. this.rebuildInputCheck();
  37007. }
  37008. }
  37009. };
  37010. CameraInputsManager.prototype.removeByType = function (inputType) {
  37011. for (var cam in this.attached) {
  37012. var input = this.attached[cam];
  37013. if (input.getClassName() === inputType) {
  37014. input.detachControl(this.attachedElement);
  37015. input.camera = null;
  37016. delete this.attached[cam];
  37017. this.rebuildInputCheck();
  37018. }
  37019. }
  37020. };
  37021. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  37022. var current = this.checkInputs;
  37023. return function () {
  37024. current();
  37025. fn();
  37026. };
  37027. };
  37028. CameraInputsManager.prototype.attachInput = function (input) {
  37029. if (this.attachedElement) {
  37030. input.attachControl(this.attachedElement, this.noPreventDefault);
  37031. }
  37032. };
  37033. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37034. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37035. if (this.attachedElement) {
  37036. return;
  37037. }
  37038. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37039. this.attachedElement = element;
  37040. this.noPreventDefault = noPreventDefault;
  37041. for (var cam in this.attached) {
  37042. this.attached[cam].attachControl(element, noPreventDefault);
  37043. }
  37044. };
  37045. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37046. if (disconnect === void 0) { disconnect = false; }
  37047. if (this.attachedElement !== element) {
  37048. return;
  37049. }
  37050. for (var cam in this.attached) {
  37051. this.attached[cam].detachControl(element);
  37052. if (disconnect) {
  37053. this.attached[cam].camera = null;
  37054. }
  37055. }
  37056. this.attachedElement = null;
  37057. };
  37058. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37059. this.checkInputs = function () { };
  37060. for (var cam in this.attached) {
  37061. var input = this.attached[cam];
  37062. if (input.checkInputs) {
  37063. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37064. }
  37065. }
  37066. };
  37067. CameraInputsManager.prototype.clear = function () {
  37068. if (this.attachedElement) {
  37069. this.detachElement(this.attachedElement, true);
  37070. }
  37071. this.attached = {};
  37072. this.attachedElement = null;
  37073. this.checkInputs = function () { };
  37074. };
  37075. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37076. var inputs = {};
  37077. for (var cam in this.attached) {
  37078. var input = this.attached[cam];
  37079. var res = BABYLON.SerializationHelper.Serialize(input);
  37080. inputs[input.getClassName()] = res;
  37081. }
  37082. serializedCamera.inputsmgr = inputs;
  37083. };
  37084. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37085. var parsedInputs = parsedCamera.inputsmgr;
  37086. if (parsedInputs) {
  37087. this.clear();
  37088. for (var n in parsedInputs) {
  37089. var construct = BABYLON.CameraInputTypes[n];
  37090. if (construct) {
  37091. var parsedinput = parsedInputs[n];
  37092. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37093. this.add(input);
  37094. }
  37095. }
  37096. }
  37097. else {
  37098. //2016-03-08 this part is for managing backward compatibility
  37099. for (var n in this.attached) {
  37100. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37101. if (construct) {
  37102. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37103. this.remove(this.attached[n]);
  37104. this.add(input);
  37105. }
  37106. }
  37107. }
  37108. };
  37109. return CameraInputsManager;
  37110. }());
  37111. BABYLON.CameraInputsManager = CameraInputsManager;
  37112. })(BABYLON || (BABYLON = {}));
  37113. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37114. var BABYLON;
  37115. (function (BABYLON) {
  37116. var FreeCameraMouseInput = /** @class */ (function () {
  37117. function FreeCameraMouseInput(touchEnabled) {
  37118. if (touchEnabled === void 0) { touchEnabled = true; }
  37119. this.touchEnabled = touchEnabled;
  37120. this.buttons = [0, 1, 2];
  37121. this.angularSensibility = 2000.0;
  37122. this.previousPosition = null;
  37123. }
  37124. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37125. var _this = this;
  37126. var engine = this.camera.getEngine();
  37127. if (!this._pointerInput) {
  37128. this._pointerInput = function (p, s) {
  37129. var evt = p.event;
  37130. if (engine.isInVRExclusivePointerMode) {
  37131. return;
  37132. }
  37133. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37134. return;
  37135. }
  37136. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37137. return;
  37138. }
  37139. var srcElement = (evt.srcElement || evt.target);
  37140. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37141. try {
  37142. srcElement.setPointerCapture(evt.pointerId);
  37143. }
  37144. catch (e) {
  37145. //Nothing to do with the error. Execution will continue.
  37146. }
  37147. _this.previousPosition = {
  37148. x: evt.clientX,
  37149. y: evt.clientY
  37150. };
  37151. if (!noPreventDefault) {
  37152. evt.preventDefault();
  37153. element.focus();
  37154. }
  37155. }
  37156. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37157. try {
  37158. srcElement.releasePointerCapture(evt.pointerId);
  37159. }
  37160. catch (e) {
  37161. //Nothing to do with the error.
  37162. }
  37163. _this.previousPosition = null;
  37164. if (!noPreventDefault) {
  37165. evt.preventDefault();
  37166. }
  37167. }
  37168. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37169. if (!_this.previousPosition || engine.isPointerLock) {
  37170. return;
  37171. }
  37172. var offsetX = evt.clientX - _this.previousPosition.x;
  37173. var offsetY = evt.clientY - _this.previousPosition.y;
  37174. if (_this.camera.getScene().useRightHandedSystem) {
  37175. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37176. }
  37177. else {
  37178. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37179. }
  37180. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37181. _this.previousPosition = {
  37182. x: evt.clientX,
  37183. y: evt.clientY
  37184. };
  37185. if (!noPreventDefault) {
  37186. evt.preventDefault();
  37187. }
  37188. }
  37189. };
  37190. }
  37191. this._onMouseMove = function (evt) {
  37192. if (!engine.isPointerLock) {
  37193. return;
  37194. }
  37195. if (engine.isInVRExclusivePointerMode) {
  37196. return;
  37197. }
  37198. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37199. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37200. if (_this.camera.getScene().useRightHandedSystem) {
  37201. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37202. }
  37203. else {
  37204. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37205. }
  37206. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37207. _this.previousPosition = null;
  37208. if (!noPreventDefault) {
  37209. evt.preventDefault();
  37210. }
  37211. };
  37212. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37213. element.addEventListener("mousemove", this._onMouseMove, false);
  37214. };
  37215. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37216. if (this._observer && element) {
  37217. this.camera.getScene().onPointerObservable.remove(this._observer);
  37218. if (this._onMouseMove) {
  37219. element.removeEventListener("mousemove", this._onMouseMove);
  37220. }
  37221. this._observer = null;
  37222. this._onMouseMove = null;
  37223. this.previousPosition = null;
  37224. }
  37225. };
  37226. FreeCameraMouseInput.prototype.getClassName = function () {
  37227. return "FreeCameraMouseInput";
  37228. };
  37229. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37230. return "mouse";
  37231. };
  37232. __decorate([
  37233. BABYLON.serialize()
  37234. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37235. __decorate([
  37236. BABYLON.serialize()
  37237. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37238. return FreeCameraMouseInput;
  37239. }());
  37240. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37241. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37242. })(BABYLON || (BABYLON = {}));
  37243. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37244. var BABYLON;
  37245. (function (BABYLON) {
  37246. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37247. function FreeCameraKeyboardMoveInput() {
  37248. this._keys = new Array();
  37249. this.keysUp = [38];
  37250. this.keysDown = [40];
  37251. this.keysLeft = [37];
  37252. this.keysRight = [39];
  37253. }
  37254. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37255. var _this = this;
  37256. if (this._onCanvasBlurObserver) {
  37257. return;
  37258. }
  37259. this._scene = this.camera.getScene();
  37260. this._engine = this._scene.getEngine();
  37261. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37262. _this._keys = [];
  37263. });
  37264. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37265. var evt = info.event;
  37266. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37267. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37268. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37269. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37270. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37271. var index = _this._keys.indexOf(evt.keyCode);
  37272. if (index === -1) {
  37273. _this._keys.push(evt.keyCode);
  37274. }
  37275. if (!noPreventDefault) {
  37276. evt.preventDefault();
  37277. }
  37278. }
  37279. }
  37280. else {
  37281. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37282. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37283. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37284. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37285. var index = _this._keys.indexOf(evt.keyCode);
  37286. if (index >= 0) {
  37287. _this._keys.splice(index, 1);
  37288. }
  37289. if (!noPreventDefault) {
  37290. evt.preventDefault();
  37291. }
  37292. }
  37293. }
  37294. });
  37295. };
  37296. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37297. if (this._scene) {
  37298. if (this._onKeyboardObserver) {
  37299. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37300. }
  37301. if (this._onCanvasBlurObserver) {
  37302. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37303. }
  37304. this._onKeyboardObserver = null;
  37305. this._onCanvasBlurObserver = null;
  37306. }
  37307. this._keys = [];
  37308. };
  37309. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37310. if (this._onKeyboardObserver) {
  37311. var camera = this.camera;
  37312. // Keyboard
  37313. for (var index = 0; index < this._keys.length; index++) {
  37314. var keyCode = this._keys[index];
  37315. var speed = camera._computeLocalCameraSpeed();
  37316. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37317. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37318. }
  37319. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37320. camera._localDirection.copyFromFloats(0, 0, speed);
  37321. }
  37322. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37323. camera._localDirection.copyFromFloats(speed, 0, 0);
  37324. }
  37325. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37326. camera._localDirection.copyFromFloats(0, 0, -speed);
  37327. }
  37328. if (camera.getScene().useRightHandedSystem) {
  37329. camera._localDirection.z *= -1;
  37330. }
  37331. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37332. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37333. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37334. }
  37335. }
  37336. };
  37337. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37338. return "FreeCameraKeyboardMoveInput";
  37339. };
  37340. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37341. this._keys = [];
  37342. };
  37343. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37344. return "keyboard";
  37345. };
  37346. __decorate([
  37347. BABYLON.serialize()
  37348. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37349. __decorate([
  37350. BABYLON.serialize()
  37351. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37352. __decorate([
  37353. BABYLON.serialize()
  37354. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37355. __decorate([
  37356. BABYLON.serialize()
  37357. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37358. return FreeCameraKeyboardMoveInput;
  37359. }());
  37360. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37361. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37362. })(BABYLON || (BABYLON = {}));
  37363. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37364. var BABYLON;
  37365. (function (BABYLON) {
  37366. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37367. __extends(FreeCameraInputsManager, _super);
  37368. function FreeCameraInputsManager(camera) {
  37369. return _super.call(this, camera) || this;
  37370. }
  37371. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37372. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37373. return this;
  37374. };
  37375. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37376. if (touchEnabled === void 0) { touchEnabled = true; }
  37377. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37378. return this;
  37379. };
  37380. FreeCameraInputsManager.prototype.addGamepad = function () {
  37381. this.add(new BABYLON.FreeCameraGamepadInput());
  37382. return this;
  37383. };
  37384. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37385. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37386. return this;
  37387. };
  37388. FreeCameraInputsManager.prototype.addTouch = function () {
  37389. this.add(new BABYLON.FreeCameraTouchInput());
  37390. return this;
  37391. };
  37392. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37393. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37394. return this;
  37395. };
  37396. return FreeCameraInputsManager;
  37397. }(BABYLON.CameraInputsManager));
  37398. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37399. })(BABYLON || (BABYLON = {}));
  37400. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37401. var BABYLON;
  37402. (function (BABYLON) {
  37403. var TargetCamera = /** @class */ (function (_super) {
  37404. __extends(TargetCamera, _super);
  37405. function TargetCamera(name, position, scene) {
  37406. var _this = _super.call(this, name, position, scene) || this;
  37407. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37408. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37409. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37410. _this.speed = 2.0;
  37411. _this.noRotationConstraint = false;
  37412. _this.lockedTarget = null;
  37413. _this._currentTarget = BABYLON.Vector3.Zero();
  37414. _this._viewMatrix = BABYLON.Matrix.Zero();
  37415. _this._camMatrix = BABYLON.Matrix.Zero();
  37416. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37417. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37418. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37419. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37420. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37421. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37422. _this._tempMatrix = BABYLON.Matrix.Zero();
  37423. return _this;
  37424. }
  37425. TargetCamera.prototype.getFrontPosition = function (distance) {
  37426. var direction = this.getTarget().subtract(this.position);
  37427. direction.normalize();
  37428. direction.scaleInPlace(distance);
  37429. return this.globalPosition.add(direction);
  37430. };
  37431. TargetCamera.prototype._getLockedTargetPosition = function () {
  37432. if (!this.lockedTarget) {
  37433. return null;
  37434. }
  37435. if (this.lockedTarget.absolutePosition) {
  37436. this.lockedTarget.computeWorldMatrix();
  37437. }
  37438. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37439. };
  37440. TargetCamera.prototype.storeState = function () {
  37441. this._storedPosition = this.position.clone();
  37442. this._storedRotation = this.rotation.clone();
  37443. if (this.rotationQuaternion) {
  37444. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37445. }
  37446. return _super.prototype.storeState.call(this);
  37447. };
  37448. /**
  37449. * Restored camera state. You must call storeState() first
  37450. */
  37451. TargetCamera.prototype._restoreStateValues = function () {
  37452. if (!_super.prototype._restoreStateValues.call(this)) {
  37453. return false;
  37454. }
  37455. this.position = this._storedPosition.clone();
  37456. this.rotation = this._storedRotation.clone();
  37457. if (this.rotationQuaternion) {
  37458. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37459. }
  37460. this.cameraDirection.copyFromFloats(0, 0, 0);
  37461. this.cameraRotation.copyFromFloats(0, 0);
  37462. return true;
  37463. };
  37464. // Cache
  37465. TargetCamera.prototype._initCache = function () {
  37466. _super.prototype._initCache.call(this);
  37467. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37468. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37469. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37470. };
  37471. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37472. if (!ignoreParentClass) {
  37473. _super.prototype._updateCache.call(this);
  37474. }
  37475. var lockedTargetPosition = this._getLockedTargetPosition();
  37476. if (!lockedTargetPosition) {
  37477. this._cache.lockedTarget = null;
  37478. }
  37479. else {
  37480. if (!this._cache.lockedTarget) {
  37481. this._cache.lockedTarget = lockedTargetPosition.clone();
  37482. }
  37483. else {
  37484. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37485. }
  37486. }
  37487. this._cache.rotation.copyFrom(this.rotation);
  37488. if (this.rotationQuaternion)
  37489. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37490. };
  37491. // Synchronized
  37492. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37493. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37494. return false;
  37495. }
  37496. var lockedTargetPosition = this._getLockedTargetPosition();
  37497. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37498. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37499. };
  37500. // Methods
  37501. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37502. var engine = this.getEngine();
  37503. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37504. };
  37505. // Target
  37506. TargetCamera.prototype.setTarget = function (target) {
  37507. this.upVector.normalize();
  37508. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37509. this._camMatrix.invert();
  37510. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37511. var vDir = target.subtract(this.position);
  37512. if (vDir.x >= 0.0) {
  37513. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37514. }
  37515. else {
  37516. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37517. }
  37518. this.rotation.z = 0;
  37519. if (isNaN(this.rotation.x)) {
  37520. this.rotation.x = 0;
  37521. }
  37522. if (isNaN(this.rotation.y)) {
  37523. this.rotation.y = 0;
  37524. }
  37525. if (isNaN(this.rotation.z)) {
  37526. this.rotation.z = 0;
  37527. }
  37528. if (this.rotationQuaternion) {
  37529. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37530. }
  37531. };
  37532. /**
  37533. * Return the current target position of the camera. This value is expressed in local space.
  37534. */
  37535. TargetCamera.prototype.getTarget = function () {
  37536. return this._currentTarget;
  37537. };
  37538. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37539. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37540. };
  37541. TargetCamera.prototype._updatePosition = function () {
  37542. if (this.parent) {
  37543. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37544. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37545. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37546. return;
  37547. }
  37548. this.position.addInPlace(this.cameraDirection);
  37549. };
  37550. TargetCamera.prototype._checkInputs = function () {
  37551. var needToMove = this._decideIfNeedsToMove();
  37552. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37553. // Move
  37554. if (needToMove) {
  37555. this._updatePosition();
  37556. }
  37557. // Rotate
  37558. if (needToRotate) {
  37559. this.rotation.x += this.cameraRotation.x;
  37560. this.rotation.y += this.cameraRotation.y;
  37561. //rotate, if quaternion is set and rotation was used
  37562. if (this.rotationQuaternion) {
  37563. var len = this.rotation.lengthSquared();
  37564. if (len) {
  37565. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37566. }
  37567. }
  37568. if (!this.noRotationConstraint) {
  37569. var limit = (Math.PI / 2) * 0.95;
  37570. if (this.rotation.x > limit)
  37571. this.rotation.x = limit;
  37572. if (this.rotation.x < -limit)
  37573. this.rotation.x = -limit;
  37574. }
  37575. }
  37576. // Inertia
  37577. if (needToMove) {
  37578. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37579. this.cameraDirection.x = 0;
  37580. }
  37581. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37582. this.cameraDirection.y = 0;
  37583. }
  37584. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37585. this.cameraDirection.z = 0;
  37586. }
  37587. this.cameraDirection.scaleInPlace(this.inertia);
  37588. }
  37589. if (needToRotate) {
  37590. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37591. this.cameraRotation.x = 0;
  37592. }
  37593. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37594. this.cameraRotation.y = 0;
  37595. }
  37596. this.cameraRotation.scaleInPlace(this.inertia);
  37597. }
  37598. _super.prototype._checkInputs.call(this);
  37599. };
  37600. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37601. if (this.rotationQuaternion) {
  37602. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37603. }
  37604. else {
  37605. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37606. }
  37607. //update the up vector!
  37608. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37609. };
  37610. TargetCamera.prototype._getViewMatrix = function () {
  37611. if (!this.lockedTarget) {
  37612. // Compute
  37613. this._updateCameraRotationMatrix();
  37614. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37615. // Computing target and final matrix
  37616. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37617. }
  37618. else {
  37619. var targetPosition = this._getLockedTargetPosition();
  37620. if (targetPosition) {
  37621. this._currentTarget.copyFrom(targetPosition);
  37622. }
  37623. }
  37624. if (this.getScene().useRightHandedSystem) {
  37625. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37626. }
  37627. else {
  37628. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37629. }
  37630. return this._viewMatrix;
  37631. };
  37632. /**
  37633. * @override
  37634. * Override Camera.createRigCamera
  37635. */
  37636. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37637. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37638. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37639. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37640. if (!this.rotationQuaternion) {
  37641. this.rotationQuaternion = new BABYLON.Quaternion();
  37642. }
  37643. rigCamera._cameraRigParams = {};
  37644. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37645. }
  37646. return rigCamera;
  37647. }
  37648. return null;
  37649. };
  37650. /**
  37651. * @override
  37652. * Override Camera._updateRigCameras
  37653. */
  37654. TargetCamera.prototype._updateRigCameras = function () {
  37655. var camLeft = this._rigCameras[0];
  37656. var camRight = this._rigCameras[1];
  37657. switch (this.cameraRigMode) {
  37658. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37659. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37661. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37662. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37663. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37664. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37665. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37666. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37667. camLeft.setTarget(this.getTarget());
  37668. camRight.setTarget(this.getTarget());
  37669. break;
  37670. case BABYLON.Camera.RIG_MODE_VR:
  37671. if (camLeft.rotationQuaternion) {
  37672. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37673. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37674. }
  37675. else {
  37676. camLeft.rotation.copyFrom(this.rotation);
  37677. camRight.rotation.copyFrom(this.rotation);
  37678. }
  37679. camLeft.position.copyFrom(this.position);
  37680. camRight.position.copyFrom(this.position);
  37681. break;
  37682. }
  37683. _super.prototype._updateRigCameras.call(this);
  37684. };
  37685. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37686. if (!this._rigCamTransformMatrix) {
  37687. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37688. }
  37689. var target = this.getTarget();
  37690. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37691. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37692. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37693. };
  37694. TargetCamera.prototype.getClassName = function () {
  37695. return "TargetCamera";
  37696. };
  37697. __decorate([
  37698. BABYLON.serializeAsVector3()
  37699. ], TargetCamera.prototype, "rotation", void 0);
  37700. __decorate([
  37701. BABYLON.serialize()
  37702. ], TargetCamera.prototype, "speed", void 0);
  37703. __decorate([
  37704. BABYLON.serializeAsMeshReference("lockedTargetId")
  37705. ], TargetCamera.prototype, "lockedTarget", void 0);
  37706. return TargetCamera;
  37707. }(BABYLON.Camera));
  37708. BABYLON.TargetCamera = TargetCamera;
  37709. })(BABYLON || (BABYLON = {}));
  37710. //# sourceMappingURL=babylon.targetCamera.js.map
  37711. var BABYLON;
  37712. (function (BABYLON) {
  37713. var FreeCamera = /** @class */ (function (_super) {
  37714. __extends(FreeCamera, _super);
  37715. function FreeCamera(name, position, scene) {
  37716. var _this = _super.call(this, name, position, scene) || this;
  37717. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37718. _this.checkCollisions = false;
  37719. _this.applyGravity = false;
  37720. _this._needMoveForGravity = false;
  37721. _this._oldPosition = BABYLON.Vector3.Zero();
  37722. _this._diffPosition = BABYLON.Vector3.Zero();
  37723. _this._newPosition = BABYLON.Vector3.Zero();
  37724. // Collisions
  37725. _this._collisionMask = -1;
  37726. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37727. if (collidedMesh === void 0) { collidedMesh = null; }
  37728. //TODO move this to the collision coordinator!
  37729. if (_this.getScene().workerCollisions)
  37730. newPosition.multiplyInPlace(_this._collider.radius);
  37731. var updatePosition = function (newPos) {
  37732. _this._newPosition.copyFrom(newPos);
  37733. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37734. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37735. _this.position.addInPlace(_this._diffPosition);
  37736. if (_this.onCollide && collidedMesh) {
  37737. _this.onCollide(collidedMesh);
  37738. }
  37739. }
  37740. };
  37741. updatePosition(newPosition);
  37742. };
  37743. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37744. _this.inputs.addKeyboard().addMouse();
  37745. return _this;
  37746. }
  37747. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37748. //-- begin properties for backward compatibility for inputs
  37749. get: function () {
  37750. var mouse = this.inputs.attached["mouse"];
  37751. if (mouse)
  37752. return mouse.angularSensibility;
  37753. return 0;
  37754. },
  37755. set: function (value) {
  37756. var mouse = this.inputs.attached["mouse"];
  37757. if (mouse)
  37758. mouse.angularSensibility = value;
  37759. },
  37760. enumerable: true,
  37761. configurable: true
  37762. });
  37763. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37764. get: function () {
  37765. var keyboard = this.inputs.attached["keyboard"];
  37766. if (keyboard)
  37767. return keyboard.keysUp;
  37768. return [];
  37769. },
  37770. set: function (value) {
  37771. var keyboard = this.inputs.attached["keyboard"];
  37772. if (keyboard)
  37773. keyboard.keysUp = value;
  37774. },
  37775. enumerable: true,
  37776. configurable: true
  37777. });
  37778. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37779. get: function () {
  37780. var keyboard = this.inputs.attached["keyboard"];
  37781. if (keyboard)
  37782. return keyboard.keysDown;
  37783. return [];
  37784. },
  37785. set: function (value) {
  37786. var keyboard = this.inputs.attached["keyboard"];
  37787. if (keyboard)
  37788. keyboard.keysDown = value;
  37789. },
  37790. enumerable: true,
  37791. configurable: true
  37792. });
  37793. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37794. get: function () {
  37795. var keyboard = this.inputs.attached["keyboard"];
  37796. if (keyboard)
  37797. return keyboard.keysLeft;
  37798. return [];
  37799. },
  37800. set: function (value) {
  37801. var keyboard = this.inputs.attached["keyboard"];
  37802. if (keyboard)
  37803. keyboard.keysLeft = value;
  37804. },
  37805. enumerable: true,
  37806. configurable: true
  37807. });
  37808. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37809. get: function () {
  37810. var keyboard = this.inputs.attached["keyboard"];
  37811. if (keyboard)
  37812. return keyboard.keysRight;
  37813. return [];
  37814. },
  37815. set: function (value) {
  37816. var keyboard = this.inputs.attached["keyboard"];
  37817. if (keyboard)
  37818. keyboard.keysRight = value;
  37819. },
  37820. enumerable: true,
  37821. configurable: true
  37822. });
  37823. // Controls
  37824. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37825. this.inputs.attachElement(element, noPreventDefault);
  37826. };
  37827. FreeCamera.prototype.detachControl = function (element) {
  37828. this.inputs.detachElement(element);
  37829. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37830. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37831. };
  37832. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37833. get: function () {
  37834. return this._collisionMask;
  37835. },
  37836. set: function (mask) {
  37837. this._collisionMask = !isNaN(mask) ? mask : -1;
  37838. },
  37839. enumerable: true,
  37840. configurable: true
  37841. });
  37842. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37843. var globalPosition;
  37844. if (this.parent) {
  37845. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37846. }
  37847. else {
  37848. globalPosition = this.position;
  37849. }
  37850. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37851. if (!this._collider) {
  37852. this._collider = new BABYLON.Collider();
  37853. }
  37854. this._collider.radius = this.ellipsoid;
  37855. this._collider.collisionMask = this._collisionMask;
  37856. //no need for clone, as long as gravity is not on.
  37857. var actualDisplacement = displacement;
  37858. //add gravity to the direction to prevent the dual-collision checking
  37859. if (this.applyGravity) {
  37860. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37861. actualDisplacement = displacement.add(this.getScene().gravity);
  37862. }
  37863. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37864. };
  37865. FreeCamera.prototype._checkInputs = function () {
  37866. if (!this._localDirection) {
  37867. this._localDirection = BABYLON.Vector3.Zero();
  37868. this._transformedDirection = BABYLON.Vector3.Zero();
  37869. }
  37870. this.inputs.checkInputs();
  37871. _super.prototype._checkInputs.call(this);
  37872. };
  37873. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37874. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37875. };
  37876. FreeCamera.prototype._updatePosition = function () {
  37877. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37878. this._collideWithWorld(this.cameraDirection);
  37879. }
  37880. else {
  37881. _super.prototype._updatePosition.call(this);
  37882. }
  37883. };
  37884. FreeCamera.prototype.dispose = function () {
  37885. this.inputs.clear();
  37886. _super.prototype.dispose.call(this);
  37887. };
  37888. FreeCamera.prototype.getClassName = function () {
  37889. return "FreeCamera";
  37890. };
  37891. __decorate([
  37892. BABYLON.serializeAsVector3()
  37893. ], FreeCamera.prototype, "ellipsoid", void 0);
  37894. __decorate([
  37895. BABYLON.serialize()
  37896. ], FreeCamera.prototype, "checkCollisions", void 0);
  37897. __decorate([
  37898. BABYLON.serialize()
  37899. ], FreeCamera.prototype, "applyGravity", void 0);
  37900. return FreeCamera;
  37901. }(BABYLON.TargetCamera));
  37902. BABYLON.FreeCamera = FreeCamera;
  37903. })(BABYLON || (BABYLON = {}));
  37904. //# sourceMappingURL=babylon.freeCamera.js.map
  37905. var BABYLON;
  37906. (function (BABYLON) {
  37907. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37908. function ArcRotateCameraKeyboardMoveInput() {
  37909. this._keys = new Array();
  37910. this.keysUp = [38];
  37911. this.keysDown = [40];
  37912. this.keysLeft = [37];
  37913. this.keysRight = [39];
  37914. this.keysReset = [220];
  37915. this.panningSensibility = 50.0;
  37916. this.zoomingSensibility = 25.0;
  37917. this.useAltToZoom = true;
  37918. }
  37919. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37920. var _this = this;
  37921. if (this._onCanvasBlurObserver) {
  37922. return;
  37923. }
  37924. this._scene = this.camera.getScene();
  37925. this._engine = this._scene.getEngine();
  37926. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37927. _this._keys = [];
  37928. });
  37929. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37930. var evt = info.event;
  37931. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37932. _this._ctrlPressed = evt.ctrlKey;
  37933. _this._altPressed = evt.altKey;
  37934. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37935. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37936. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37937. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37938. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37939. var index = _this._keys.indexOf(evt.keyCode);
  37940. if (index === -1) {
  37941. _this._keys.push(evt.keyCode);
  37942. }
  37943. if (evt.preventDefault) {
  37944. if (!noPreventDefault) {
  37945. evt.preventDefault();
  37946. }
  37947. }
  37948. }
  37949. }
  37950. else {
  37951. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37952. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37953. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37954. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37955. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37956. var index = _this._keys.indexOf(evt.keyCode);
  37957. if (index >= 0) {
  37958. _this._keys.splice(index, 1);
  37959. }
  37960. if (evt.preventDefault) {
  37961. if (!noPreventDefault) {
  37962. evt.preventDefault();
  37963. }
  37964. }
  37965. }
  37966. }
  37967. });
  37968. };
  37969. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37970. if (this._scene) {
  37971. if (this._onKeyboardObserver) {
  37972. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37973. }
  37974. if (this._onCanvasBlurObserver) {
  37975. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37976. }
  37977. this._onKeyboardObserver = null;
  37978. this._onCanvasBlurObserver = null;
  37979. }
  37980. this._keys = [];
  37981. };
  37982. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37983. if (this._onKeyboardObserver) {
  37984. var camera = this.camera;
  37985. for (var index = 0; index < this._keys.length; index++) {
  37986. var keyCode = this._keys[index];
  37987. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37988. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37989. camera.inertialPanningX -= 1 / this.panningSensibility;
  37990. }
  37991. else {
  37992. camera.inertialAlphaOffset -= 0.01;
  37993. }
  37994. }
  37995. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37996. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37997. camera.inertialPanningY += 1 / this.panningSensibility;
  37998. }
  37999. else if (this._altPressed && this.useAltToZoom) {
  38000. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  38001. }
  38002. else {
  38003. camera.inertialBetaOffset -= 0.01;
  38004. }
  38005. }
  38006. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38007. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38008. camera.inertialPanningX += 1 / this.panningSensibility;
  38009. }
  38010. else {
  38011. camera.inertialAlphaOffset += 0.01;
  38012. }
  38013. }
  38014. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38015. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38016. camera.inertialPanningY -= 1 / this.panningSensibility;
  38017. }
  38018. else if (this._altPressed && this.useAltToZoom) {
  38019. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  38020. }
  38021. else {
  38022. camera.inertialBetaOffset += 0.01;
  38023. }
  38024. }
  38025. else if (this.keysReset.indexOf(keyCode) !== -1) {
  38026. camera.restoreState();
  38027. }
  38028. }
  38029. }
  38030. };
  38031. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38032. return "ArcRotateCameraKeyboardMoveInput";
  38033. };
  38034. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38035. return "keyboard";
  38036. };
  38037. __decorate([
  38038. BABYLON.serialize()
  38039. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38040. __decorate([
  38041. BABYLON.serialize()
  38042. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38043. __decorate([
  38044. BABYLON.serialize()
  38045. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38046. __decorate([
  38047. BABYLON.serialize()
  38048. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38049. __decorate([
  38050. BABYLON.serialize()
  38051. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38052. __decorate([
  38053. BABYLON.serialize()
  38054. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38055. __decorate([
  38056. BABYLON.serialize()
  38057. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38058. __decorate([
  38059. BABYLON.serialize()
  38060. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38061. return ArcRotateCameraKeyboardMoveInput;
  38062. }());
  38063. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38064. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38065. })(BABYLON || (BABYLON = {}));
  38066. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38067. var BABYLON;
  38068. (function (BABYLON) {
  38069. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38070. function ArcRotateCameraMouseWheelInput() {
  38071. this.wheelPrecision = 3.0;
  38072. /**
  38073. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38074. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38075. */
  38076. this.wheelDeltaPercentage = 0;
  38077. }
  38078. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38079. var _this = this;
  38080. this._wheel = function (p, s) {
  38081. //sanity check - this should be a PointerWheel event.
  38082. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38083. return;
  38084. var event = p.event;
  38085. var delta = 0;
  38086. if (event.wheelDelta) {
  38087. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38088. }
  38089. else if (event.detail) {
  38090. delta = -event.detail / _this.wheelPrecision;
  38091. }
  38092. if (delta)
  38093. _this.camera.inertialRadiusOffset += delta;
  38094. if (event.preventDefault) {
  38095. if (!noPreventDefault) {
  38096. event.preventDefault();
  38097. }
  38098. }
  38099. };
  38100. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38101. };
  38102. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38103. if (this._observer && element) {
  38104. this.camera.getScene().onPointerObservable.remove(this._observer);
  38105. this._observer = null;
  38106. this._wheel = null;
  38107. }
  38108. };
  38109. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38110. return "ArcRotateCameraMouseWheelInput";
  38111. };
  38112. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38113. return "mousewheel";
  38114. };
  38115. __decorate([
  38116. BABYLON.serialize()
  38117. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38118. __decorate([
  38119. BABYLON.serialize()
  38120. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38121. return ArcRotateCameraMouseWheelInput;
  38122. }());
  38123. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38124. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38125. })(BABYLON || (BABYLON = {}));
  38126. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38127. var BABYLON;
  38128. (function (BABYLON) {
  38129. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38130. function ArcRotateCameraPointersInput() {
  38131. this.buttons = [0, 1, 2];
  38132. this.angularSensibilityX = 1000.0;
  38133. this.angularSensibilityY = 1000.0;
  38134. this.pinchPrecision = 12.0;
  38135. /**
  38136. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38137. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38138. */
  38139. this.pinchDeltaPercentage = 0;
  38140. this.panningSensibility = 1000.0;
  38141. this.multiTouchPanning = true;
  38142. this.multiTouchPanAndZoom = true;
  38143. this._isPanClick = false;
  38144. this.pinchInwards = true;
  38145. }
  38146. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38147. var _this = this;
  38148. var engine = this.camera.getEngine();
  38149. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38150. var pointA = null;
  38151. var pointB = null;
  38152. var previousPinchSquaredDistance = 0;
  38153. var initialDistance = 0;
  38154. var twoFingerActivityCount = 0;
  38155. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38156. this._pointerInput = function (p, s) {
  38157. var evt = p.event;
  38158. var isTouch = p.event.pointerType === "touch";
  38159. if (engine.isInVRExclusivePointerMode) {
  38160. return;
  38161. }
  38162. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38163. return;
  38164. }
  38165. var srcElement = (evt.srcElement || evt.target);
  38166. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38167. try {
  38168. srcElement.setPointerCapture(evt.pointerId);
  38169. }
  38170. catch (e) {
  38171. //Nothing to do with the error. Execution will continue.
  38172. }
  38173. // Manage panning with pan button click
  38174. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38175. // manage pointers
  38176. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38177. if (pointA === null) {
  38178. pointA = cacheSoloPointer;
  38179. }
  38180. else if (pointB === null) {
  38181. pointB = cacheSoloPointer;
  38182. }
  38183. if (!noPreventDefault) {
  38184. evt.preventDefault();
  38185. element.focus();
  38186. }
  38187. }
  38188. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38189. _this.camera.restoreState();
  38190. }
  38191. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38192. try {
  38193. srcElement.releasePointerCapture(evt.pointerId);
  38194. }
  38195. catch (e) {
  38196. //Nothing to do with the error.
  38197. }
  38198. cacheSoloPointer = null;
  38199. previousPinchSquaredDistance = 0;
  38200. previousMultiTouchPanPosition.isPaning = false;
  38201. previousMultiTouchPanPosition.isPinching = false;
  38202. twoFingerActivityCount = 0;
  38203. initialDistance = 0;
  38204. if (!isTouch) {
  38205. pointB = null; // Mouse and pen are mono pointer
  38206. }
  38207. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38208. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38209. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38210. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38211. if (engine.badOS) {
  38212. pointA = pointB = null;
  38213. }
  38214. else {
  38215. //only remove the impacted pointer in case of multitouch allowing on most
  38216. //platforms switching from rotate to zoom and pan seamlessly.
  38217. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38218. pointA = pointB;
  38219. pointB = null;
  38220. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38221. }
  38222. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38223. pointB = null;
  38224. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38225. }
  38226. else {
  38227. pointA = pointB = null;
  38228. }
  38229. }
  38230. if (!noPreventDefault) {
  38231. evt.preventDefault();
  38232. }
  38233. }
  38234. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38235. if (!noPreventDefault) {
  38236. evt.preventDefault();
  38237. }
  38238. // One button down
  38239. if (pointA && pointB === null && cacheSoloPointer) {
  38240. if (_this.panningSensibility !== 0 &&
  38241. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38242. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38243. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38244. }
  38245. else {
  38246. var offsetX = evt.clientX - cacheSoloPointer.x;
  38247. var offsetY = evt.clientY - cacheSoloPointer.y;
  38248. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38249. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38250. }
  38251. cacheSoloPointer.x = evt.clientX;
  38252. cacheSoloPointer.y = evt.clientY;
  38253. }
  38254. else if (pointA && pointB) {
  38255. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38256. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38257. ed.x = evt.clientX;
  38258. ed.y = evt.clientY;
  38259. var direction = _this.pinchInwards ? 1 : -1;
  38260. var distX = pointA.x - pointB.x;
  38261. var distY = pointA.y - pointB.y;
  38262. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38263. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38264. if (previousPinchSquaredDistance === 0) {
  38265. initialDistance = pinchDistance;
  38266. previousPinchSquaredDistance = pinchSquaredDistance;
  38267. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38268. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38269. return;
  38270. }
  38271. if (_this.multiTouchPanAndZoom) {
  38272. if (_this.pinchDeltaPercentage) {
  38273. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38274. }
  38275. else {
  38276. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38277. (_this.pinchPrecision *
  38278. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38279. direction);
  38280. }
  38281. if (_this.panningSensibility !== 0) {
  38282. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38283. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38284. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38285. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38286. previousMultiTouchPanPosition.x = pointersCenterX;
  38287. previousMultiTouchPanPosition.y = pointersCenterY;
  38288. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38289. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38290. }
  38291. }
  38292. else {
  38293. twoFingerActivityCount++;
  38294. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38295. if (_this.pinchDeltaPercentage) {
  38296. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38297. }
  38298. else {
  38299. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38300. (_this.pinchPrecision *
  38301. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38302. direction);
  38303. }
  38304. previousMultiTouchPanPosition.isPaning = false;
  38305. previousMultiTouchPanPosition.isPinching = true;
  38306. }
  38307. else {
  38308. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38309. if (!previousMultiTouchPanPosition.isPaning) {
  38310. previousMultiTouchPanPosition.isPaning = true;
  38311. previousMultiTouchPanPosition.isPinching = false;
  38312. previousMultiTouchPanPosition.x = ed.x;
  38313. previousMultiTouchPanPosition.y = ed.y;
  38314. return;
  38315. }
  38316. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38317. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38318. }
  38319. }
  38320. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38321. previousMultiTouchPanPosition.x = ed.x;
  38322. previousMultiTouchPanPosition.y = ed.y;
  38323. }
  38324. }
  38325. previousPinchSquaredDistance = pinchSquaredDistance;
  38326. }
  38327. }
  38328. };
  38329. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38330. this._onContextMenu = function (evt) {
  38331. evt.preventDefault();
  38332. };
  38333. if (!this.camera._useCtrlForPanning) {
  38334. element.addEventListener("contextmenu", this._onContextMenu, false);
  38335. }
  38336. this._onLostFocus = function () {
  38337. //this._keys = [];
  38338. pointA = pointB = null;
  38339. previousPinchSquaredDistance = 0;
  38340. previousMultiTouchPanPosition.isPaning = false;
  38341. previousMultiTouchPanPosition.isPinching = false;
  38342. twoFingerActivityCount = 0;
  38343. cacheSoloPointer = null;
  38344. initialDistance = 0;
  38345. };
  38346. this._onMouseMove = function (evt) {
  38347. if (!engine.isPointerLock) {
  38348. return;
  38349. }
  38350. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38351. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38352. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38353. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38354. if (!noPreventDefault) {
  38355. evt.preventDefault();
  38356. }
  38357. };
  38358. this._onGestureStart = function (e) {
  38359. if (window.MSGesture === undefined) {
  38360. return;
  38361. }
  38362. if (!_this._MSGestureHandler) {
  38363. _this._MSGestureHandler = new MSGesture();
  38364. _this._MSGestureHandler.target = element;
  38365. }
  38366. _this._MSGestureHandler.addPointer(e.pointerId);
  38367. };
  38368. this._onGesture = function (e) {
  38369. _this.camera.radius *= e.scale;
  38370. if (e.preventDefault) {
  38371. if (!noPreventDefault) {
  38372. e.stopPropagation();
  38373. e.preventDefault();
  38374. }
  38375. }
  38376. };
  38377. element.addEventListener("mousemove", this._onMouseMove, false);
  38378. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38379. element.addEventListener("MSGestureChange", this._onGesture, false);
  38380. BABYLON.Tools.RegisterTopRootEvents([
  38381. { name: "blur", handler: this._onLostFocus }
  38382. ]);
  38383. };
  38384. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38385. if (this._onLostFocus) {
  38386. BABYLON.Tools.UnregisterTopRootEvents([
  38387. { name: "blur", handler: this._onLostFocus }
  38388. ]);
  38389. }
  38390. if (element && this._observer) {
  38391. this.camera.getScene().onPointerObservable.remove(this._observer);
  38392. this._observer = null;
  38393. if (this._onContextMenu) {
  38394. element.removeEventListener("contextmenu", this._onContextMenu);
  38395. }
  38396. if (this._onMouseMove) {
  38397. element.removeEventListener("mousemove", this._onMouseMove);
  38398. }
  38399. if (this._onGestureStart) {
  38400. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38401. }
  38402. if (this._onGesture) {
  38403. element.removeEventListener("MSGestureChange", this._onGesture);
  38404. }
  38405. this._isPanClick = false;
  38406. this.pinchInwards = true;
  38407. this._onMouseMove = null;
  38408. this._onGestureStart = null;
  38409. this._onGesture = null;
  38410. this._MSGestureHandler = null;
  38411. this._onLostFocus = null;
  38412. this._onContextMenu = null;
  38413. }
  38414. };
  38415. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38416. return "ArcRotateCameraPointersInput";
  38417. };
  38418. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38419. return "pointers";
  38420. };
  38421. __decorate([
  38422. BABYLON.serialize()
  38423. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38424. __decorate([
  38425. BABYLON.serialize()
  38426. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38427. __decorate([
  38428. BABYLON.serialize()
  38429. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38430. __decorate([
  38431. BABYLON.serialize()
  38432. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38433. __decorate([
  38434. BABYLON.serialize()
  38435. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38436. __decorate([
  38437. BABYLON.serialize()
  38438. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38439. __decorate([
  38440. BABYLON.serialize()
  38441. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38442. __decorate([
  38443. BABYLON.serialize()
  38444. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38445. return ArcRotateCameraPointersInput;
  38446. }());
  38447. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38448. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38449. })(BABYLON || (BABYLON = {}));
  38450. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38451. var BABYLON;
  38452. (function (BABYLON) {
  38453. var ArcRotateCamera = /** @class */ (function (_super) {
  38454. __extends(ArcRotateCamera, _super);
  38455. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38456. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38457. _this.inertialAlphaOffset = 0;
  38458. _this.inertialBetaOffset = 0;
  38459. _this.inertialRadiusOffset = 0;
  38460. _this.lowerAlphaLimit = null;
  38461. _this.upperAlphaLimit = null;
  38462. _this.lowerBetaLimit = 0.01;
  38463. _this.upperBetaLimit = Math.PI;
  38464. _this.lowerRadiusLimit = null;
  38465. _this.upperRadiusLimit = null;
  38466. _this.inertialPanningX = 0;
  38467. _this.inertialPanningY = 0;
  38468. _this.pinchToPanMaxDistance = 20;
  38469. _this.panningDistanceLimit = null;
  38470. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38471. _this.panningInertia = 0.9;
  38472. //-- end properties for backward compatibility for inputs
  38473. _this.zoomOnFactor = 1;
  38474. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38475. _this.allowUpsideDown = true;
  38476. _this._viewMatrix = new BABYLON.Matrix();
  38477. // Panning
  38478. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38479. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38480. _this.checkCollisions = false;
  38481. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38482. _this._previousPosition = BABYLON.Vector3.Zero();
  38483. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38484. _this._newPosition = BABYLON.Vector3.Zero();
  38485. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38486. if (collidedMesh === void 0) { collidedMesh = null; }
  38487. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38488. newPosition.multiplyInPlace(_this._collider.radius);
  38489. }
  38490. if (!collidedMesh) {
  38491. _this._previousPosition.copyFrom(_this.position);
  38492. }
  38493. else {
  38494. _this.setPosition(newPosition);
  38495. if (_this.onCollide) {
  38496. _this.onCollide(collidedMesh);
  38497. }
  38498. }
  38499. // Recompute because of constraints
  38500. var cosa = Math.cos(_this.alpha);
  38501. var sina = Math.sin(_this.alpha);
  38502. var cosb = Math.cos(_this.beta);
  38503. var sinb = Math.sin(_this.beta);
  38504. if (sinb === 0) {
  38505. sinb = 0.0001;
  38506. }
  38507. var target = _this._getTargetPosition();
  38508. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38509. _this.position.copyFrom(_this._newPosition);
  38510. var up = _this.upVector;
  38511. if (_this.allowUpsideDown && _this.beta < 0) {
  38512. up = up.clone();
  38513. up = up.negate();
  38514. }
  38515. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38516. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38517. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38518. _this._collisionTriggered = false;
  38519. };
  38520. _this._target = BABYLON.Vector3.Zero();
  38521. if (target) {
  38522. _this.setTarget(target);
  38523. }
  38524. _this.alpha = alpha;
  38525. _this.beta = beta;
  38526. _this.radius = radius;
  38527. _this.getViewMatrix();
  38528. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38529. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38530. return _this;
  38531. }
  38532. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38533. get: function () {
  38534. return this._target;
  38535. },
  38536. set: function (value) {
  38537. this.setTarget(value);
  38538. },
  38539. enumerable: true,
  38540. configurable: true
  38541. });
  38542. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38543. //-- begin properties for backward compatibility for inputs
  38544. get: function () {
  38545. var pointers = this.inputs.attached["pointers"];
  38546. if (pointers)
  38547. return pointers.angularSensibilityX;
  38548. return 0;
  38549. },
  38550. set: function (value) {
  38551. var pointers = this.inputs.attached["pointers"];
  38552. if (pointers) {
  38553. pointers.angularSensibilityX = value;
  38554. }
  38555. },
  38556. enumerable: true,
  38557. configurable: true
  38558. });
  38559. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38560. get: function () {
  38561. var pointers = this.inputs.attached["pointers"];
  38562. if (pointers)
  38563. return pointers.angularSensibilityY;
  38564. return 0;
  38565. },
  38566. set: function (value) {
  38567. var pointers = this.inputs.attached["pointers"];
  38568. if (pointers) {
  38569. pointers.angularSensibilityY = value;
  38570. }
  38571. },
  38572. enumerable: true,
  38573. configurable: true
  38574. });
  38575. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38576. get: function () {
  38577. var pointers = this.inputs.attached["pointers"];
  38578. if (pointers)
  38579. return pointers.pinchPrecision;
  38580. return 0;
  38581. },
  38582. set: function (value) {
  38583. var pointers = this.inputs.attached["pointers"];
  38584. if (pointers) {
  38585. pointers.pinchPrecision = value;
  38586. }
  38587. },
  38588. enumerable: true,
  38589. configurable: true
  38590. });
  38591. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38592. get: function () {
  38593. var pointers = this.inputs.attached["pointers"];
  38594. if (pointers)
  38595. return pointers.pinchDeltaPercentage;
  38596. return 0;
  38597. },
  38598. set: function (value) {
  38599. var pointers = this.inputs.attached["pointers"];
  38600. if (pointers) {
  38601. pointers.pinchDeltaPercentage = value;
  38602. }
  38603. },
  38604. enumerable: true,
  38605. configurable: true
  38606. });
  38607. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38608. get: function () {
  38609. var pointers = this.inputs.attached["pointers"];
  38610. if (pointers)
  38611. return pointers.panningSensibility;
  38612. return 0;
  38613. },
  38614. set: function (value) {
  38615. var pointers = this.inputs.attached["pointers"];
  38616. if (pointers) {
  38617. pointers.panningSensibility = value;
  38618. }
  38619. },
  38620. enumerable: true,
  38621. configurable: true
  38622. });
  38623. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38624. get: function () {
  38625. var keyboard = this.inputs.attached["keyboard"];
  38626. if (keyboard)
  38627. return keyboard.keysUp;
  38628. return [];
  38629. },
  38630. set: function (value) {
  38631. var keyboard = this.inputs.attached["keyboard"];
  38632. if (keyboard)
  38633. keyboard.keysUp = value;
  38634. },
  38635. enumerable: true,
  38636. configurable: true
  38637. });
  38638. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38639. get: function () {
  38640. var keyboard = this.inputs.attached["keyboard"];
  38641. if (keyboard)
  38642. return keyboard.keysDown;
  38643. return [];
  38644. },
  38645. set: function (value) {
  38646. var keyboard = this.inputs.attached["keyboard"];
  38647. if (keyboard)
  38648. keyboard.keysDown = value;
  38649. },
  38650. enumerable: true,
  38651. configurable: true
  38652. });
  38653. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38654. get: function () {
  38655. var keyboard = this.inputs.attached["keyboard"];
  38656. if (keyboard)
  38657. return keyboard.keysLeft;
  38658. return [];
  38659. },
  38660. set: function (value) {
  38661. var keyboard = this.inputs.attached["keyboard"];
  38662. if (keyboard)
  38663. keyboard.keysLeft = value;
  38664. },
  38665. enumerable: true,
  38666. configurable: true
  38667. });
  38668. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38669. get: function () {
  38670. var keyboard = this.inputs.attached["keyboard"];
  38671. if (keyboard)
  38672. return keyboard.keysRight;
  38673. return [];
  38674. },
  38675. set: function (value) {
  38676. var keyboard = this.inputs.attached["keyboard"];
  38677. if (keyboard)
  38678. keyboard.keysRight = value;
  38679. },
  38680. enumerable: true,
  38681. configurable: true
  38682. });
  38683. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38684. get: function () {
  38685. var mousewheel = this.inputs.attached["mousewheel"];
  38686. if (mousewheel)
  38687. return mousewheel.wheelPrecision;
  38688. return 0;
  38689. },
  38690. set: function (value) {
  38691. var mousewheel = this.inputs.attached["mousewheel"];
  38692. if (mousewheel)
  38693. mousewheel.wheelPrecision = value;
  38694. },
  38695. enumerable: true,
  38696. configurable: true
  38697. });
  38698. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38699. get: function () {
  38700. var mousewheel = this.inputs.attached["mousewheel"];
  38701. if (mousewheel)
  38702. return mousewheel.wheelDeltaPercentage;
  38703. return 0;
  38704. },
  38705. set: function (value) {
  38706. var mousewheel = this.inputs.attached["mousewheel"];
  38707. if (mousewheel)
  38708. mousewheel.wheelDeltaPercentage = value;
  38709. },
  38710. enumerable: true,
  38711. configurable: true
  38712. });
  38713. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38714. get: function () {
  38715. return this._bouncingBehavior;
  38716. },
  38717. enumerable: true,
  38718. configurable: true
  38719. });
  38720. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38721. get: function () {
  38722. return this._bouncingBehavior != null;
  38723. },
  38724. set: function (value) {
  38725. if (value === this.useBouncingBehavior) {
  38726. return;
  38727. }
  38728. if (value) {
  38729. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38730. this.addBehavior(this._bouncingBehavior);
  38731. }
  38732. else if (this._bouncingBehavior) {
  38733. this.removeBehavior(this._bouncingBehavior);
  38734. this._bouncingBehavior = null;
  38735. }
  38736. },
  38737. enumerable: true,
  38738. configurable: true
  38739. });
  38740. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38741. get: function () {
  38742. return this._framingBehavior;
  38743. },
  38744. enumerable: true,
  38745. configurable: true
  38746. });
  38747. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38748. get: function () {
  38749. return this._framingBehavior != null;
  38750. },
  38751. set: function (value) {
  38752. if (value === this.useFramingBehavior) {
  38753. return;
  38754. }
  38755. if (value) {
  38756. this._framingBehavior = new BABYLON.FramingBehavior();
  38757. this.addBehavior(this._framingBehavior);
  38758. }
  38759. else if (this._framingBehavior) {
  38760. this.removeBehavior(this._framingBehavior);
  38761. this._framingBehavior = null;
  38762. }
  38763. },
  38764. enumerable: true,
  38765. configurable: true
  38766. });
  38767. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38768. get: function () {
  38769. return this._autoRotationBehavior;
  38770. },
  38771. enumerable: true,
  38772. configurable: true
  38773. });
  38774. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38775. get: function () {
  38776. return this._autoRotationBehavior != null;
  38777. },
  38778. set: function (value) {
  38779. if (value === this.useAutoRotationBehavior) {
  38780. return;
  38781. }
  38782. if (value) {
  38783. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38784. this.addBehavior(this._autoRotationBehavior);
  38785. }
  38786. else if (this._autoRotationBehavior) {
  38787. this.removeBehavior(this._autoRotationBehavior);
  38788. this._autoRotationBehavior = null;
  38789. }
  38790. },
  38791. enumerable: true,
  38792. configurable: true
  38793. });
  38794. // Cache
  38795. ArcRotateCamera.prototype._initCache = function () {
  38796. _super.prototype._initCache.call(this);
  38797. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38798. this._cache.alpha = undefined;
  38799. this._cache.beta = undefined;
  38800. this._cache.radius = undefined;
  38801. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38802. };
  38803. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38804. if (!ignoreParentClass) {
  38805. _super.prototype._updateCache.call(this);
  38806. }
  38807. this._cache._target.copyFrom(this._getTargetPosition());
  38808. this._cache.alpha = this.alpha;
  38809. this._cache.beta = this.beta;
  38810. this._cache.radius = this.radius;
  38811. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38812. };
  38813. ArcRotateCamera.prototype._getTargetPosition = function () {
  38814. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38815. var pos = this._targetHost.getAbsolutePosition();
  38816. if (this._targetBoundingCenter) {
  38817. pos.addToRef(this._targetBoundingCenter, this._target);
  38818. }
  38819. else {
  38820. this._target.copyFrom(pos);
  38821. }
  38822. }
  38823. var lockedTargetPosition = this._getLockedTargetPosition();
  38824. if (lockedTargetPosition) {
  38825. return lockedTargetPosition;
  38826. }
  38827. return this._target;
  38828. };
  38829. ArcRotateCamera.prototype.storeState = function () {
  38830. this._storedAlpha = this.alpha;
  38831. this._storedBeta = this.beta;
  38832. this._storedRadius = this.radius;
  38833. this._storedTarget = this._getTargetPosition().clone();
  38834. return _super.prototype.storeState.call(this);
  38835. };
  38836. /**
  38837. * Restored camera state. You must call storeState() first
  38838. */
  38839. ArcRotateCamera.prototype._restoreStateValues = function () {
  38840. if (!_super.prototype._restoreStateValues.call(this)) {
  38841. return false;
  38842. }
  38843. this.alpha = this._storedAlpha;
  38844. this.beta = this._storedBeta;
  38845. this.radius = this._storedRadius;
  38846. this.setTarget(this._storedTarget.clone());
  38847. this.inertialAlphaOffset = 0;
  38848. this.inertialBetaOffset = 0;
  38849. this.inertialRadiusOffset = 0;
  38850. this.inertialPanningX = 0;
  38851. this.inertialPanningY = 0;
  38852. return true;
  38853. };
  38854. // Synchronized
  38855. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38856. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38857. return false;
  38858. return this._cache._target.equals(this._getTargetPosition())
  38859. && this._cache.alpha === this.alpha
  38860. && this._cache.beta === this.beta
  38861. && this._cache.radius === this.radius
  38862. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38863. };
  38864. // Methods
  38865. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38866. var _this = this;
  38867. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38868. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38869. this._useCtrlForPanning = useCtrlForPanning;
  38870. this._panningMouseButton = panningMouseButton;
  38871. this.inputs.attachElement(element, noPreventDefault);
  38872. this._reset = function () {
  38873. _this.inertialAlphaOffset = 0;
  38874. _this.inertialBetaOffset = 0;
  38875. _this.inertialRadiusOffset = 0;
  38876. _this.inertialPanningX = 0;
  38877. _this.inertialPanningY = 0;
  38878. };
  38879. };
  38880. ArcRotateCamera.prototype.detachControl = function (element) {
  38881. this.inputs.detachElement(element);
  38882. if (this._reset) {
  38883. this._reset();
  38884. }
  38885. };
  38886. ArcRotateCamera.prototype._checkInputs = function () {
  38887. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38888. if (this._collisionTriggered) {
  38889. return;
  38890. }
  38891. this.inputs.checkInputs();
  38892. // Inertia
  38893. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38894. if (this.getScene().useRightHandedSystem) {
  38895. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38896. }
  38897. else {
  38898. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38899. }
  38900. this.beta += this.inertialBetaOffset;
  38901. this.radius -= this.inertialRadiusOffset;
  38902. this.inertialAlphaOffset *= this.inertia;
  38903. this.inertialBetaOffset *= this.inertia;
  38904. this.inertialRadiusOffset *= this.inertia;
  38905. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38906. this.inertialAlphaOffset = 0;
  38907. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38908. this.inertialBetaOffset = 0;
  38909. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38910. this.inertialRadiusOffset = 0;
  38911. }
  38912. // Panning inertia
  38913. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38914. if (!this._localDirection) {
  38915. this._localDirection = BABYLON.Vector3.Zero();
  38916. this._transformedDirection = BABYLON.Vector3.Zero();
  38917. }
  38918. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38919. this._localDirection.multiplyInPlace(this.panningAxis);
  38920. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38921. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38922. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38923. if (!this.panningAxis.y) {
  38924. this._transformedDirection.y = 0;
  38925. }
  38926. if (!this._targetHost) {
  38927. if (this.panningDistanceLimit) {
  38928. this._transformedDirection.addInPlace(this._target);
  38929. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38930. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38931. this._target.copyFrom(this._transformedDirection);
  38932. }
  38933. }
  38934. else {
  38935. this._target.addInPlace(this._transformedDirection);
  38936. }
  38937. }
  38938. this.inertialPanningX *= this.panningInertia;
  38939. this.inertialPanningY *= this.panningInertia;
  38940. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38941. this.inertialPanningX = 0;
  38942. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38943. this.inertialPanningY = 0;
  38944. }
  38945. // Limits
  38946. this._checkLimits();
  38947. _super.prototype._checkInputs.call(this);
  38948. };
  38949. ArcRotateCamera.prototype._checkLimits = function () {
  38950. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38951. if (this.allowUpsideDown && this.beta > Math.PI) {
  38952. this.beta = this.beta - (2 * Math.PI);
  38953. }
  38954. }
  38955. else {
  38956. if (this.beta < this.lowerBetaLimit) {
  38957. this.beta = this.lowerBetaLimit;
  38958. }
  38959. }
  38960. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38961. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38962. this.beta = this.beta + (2 * Math.PI);
  38963. }
  38964. }
  38965. else {
  38966. if (this.beta > this.upperBetaLimit) {
  38967. this.beta = this.upperBetaLimit;
  38968. }
  38969. }
  38970. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38971. this.alpha = this.lowerAlphaLimit;
  38972. }
  38973. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38974. this.alpha = this.upperAlphaLimit;
  38975. }
  38976. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38977. this.radius = this.lowerRadiusLimit;
  38978. }
  38979. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38980. this.radius = this.upperRadiusLimit;
  38981. }
  38982. };
  38983. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38984. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38985. this.radius = radiusv3.length();
  38986. if (this.radius === 0) {
  38987. this.radius = 0.0001; // Just to avoid division by zero
  38988. }
  38989. // Alpha
  38990. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38991. if (radiusv3.z < 0) {
  38992. this.alpha = 2 * Math.PI - this.alpha;
  38993. }
  38994. // Beta
  38995. this.beta = Math.acos(radiusv3.y / this.radius);
  38996. this._checkLimits();
  38997. };
  38998. ArcRotateCamera.prototype.setPosition = function (position) {
  38999. if (this.position.equals(position)) {
  39000. return;
  39001. }
  39002. this.position.copyFrom(position);
  39003. this.rebuildAnglesAndRadius();
  39004. };
  39005. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  39006. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  39007. if (allowSamePosition === void 0) { allowSamePosition = false; }
  39008. if (target.getBoundingInfo) {
  39009. if (toBoundingCenter) {
  39010. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  39011. }
  39012. else {
  39013. this._targetBoundingCenter = null;
  39014. }
  39015. this._targetHost = target;
  39016. this._target = this._getTargetPosition();
  39017. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  39018. }
  39019. else {
  39020. var newTarget = target;
  39021. var currentTarget = this._getTargetPosition();
  39022. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  39023. return;
  39024. }
  39025. this._targetHost = null;
  39026. this._target = newTarget;
  39027. this._targetBoundingCenter = null;
  39028. this.onMeshTargetChangedObservable.notifyObservers(null);
  39029. }
  39030. this.rebuildAnglesAndRadius();
  39031. };
  39032. ArcRotateCamera.prototype._getViewMatrix = function () {
  39033. // Compute
  39034. var cosa = Math.cos(this.alpha);
  39035. var sina = Math.sin(this.alpha);
  39036. var cosb = Math.cos(this.beta);
  39037. var sinb = Math.sin(this.beta);
  39038. if (sinb === 0) {
  39039. sinb = 0.0001;
  39040. }
  39041. var target = this._getTargetPosition();
  39042. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39043. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39044. if (!this._collider) {
  39045. this._collider = new BABYLON.Collider();
  39046. }
  39047. this._collider.radius = this.collisionRadius;
  39048. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39049. this._collisionTriggered = true;
  39050. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39051. }
  39052. else {
  39053. this.position.copyFrom(this._newPosition);
  39054. var up = this.upVector;
  39055. if (this.allowUpsideDown && sinb < 0) {
  39056. up = up.clone();
  39057. up = up.negate();
  39058. }
  39059. if (this.getScene().useRightHandedSystem) {
  39060. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39061. }
  39062. else {
  39063. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39064. }
  39065. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39066. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39067. }
  39068. this._currentTarget = target;
  39069. return this._viewMatrix;
  39070. };
  39071. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39072. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39073. meshes = meshes || this.getScene().meshes;
  39074. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39075. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39076. this.radius = distance * this.zoomOnFactor;
  39077. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39078. };
  39079. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39080. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39081. var meshesOrMinMaxVector;
  39082. var distance;
  39083. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39084. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39085. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39086. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39087. }
  39088. else {
  39089. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39090. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39091. distance = minMaxVectorAndDistance.distance;
  39092. }
  39093. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39094. if (!doNotUpdateMaxZ) {
  39095. this.maxZ = distance * 2;
  39096. }
  39097. };
  39098. /**
  39099. * @override
  39100. * Override Camera.createRigCamera
  39101. */
  39102. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39103. var alphaShift = 0;
  39104. switch (this.cameraRigMode) {
  39105. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39106. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39107. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39108. case BABYLON.Camera.RIG_MODE_VR:
  39109. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39110. break;
  39111. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39112. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39113. break;
  39114. }
  39115. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39116. rigCam._cameraRigParams = {};
  39117. return rigCam;
  39118. };
  39119. /**
  39120. * @override
  39121. * Override Camera._updateRigCameras
  39122. */
  39123. ArcRotateCamera.prototype._updateRigCameras = function () {
  39124. var camLeft = this._rigCameras[0];
  39125. var camRight = this._rigCameras[1];
  39126. camLeft.beta = camRight.beta = this.beta;
  39127. camLeft.radius = camRight.radius = this.radius;
  39128. switch (this.cameraRigMode) {
  39129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39131. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39132. case BABYLON.Camera.RIG_MODE_VR:
  39133. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39134. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39135. break;
  39136. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39137. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39138. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39139. break;
  39140. }
  39141. _super.prototype._updateRigCameras.call(this);
  39142. };
  39143. ArcRotateCamera.prototype.dispose = function () {
  39144. this.inputs.clear();
  39145. _super.prototype.dispose.call(this);
  39146. };
  39147. ArcRotateCamera.prototype.getClassName = function () {
  39148. return "ArcRotateCamera";
  39149. };
  39150. __decorate([
  39151. BABYLON.serialize()
  39152. ], ArcRotateCamera.prototype, "alpha", void 0);
  39153. __decorate([
  39154. BABYLON.serialize()
  39155. ], ArcRotateCamera.prototype, "beta", void 0);
  39156. __decorate([
  39157. BABYLON.serialize()
  39158. ], ArcRotateCamera.prototype, "radius", void 0);
  39159. __decorate([
  39160. BABYLON.serializeAsVector3("target")
  39161. ], ArcRotateCamera.prototype, "_target", void 0);
  39162. __decorate([
  39163. BABYLON.serialize()
  39164. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39165. __decorate([
  39166. BABYLON.serialize()
  39167. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39168. __decorate([
  39169. BABYLON.serialize()
  39170. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39171. __decorate([
  39172. BABYLON.serialize()
  39173. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39174. __decorate([
  39175. BABYLON.serialize()
  39176. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39177. __decorate([
  39178. BABYLON.serialize()
  39179. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39180. __decorate([
  39181. BABYLON.serialize()
  39182. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39183. __decorate([
  39184. BABYLON.serialize()
  39185. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39186. __decorate([
  39187. BABYLON.serialize()
  39188. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39189. __decorate([
  39190. BABYLON.serialize()
  39191. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39192. __decorate([
  39193. BABYLON.serialize()
  39194. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39195. __decorate([
  39196. BABYLON.serialize()
  39197. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39198. __decorate([
  39199. BABYLON.serialize()
  39200. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39201. __decorate([
  39202. BABYLON.serializeAsVector3()
  39203. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39204. __decorate([
  39205. BABYLON.serialize()
  39206. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39207. __decorate([
  39208. BABYLON.serialize()
  39209. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39210. __decorate([
  39211. BABYLON.serialize()
  39212. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39213. return ArcRotateCamera;
  39214. }(BABYLON.TargetCamera));
  39215. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39216. })(BABYLON || (BABYLON = {}));
  39217. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39218. var BABYLON;
  39219. (function (BABYLON) {
  39220. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39221. __extends(ArcRotateCameraInputsManager, _super);
  39222. function ArcRotateCameraInputsManager(camera) {
  39223. return _super.call(this, camera) || this;
  39224. }
  39225. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39226. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39227. return this;
  39228. };
  39229. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39230. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39231. return this;
  39232. };
  39233. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39234. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39235. return this;
  39236. };
  39237. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39238. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39239. return this;
  39240. };
  39241. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39242. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39243. return this;
  39244. };
  39245. return ArcRotateCameraInputsManager;
  39246. }(BABYLON.CameraInputsManager));
  39247. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39248. })(BABYLON || (BABYLON = {}));
  39249. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39250. var BABYLON;
  39251. (function (BABYLON) {
  39252. var HemisphericLight = /** @class */ (function (_super) {
  39253. __extends(HemisphericLight, _super);
  39254. /**
  39255. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39256. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39257. * The HemisphericLight can't cast shadows.
  39258. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39259. */
  39260. function HemisphericLight(name, direction, scene) {
  39261. var _this = _super.call(this, name, scene) || this;
  39262. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39263. _this.direction = direction || BABYLON.Vector3.Up();
  39264. return _this;
  39265. }
  39266. HemisphericLight.prototype._buildUniformLayout = function () {
  39267. this._uniformBuffer.addUniform("vLightData", 4);
  39268. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39269. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39270. this._uniformBuffer.addUniform("vLightGround", 3);
  39271. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39272. this._uniformBuffer.addUniform("depthValues", 2);
  39273. this._uniformBuffer.create();
  39274. };
  39275. /**
  39276. * Returns the string "HemisphericLight".
  39277. */
  39278. HemisphericLight.prototype.getClassName = function () {
  39279. return "HemisphericLight";
  39280. };
  39281. /**
  39282. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39283. * Returns the updated direction.
  39284. */
  39285. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39286. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39287. return this.direction;
  39288. };
  39289. HemisphericLight.prototype.getShadowGenerator = function () {
  39290. return null;
  39291. };
  39292. /**
  39293. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39294. * Returns the HemisphericLight.
  39295. */
  39296. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39297. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39298. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39299. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39300. return this;
  39301. };
  39302. HemisphericLight.prototype._getWorldMatrix = function () {
  39303. if (!this._worldMatrix) {
  39304. this._worldMatrix = BABYLON.Matrix.Identity();
  39305. }
  39306. return this._worldMatrix;
  39307. };
  39308. /**
  39309. * Returns the integer 3.
  39310. */
  39311. HemisphericLight.prototype.getTypeID = function () {
  39312. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39313. };
  39314. __decorate([
  39315. BABYLON.serializeAsColor3()
  39316. ], HemisphericLight.prototype, "groundColor", void 0);
  39317. __decorate([
  39318. BABYLON.serializeAsVector3()
  39319. ], HemisphericLight.prototype, "direction", void 0);
  39320. return HemisphericLight;
  39321. }(BABYLON.Light));
  39322. BABYLON.HemisphericLight = HemisphericLight;
  39323. })(BABYLON || (BABYLON = {}));
  39324. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39325. var BABYLON;
  39326. (function (BABYLON) {
  39327. var ShadowLight = /** @class */ (function (_super) {
  39328. __extends(ShadowLight, _super);
  39329. function ShadowLight() {
  39330. var _this = _super !== null && _super.apply(this, arguments) || this;
  39331. _this._needProjectionMatrixCompute = true;
  39332. return _this;
  39333. }
  39334. Object.defineProperty(ShadowLight.prototype, "direction", {
  39335. get: function () {
  39336. return this._direction;
  39337. },
  39338. set: function (value) {
  39339. this._direction = value;
  39340. },
  39341. enumerable: true,
  39342. configurable: true
  39343. });
  39344. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39345. get: function () {
  39346. return this._shadowMinZ;
  39347. },
  39348. set: function (value) {
  39349. this._shadowMinZ = value;
  39350. this.forceProjectionMatrixCompute();
  39351. },
  39352. enumerable: true,
  39353. configurable: true
  39354. });
  39355. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39356. get: function () {
  39357. return this._shadowMaxZ;
  39358. },
  39359. set: function (value) {
  39360. this._shadowMaxZ = value;
  39361. this.forceProjectionMatrixCompute();
  39362. },
  39363. enumerable: true,
  39364. configurable: true
  39365. });
  39366. /**
  39367. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39368. */
  39369. ShadowLight.prototype.computeTransformedInformation = function () {
  39370. if (this.parent && this.parent.getWorldMatrix) {
  39371. if (!this.transformedPosition) {
  39372. this.transformedPosition = BABYLON.Vector3.Zero();
  39373. }
  39374. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39375. // In case the direction is present.
  39376. if (this.direction) {
  39377. if (!this.transformedDirection) {
  39378. this.transformedDirection = BABYLON.Vector3.Zero();
  39379. }
  39380. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39381. }
  39382. return true;
  39383. }
  39384. return false;
  39385. };
  39386. /**
  39387. * Return the depth scale used for the shadow map.
  39388. */
  39389. ShadowLight.prototype.getDepthScale = function () {
  39390. return 50.0;
  39391. };
  39392. /**
  39393. * Returns the light direction (Vector3) for any passed face index.
  39394. */
  39395. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39396. return this.transformedDirection ? this.transformedDirection : this.direction;
  39397. };
  39398. /**
  39399. * Returns the DirectionalLight absolute position in the World.
  39400. */
  39401. ShadowLight.prototype.getAbsolutePosition = function () {
  39402. return this.transformedPosition ? this.transformedPosition : this.position;
  39403. };
  39404. /**
  39405. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39406. * Returns the updated DirectionalLight direction (Vector3).
  39407. */
  39408. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39409. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39410. return this.direction;
  39411. };
  39412. /**
  39413. * Returns the light rotation (Vector3).
  39414. */
  39415. ShadowLight.prototype.getRotation = function () {
  39416. this.direction.normalize();
  39417. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39418. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39419. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39420. };
  39421. /**
  39422. * Boolean : false by default.
  39423. */
  39424. ShadowLight.prototype.needCube = function () {
  39425. return false;
  39426. };
  39427. /**
  39428. * Specifies wether or not the projection matrix should be recomputed this frame.
  39429. */
  39430. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39431. return this._needProjectionMatrixCompute;
  39432. };
  39433. /**
  39434. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39435. */
  39436. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39437. this._needProjectionMatrixCompute = true;
  39438. };
  39439. /**
  39440. * Get the world matrix of the sahdow lights.
  39441. */
  39442. ShadowLight.prototype._getWorldMatrix = function () {
  39443. if (!this._worldMatrix) {
  39444. this._worldMatrix = BABYLON.Matrix.Identity();
  39445. }
  39446. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39447. return this._worldMatrix;
  39448. };
  39449. /**
  39450. * Gets the minZ used for shadow according to both the scene and the light.
  39451. * @param activeCamera
  39452. */
  39453. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39454. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39455. };
  39456. /**
  39457. * Gets the maxZ used for shadow according to both the scene and the light.
  39458. * @param activeCamera
  39459. */
  39460. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39461. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39462. };
  39463. /**
  39464. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39465. * Returns the light.
  39466. */
  39467. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39468. if (this.customProjectionMatrixBuilder) {
  39469. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39470. }
  39471. else {
  39472. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39473. }
  39474. return this;
  39475. };
  39476. __decorate([
  39477. BABYLON.serializeAsVector3()
  39478. ], ShadowLight.prototype, "position", void 0);
  39479. __decorate([
  39480. BABYLON.serializeAsVector3()
  39481. ], ShadowLight.prototype, "direction", null);
  39482. __decorate([
  39483. BABYLON.serialize()
  39484. ], ShadowLight.prototype, "shadowMinZ", null);
  39485. __decorate([
  39486. BABYLON.serialize()
  39487. ], ShadowLight.prototype, "shadowMaxZ", null);
  39488. return ShadowLight;
  39489. }(BABYLON.Light));
  39490. BABYLON.ShadowLight = ShadowLight;
  39491. })(BABYLON || (BABYLON = {}));
  39492. //# sourceMappingURL=babylon.shadowLight.js.map
  39493. var BABYLON;
  39494. (function (BABYLON) {
  39495. var PointLight = /** @class */ (function (_super) {
  39496. __extends(PointLight, _super);
  39497. /**
  39498. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39499. * A PointLight emits the light in every direction.
  39500. * It can cast shadows.
  39501. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39502. * ```javascript
  39503. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39504. * ```
  39505. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39506. */
  39507. function PointLight(name, position, scene) {
  39508. var _this = _super.call(this, name, scene) || this;
  39509. _this._shadowAngle = Math.PI / 2;
  39510. _this.position = position;
  39511. return _this;
  39512. }
  39513. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39514. /**
  39515. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39516. * This specifies what angle the shadow will use to be created.
  39517. *
  39518. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39519. */
  39520. get: function () {
  39521. return this._shadowAngle;
  39522. },
  39523. /**
  39524. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39525. * This specifies what angle the shadow will use to be created.
  39526. *
  39527. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39528. */
  39529. set: function (value) {
  39530. this._shadowAngle = value;
  39531. this.forceProjectionMatrixCompute();
  39532. },
  39533. enumerable: true,
  39534. configurable: true
  39535. });
  39536. Object.defineProperty(PointLight.prototype, "direction", {
  39537. get: function () {
  39538. return this._direction;
  39539. },
  39540. /**
  39541. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39542. */
  39543. set: function (value) {
  39544. var previousNeedCube = this.needCube();
  39545. this._direction = value;
  39546. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39547. this._shadowGenerator.recreateShadowMap();
  39548. }
  39549. },
  39550. enumerable: true,
  39551. configurable: true
  39552. });
  39553. /**
  39554. * Returns the string "PointLight"
  39555. */
  39556. PointLight.prototype.getClassName = function () {
  39557. return "PointLight";
  39558. };
  39559. /**
  39560. * Returns the integer 0.
  39561. */
  39562. PointLight.prototype.getTypeID = function () {
  39563. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39564. };
  39565. /**
  39566. * Specifies wether or not the shadowmap should be a cube texture.
  39567. */
  39568. PointLight.prototype.needCube = function () {
  39569. return !this.direction;
  39570. };
  39571. /**
  39572. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39573. */
  39574. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39575. if (this.direction) {
  39576. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39577. }
  39578. else {
  39579. switch (faceIndex) {
  39580. case 0:
  39581. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39582. case 1:
  39583. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39584. case 2:
  39585. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39586. case 3:
  39587. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39588. case 4:
  39589. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39590. case 5:
  39591. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39592. }
  39593. }
  39594. return BABYLON.Vector3.Zero();
  39595. };
  39596. /**
  39597. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39598. * - fov = PI / 2
  39599. * - aspect ratio : 1.0
  39600. * - z-near and far equal to the active camera minZ and maxZ.
  39601. * Returns the PointLight.
  39602. */
  39603. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39604. var activeCamera = this.getScene().activeCamera;
  39605. if (!activeCamera) {
  39606. return;
  39607. }
  39608. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39609. };
  39610. PointLight.prototype._buildUniformLayout = function () {
  39611. this._uniformBuffer.addUniform("vLightData", 4);
  39612. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39613. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39614. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39615. this._uniformBuffer.addUniform("depthValues", 2);
  39616. this._uniformBuffer.create();
  39617. };
  39618. /**
  39619. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39620. * Returns the PointLight.
  39621. */
  39622. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39623. if (this.computeTransformedInformation()) {
  39624. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39625. return this;
  39626. }
  39627. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39628. return this;
  39629. };
  39630. __decorate([
  39631. BABYLON.serialize()
  39632. ], PointLight.prototype, "shadowAngle", null);
  39633. return PointLight;
  39634. }(BABYLON.ShadowLight));
  39635. BABYLON.PointLight = PointLight;
  39636. })(BABYLON || (BABYLON = {}));
  39637. //# sourceMappingURL=babylon.pointLight.js.map
  39638. var BABYLON;
  39639. (function (BABYLON) {
  39640. var DirectionalLight = /** @class */ (function (_super) {
  39641. __extends(DirectionalLight, _super);
  39642. /**
  39643. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39644. * The directional light is emitted from everywhere in the given direction.
  39645. * It can cast shawdows.
  39646. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39647. */
  39648. function DirectionalLight(name, direction, scene) {
  39649. var _this = _super.call(this, name, scene) || this;
  39650. _this._shadowFrustumSize = 0;
  39651. _this._shadowOrthoScale = 0.5;
  39652. _this.autoUpdateExtends = true;
  39653. // Cache
  39654. _this._orthoLeft = Number.MAX_VALUE;
  39655. _this._orthoRight = Number.MIN_VALUE;
  39656. _this._orthoTop = Number.MIN_VALUE;
  39657. _this._orthoBottom = Number.MAX_VALUE;
  39658. _this.position = direction.scale(-1.0);
  39659. _this.direction = direction;
  39660. return _this;
  39661. }
  39662. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39663. /**
  39664. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39665. */
  39666. get: function () {
  39667. return this._shadowFrustumSize;
  39668. },
  39669. /**
  39670. * Specifies a fix frustum size for the shadow generation.
  39671. */
  39672. set: function (value) {
  39673. this._shadowFrustumSize = value;
  39674. this.forceProjectionMatrixCompute();
  39675. },
  39676. enumerable: true,
  39677. configurable: true
  39678. });
  39679. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39680. get: function () {
  39681. return this._shadowOrthoScale;
  39682. },
  39683. set: function (value) {
  39684. this._shadowOrthoScale = value;
  39685. this.forceProjectionMatrixCompute();
  39686. },
  39687. enumerable: true,
  39688. configurable: true
  39689. });
  39690. /**
  39691. * Returns the string "DirectionalLight".
  39692. */
  39693. DirectionalLight.prototype.getClassName = function () {
  39694. return "DirectionalLight";
  39695. };
  39696. /**
  39697. * Returns the integer 1.
  39698. */
  39699. DirectionalLight.prototype.getTypeID = function () {
  39700. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39701. };
  39702. /**
  39703. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39704. * Returns the DirectionalLight Shadow projection matrix.
  39705. */
  39706. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39707. if (this.shadowFrustumSize > 0) {
  39708. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39709. }
  39710. else {
  39711. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39712. }
  39713. };
  39714. /**
  39715. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39716. * Returns the DirectionalLight Shadow projection matrix.
  39717. */
  39718. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39719. var activeCamera = this.getScene().activeCamera;
  39720. if (!activeCamera) {
  39721. return;
  39722. }
  39723. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39724. };
  39725. /**
  39726. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39727. * Returns the DirectionalLight Shadow projection matrix.
  39728. */
  39729. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39730. var activeCamera = this.getScene().activeCamera;
  39731. if (!activeCamera) {
  39732. return;
  39733. }
  39734. // Check extends
  39735. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39736. var tempVector3 = BABYLON.Vector3.Zero();
  39737. this._orthoLeft = Number.MAX_VALUE;
  39738. this._orthoRight = Number.MIN_VALUE;
  39739. this._orthoTop = Number.MIN_VALUE;
  39740. this._orthoBottom = Number.MAX_VALUE;
  39741. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39742. var mesh = renderList[meshIndex];
  39743. if (!mesh) {
  39744. continue;
  39745. }
  39746. var boundingInfo = mesh.getBoundingInfo();
  39747. if (!boundingInfo) {
  39748. continue;
  39749. }
  39750. var boundingBox = boundingInfo.boundingBox;
  39751. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39752. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39753. if (tempVector3.x < this._orthoLeft)
  39754. this._orthoLeft = tempVector3.x;
  39755. if (tempVector3.y < this._orthoBottom)
  39756. this._orthoBottom = tempVector3.y;
  39757. if (tempVector3.x > this._orthoRight)
  39758. this._orthoRight = tempVector3.x;
  39759. if (tempVector3.y > this._orthoTop)
  39760. this._orthoTop = tempVector3.y;
  39761. }
  39762. }
  39763. }
  39764. var xOffset = this._orthoRight - this._orthoLeft;
  39765. var yOffset = this._orthoTop - this._orthoBottom;
  39766. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39767. };
  39768. DirectionalLight.prototype._buildUniformLayout = function () {
  39769. this._uniformBuffer.addUniform("vLightData", 4);
  39770. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39771. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39772. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39773. this._uniformBuffer.addUniform("depthValues", 2);
  39774. this._uniformBuffer.create();
  39775. };
  39776. /**
  39777. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39778. * Returns the DirectionalLight.
  39779. */
  39780. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39781. if (this.computeTransformedInformation()) {
  39782. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39783. return this;
  39784. }
  39785. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39786. return this;
  39787. };
  39788. /**
  39789. * Gets the minZ used for shadow according to both the scene and the light.
  39790. *
  39791. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39792. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39793. * @param activeCamera
  39794. */
  39795. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39796. return 1;
  39797. };
  39798. /**
  39799. * Gets the maxZ used for shadow according to both the scene and the light.
  39800. *
  39801. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39802. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39803. * @param activeCamera
  39804. */
  39805. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39806. return 1;
  39807. };
  39808. __decorate([
  39809. BABYLON.serialize()
  39810. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39811. __decorate([
  39812. BABYLON.serialize()
  39813. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39814. __decorate([
  39815. BABYLON.serialize()
  39816. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39817. return DirectionalLight;
  39818. }(BABYLON.ShadowLight));
  39819. BABYLON.DirectionalLight = DirectionalLight;
  39820. })(BABYLON || (BABYLON = {}));
  39821. //# sourceMappingURL=babylon.directionalLight.js.map
  39822. var BABYLON;
  39823. (function (BABYLON) {
  39824. var SpotLight = /** @class */ (function (_super) {
  39825. __extends(SpotLight, _super);
  39826. /**
  39827. * Creates a SpotLight object in the scene with the passed parameters :
  39828. * - `position` (Vector3) is the initial SpotLight position,
  39829. * - `direction` (Vector3) is the initial SpotLight direction,
  39830. * - `angle` (float, in radians) is the spot light cone angle,
  39831. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39832. * A spot light is a simply light oriented cone.
  39833. * It can cast shadows.
  39834. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39835. */
  39836. function SpotLight(name, position, direction, angle, exponent, scene) {
  39837. var _this = _super.call(this, name, scene) || this;
  39838. _this.position = position;
  39839. _this.direction = direction;
  39840. _this.angle = angle;
  39841. _this.exponent = exponent;
  39842. return _this;
  39843. }
  39844. Object.defineProperty(SpotLight.prototype, "angle", {
  39845. get: function () {
  39846. return this._angle;
  39847. },
  39848. set: function (value) {
  39849. this._angle = value;
  39850. this.forceProjectionMatrixCompute();
  39851. },
  39852. enumerable: true,
  39853. configurable: true
  39854. });
  39855. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39856. get: function () {
  39857. return this._shadowAngleScale;
  39858. },
  39859. /**
  39860. * Allows scaling the angle of the light for shadow generation only.
  39861. */
  39862. set: function (value) {
  39863. this._shadowAngleScale = value;
  39864. this.forceProjectionMatrixCompute();
  39865. },
  39866. enumerable: true,
  39867. configurable: true
  39868. });
  39869. /**
  39870. * Returns the string "SpotLight".
  39871. */
  39872. SpotLight.prototype.getClassName = function () {
  39873. return "SpotLight";
  39874. };
  39875. /**
  39876. * Returns the integer 2.
  39877. */
  39878. SpotLight.prototype.getTypeID = function () {
  39879. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39880. };
  39881. /**
  39882. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  39883. * Returns the SpotLight.
  39884. */
  39885. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39886. var activeCamera = this.getScene().activeCamera;
  39887. if (!activeCamera) {
  39888. return;
  39889. }
  39890. this._shadowAngleScale = this._shadowAngleScale || 1;
  39891. var angle = this._shadowAngleScale * this._angle;
  39892. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39893. };
  39894. SpotLight.prototype._buildUniformLayout = function () {
  39895. this._uniformBuffer.addUniform("vLightData", 4);
  39896. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39897. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39898. this._uniformBuffer.addUniform("vLightDirection", 3);
  39899. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39900. this._uniformBuffer.addUniform("depthValues", 2);
  39901. this._uniformBuffer.create();
  39902. };
  39903. /**
  39904. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39905. * Return the SpotLight.
  39906. */
  39907. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39908. var normalizeDirection;
  39909. if (this.computeTransformedInformation()) {
  39910. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39911. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39912. }
  39913. else {
  39914. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39915. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39916. }
  39917. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39918. return this;
  39919. };
  39920. __decorate([
  39921. BABYLON.serialize()
  39922. ], SpotLight.prototype, "angle", null);
  39923. __decorate([
  39924. BABYLON.serialize()
  39925. /**
  39926. * Allows scaling the angle of the light for shadow generation only.
  39927. */
  39928. ], SpotLight.prototype, "shadowAngleScale", null);
  39929. __decorate([
  39930. BABYLON.serialize()
  39931. ], SpotLight.prototype, "exponent", void 0);
  39932. return SpotLight;
  39933. }(BABYLON.ShadowLight));
  39934. BABYLON.SpotLight = SpotLight;
  39935. })(BABYLON || (BABYLON = {}));
  39936. //# sourceMappingURL=babylon.spotLight.js.map
  39937. var BABYLON;
  39938. (function (BABYLON) {
  39939. var AnimationRange = /** @class */ (function () {
  39940. function AnimationRange(name, from, to) {
  39941. this.name = name;
  39942. this.from = from;
  39943. this.to = to;
  39944. }
  39945. AnimationRange.prototype.clone = function () {
  39946. return new AnimationRange(this.name, this.from, this.to);
  39947. };
  39948. return AnimationRange;
  39949. }());
  39950. BABYLON.AnimationRange = AnimationRange;
  39951. /**
  39952. * Composed of a frame, and an action function
  39953. */
  39954. var AnimationEvent = /** @class */ (function () {
  39955. function AnimationEvent(frame, action, onlyOnce) {
  39956. this.frame = frame;
  39957. this.action = action;
  39958. this.onlyOnce = onlyOnce;
  39959. this.isDone = false;
  39960. }
  39961. return AnimationEvent;
  39962. }());
  39963. BABYLON.AnimationEvent = AnimationEvent;
  39964. var PathCursor = /** @class */ (function () {
  39965. function PathCursor(path) {
  39966. this.path = path;
  39967. this._onchange = new Array();
  39968. this.value = 0;
  39969. this.animations = new Array();
  39970. }
  39971. PathCursor.prototype.getPoint = function () {
  39972. var point = this.path.getPointAtLengthPosition(this.value);
  39973. return new BABYLON.Vector3(point.x, 0, point.y);
  39974. };
  39975. PathCursor.prototype.moveAhead = function (step) {
  39976. if (step === void 0) { step = 0.002; }
  39977. this.move(step);
  39978. return this;
  39979. };
  39980. PathCursor.prototype.moveBack = function (step) {
  39981. if (step === void 0) { step = 0.002; }
  39982. this.move(-step);
  39983. return this;
  39984. };
  39985. PathCursor.prototype.move = function (step) {
  39986. if (Math.abs(step) > 1) {
  39987. throw "step size should be less than 1.";
  39988. }
  39989. this.value += step;
  39990. this.ensureLimits();
  39991. this.raiseOnChange();
  39992. return this;
  39993. };
  39994. PathCursor.prototype.ensureLimits = function () {
  39995. while (this.value > 1) {
  39996. this.value -= 1;
  39997. }
  39998. while (this.value < 0) {
  39999. this.value += 1;
  40000. }
  40001. return this;
  40002. };
  40003. // used by animation engine
  40004. PathCursor.prototype.raiseOnChange = function () {
  40005. var _this = this;
  40006. this._onchange.forEach(function (f) { return f(_this); });
  40007. return this;
  40008. };
  40009. PathCursor.prototype.onchange = function (f) {
  40010. this._onchange.push(f);
  40011. return this;
  40012. };
  40013. return PathCursor;
  40014. }());
  40015. BABYLON.PathCursor = PathCursor;
  40016. var Animation = /** @class */ (function () {
  40017. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  40018. this.name = name;
  40019. this.targetProperty = targetProperty;
  40020. this.framePerSecond = framePerSecond;
  40021. this.dataType = dataType;
  40022. this.loopMode = loopMode;
  40023. this.enableBlending = enableBlending;
  40024. this._runtimeAnimations = new Array();
  40025. // The set of event that will be linked to this animation
  40026. this._events = new Array();
  40027. this.blendingSpeed = 0.01;
  40028. this._ranges = {};
  40029. this.targetPropertyPath = targetProperty.split(".");
  40030. this.dataType = dataType;
  40031. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40032. }
  40033. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40034. var dataType = undefined;
  40035. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40036. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40037. }
  40038. else if (from instanceof BABYLON.Quaternion) {
  40039. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40040. }
  40041. else if (from instanceof BABYLON.Vector3) {
  40042. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40043. }
  40044. else if (from instanceof BABYLON.Vector2) {
  40045. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40046. }
  40047. else if (from instanceof BABYLON.Color3) {
  40048. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40049. }
  40050. else if (from instanceof BABYLON.Size) {
  40051. dataType = Animation.ANIMATIONTYPE_SIZE;
  40052. }
  40053. if (dataType == undefined) {
  40054. return null;
  40055. }
  40056. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40057. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40058. animation.setKeys(keys);
  40059. if (easingFunction !== undefined) {
  40060. animation.setEasingFunction(easingFunction);
  40061. }
  40062. return animation;
  40063. };
  40064. /**
  40065. * Sets up an animation.
  40066. * @param property the property to animate
  40067. * @param animationType the animation type to apply
  40068. * @param easingFunction the easing function used in the animation
  40069. * @returns The created animation
  40070. */
  40071. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40072. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40073. animation.setEasingFunction(easingFunction);
  40074. return animation;
  40075. };
  40076. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40077. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40078. if (!animation) {
  40079. return null;
  40080. }
  40081. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40082. };
  40083. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40084. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40085. if (!animation) {
  40086. return null;
  40087. }
  40088. node.animations.push(animation);
  40089. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40090. };
  40091. /**
  40092. * Transition property of the Camera to the target Value.
  40093. * @param property The property to transition
  40094. * @param targetValue The target Value of the property
  40095. * @param host The object where the property to animate belongs
  40096. * @param scene Scene used to run the animation
  40097. * @param frameRate Framerate (in frame/s) to use
  40098. * @param transition The transition type we want to use
  40099. * @param duration The duration of the animation, in milliseconds
  40100. * @param onAnimationEnd Call back trigger at the end of the animation.
  40101. */
  40102. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40103. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40104. if (duration <= 0) {
  40105. host[property] = targetValue;
  40106. if (onAnimationEnd) {
  40107. onAnimationEnd();
  40108. }
  40109. return null;
  40110. }
  40111. var endFrame = frameRate * (duration / 1000);
  40112. transition.setKeys([{
  40113. frame: 0,
  40114. value: host[property].clone ? host[property].clone() : host[property]
  40115. },
  40116. {
  40117. frame: endFrame,
  40118. value: targetValue
  40119. }]);
  40120. if (!host.animations) {
  40121. host.animations = [];
  40122. }
  40123. host.animations.push(transition);
  40124. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40125. animation.onAnimationEnd = onAnimationEnd;
  40126. return animation;
  40127. };
  40128. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40129. /**
  40130. * Return the array of runtime animations currently using this animation
  40131. */
  40132. get: function () {
  40133. return this._runtimeAnimations;
  40134. },
  40135. enumerable: true,
  40136. configurable: true
  40137. });
  40138. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40139. get: function () {
  40140. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40141. var runtimeAnimation = _a[_i];
  40142. if (!runtimeAnimation.isStopped) {
  40143. return true;
  40144. }
  40145. }
  40146. return false;
  40147. },
  40148. enumerable: true,
  40149. configurable: true
  40150. });
  40151. // Methods
  40152. /**
  40153. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40154. */
  40155. Animation.prototype.toString = function (fullDetails) {
  40156. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40157. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40158. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40159. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40160. if (fullDetails) {
  40161. ret += ", Ranges: {";
  40162. var first = true;
  40163. for (var name in this._ranges) {
  40164. if (first) {
  40165. ret += ", ";
  40166. first = false;
  40167. }
  40168. ret += name;
  40169. }
  40170. ret += "}";
  40171. }
  40172. return ret;
  40173. };
  40174. /**
  40175. * Add an event to this animation.
  40176. */
  40177. Animation.prototype.addEvent = function (event) {
  40178. this._events.push(event);
  40179. };
  40180. /**
  40181. * Remove all events found at the given frame
  40182. * @param frame
  40183. */
  40184. Animation.prototype.removeEvents = function (frame) {
  40185. for (var index = 0; index < this._events.length; index++) {
  40186. if (this._events[index].frame === frame) {
  40187. this._events.splice(index, 1);
  40188. index--;
  40189. }
  40190. }
  40191. };
  40192. Animation.prototype.getEvents = function () {
  40193. return this._events;
  40194. };
  40195. Animation.prototype.createRange = function (name, from, to) {
  40196. // check name not already in use; could happen for bones after serialized
  40197. if (!this._ranges[name]) {
  40198. this._ranges[name] = new AnimationRange(name, from, to);
  40199. }
  40200. };
  40201. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40202. if (deleteFrames === void 0) { deleteFrames = true; }
  40203. var range = this._ranges[name];
  40204. if (!range) {
  40205. return;
  40206. }
  40207. if (deleteFrames) {
  40208. var from = range.from;
  40209. var to = range.to;
  40210. // this loop MUST go high to low for multiple splices to work
  40211. for (var key = this._keys.length - 1; key >= 0; key--) {
  40212. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40213. this._keys.splice(key, 1);
  40214. }
  40215. }
  40216. }
  40217. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40218. };
  40219. Animation.prototype.getRange = function (name) {
  40220. return this._ranges[name];
  40221. };
  40222. Animation.prototype.getKeys = function () {
  40223. return this._keys;
  40224. };
  40225. Animation.prototype.getHighestFrame = function () {
  40226. var ret = 0;
  40227. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40228. if (ret < this._keys[key].frame) {
  40229. ret = this._keys[key].frame;
  40230. }
  40231. }
  40232. return ret;
  40233. };
  40234. Animation.prototype.getEasingFunction = function () {
  40235. return this._easingFunction;
  40236. };
  40237. Animation.prototype.setEasingFunction = function (easingFunction) {
  40238. this._easingFunction = easingFunction;
  40239. };
  40240. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40241. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40242. };
  40243. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40244. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40245. };
  40246. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40247. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40248. };
  40249. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40250. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40251. };
  40252. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40253. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40254. };
  40255. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40256. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40257. };
  40258. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40259. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40260. };
  40261. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40262. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40263. };
  40264. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40265. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40266. };
  40267. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40268. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40269. };
  40270. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40271. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40272. };
  40273. Animation.prototype.clone = function () {
  40274. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40275. clone.enableBlending = this.enableBlending;
  40276. clone.blendingSpeed = this.blendingSpeed;
  40277. if (this._keys) {
  40278. clone.setKeys(this._keys);
  40279. }
  40280. if (this._ranges) {
  40281. clone._ranges = {};
  40282. for (var name in this._ranges) {
  40283. var range = this._ranges[name];
  40284. if (!range) {
  40285. continue;
  40286. }
  40287. clone._ranges[name] = range.clone();
  40288. }
  40289. }
  40290. return clone;
  40291. };
  40292. Animation.prototype.setKeys = function (values) {
  40293. this._keys = values.slice(0);
  40294. };
  40295. Animation.prototype.serialize = function () {
  40296. var serializationObject = {};
  40297. serializationObject.name = this.name;
  40298. serializationObject.property = this.targetProperty;
  40299. serializationObject.framePerSecond = this.framePerSecond;
  40300. serializationObject.dataType = this.dataType;
  40301. serializationObject.loopBehavior = this.loopMode;
  40302. serializationObject.enableBlending = this.enableBlending;
  40303. serializationObject.blendingSpeed = this.blendingSpeed;
  40304. var dataType = this.dataType;
  40305. serializationObject.keys = [];
  40306. var keys = this.getKeys();
  40307. for (var index = 0; index < keys.length; index++) {
  40308. var animationKey = keys[index];
  40309. var key = {};
  40310. key.frame = animationKey.frame;
  40311. switch (dataType) {
  40312. case Animation.ANIMATIONTYPE_FLOAT:
  40313. key.values = [animationKey.value];
  40314. break;
  40315. case Animation.ANIMATIONTYPE_QUATERNION:
  40316. case Animation.ANIMATIONTYPE_MATRIX:
  40317. case Animation.ANIMATIONTYPE_VECTOR3:
  40318. case Animation.ANIMATIONTYPE_COLOR3:
  40319. key.values = animationKey.value.asArray();
  40320. break;
  40321. }
  40322. serializationObject.keys.push(key);
  40323. }
  40324. serializationObject.ranges = [];
  40325. for (var name in this._ranges) {
  40326. var source = this._ranges[name];
  40327. if (!source) {
  40328. continue;
  40329. }
  40330. var range = {};
  40331. range.name = name;
  40332. range.from = source.from;
  40333. range.to = source.to;
  40334. serializationObject.ranges.push(range);
  40335. }
  40336. return serializationObject;
  40337. };
  40338. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40339. get: function () {
  40340. return Animation._ANIMATIONTYPE_FLOAT;
  40341. },
  40342. enumerable: true,
  40343. configurable: true
  40344. });
  40345. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40346. get: function () {
  40347. return Animation._ANIMATIONTYPE_VECTOR3;
  40348. },
  40349. enumerable: true,
  40350. configurable: true
  40351. });
  40352. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40353. get: function () {
  40354. return Animation._ANIMATIONTYPE_VECTOR2;
  40355. },
  40356. enumerable: true,
  40357. configurable: true
  40358. });
  40359. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40360. get: function () {
  40361. return Animation._ANIMATIONTYPE_SIZE;
  40362. },
  40363. enumerable: true,
  40364. configurable: true
  40365. });
  40366. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40367. get: function () {
  40368. return Animation._ANIMATIONTYPE_QUATERNION;
  40369. },
  40370. enumerable: true,
  40371. configurable: true
  40372. });
  40373. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40374. get: function () {
  40375. return Animation._ANIMATIONTYPE_MATRIX;
  40376. },
  40377. enumerable: true,
  40378. configurable: true
  40379. });
  40380. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40381. get: function () {
  40382. return Animation._ANIMATIONTYPE_COLOR3;
  40383. },
  40384. enumerable: true,
  40385. configurable: true
  40386. });
  40387. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40388. get: function () {
  40389. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40390. },
  40391. enumerable: true,
  40392. configurable: true
  40393. });
  40394. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40395. get: function () {
  40396. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40397. },
  40398. enumerable: true,
  40399. configurable: true
  40400. });
  40401. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40402. get: function () {
  40403. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40404. },
  40405. enumerable: true,
  40406. configurable: true
  40407. });
  40408. Animation.Parse = function (parsedAnimation) {
  40409. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40410. var dataType = parsedAnimation.dataType;
  40411. var keys = [];
  40412. var data;
  40413. var index;
  40414. if (parsedAnimation.enableBlending) {
  40415. animation.enableBlending = parsedAnimation.enableBlending;
  40416. }
  40417. if (parsedAnimation.blendingSpeed) {
  40418. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40419. }
  40420. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40421. var key = parsedAnimation.keys[index];
  40422. var inTangent;
  40423. var outTangent;
  40424. switch (dataType) {
  40425. case Animation.ANIMATIONTYPE_FLOAT:
  40426. data = key.values[0];
  40427. if (key.values.length >= 1) {
  40428. inTangent = key.values[1];
  40429. }
  40430. if (key.values.length >= 2) {
  40431. outTangent = key.values[2];
  40432. }
  40433. break;
  40434. case Animation.ANIMATIONTYPE_QUATERNION:
  40435. data = BABYLON.Quaternion.FromArray(key.values);
  40436. if (key.values.length >= 8) {
  40437. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40438. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40439. inTangent = _inTangent;
  40440. }
  40441. }
  40442. if (key.values.length >= 12) {
  40443. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40444. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40445. outTangent = _outTangent;
  40446. }
  40447. }
  40448. break;
  40449. case Animation.ANIMATIONTYPE_MATRIX:
  40450. data = BABYLON.Matrix.FromArray(key.values);
  40451. break;
  40452. case Animation.ANIMATIONTYPE_COLOR3:
  40453. data = BABYLON.Color3.FromArray(key.values);
  40454. break;
  40455. case Animation.ANIMATIONTYPE_VECTOR3:
  40456. default:
  40457. data = BABYLON.Vector3.FromArray(key.values);
  40458. break;
  40459. }
  40460. var keyData = {};
  40461. keyData.frame = key.frame;
  40462. keyData.value = data;
  40463. if (inTangent != undefined) {
  40464. keyData.inTangent = inTangent;
  40465. }
  40466. if (outTangent != undefined) {
  40467. keyData.outTangent = outTangent;
  40468. }
  40469. keys.push(keyData);
  40470. }
  40471. animation.setKeys(keys);
  40472. if (parsedAnimation.ranges) {
  40473. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40474. data = parsedAnimation.ranges[index];
  40475. animation.createRange(data.name, data.from, data.to);
  40476. }
  40477. }
  40478. return animation;
  40479. };
  40480. Animation.AppendSerializedAnimations = function (source, destination) {
  40481. if (source.animations) {
  40482. destination.animations = [];
  40483. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40484. var animation = source.animations[animationIndex];
  40485. destination.animations.push(animation.serialize());
  40486. }
  40487. }
  40488. };
  40489. Animation.AllowMatricesInterpolation = false;
  40490. // Statics
  40491. Animation._ANIMATIONTYPE_FLOAT = 0;
  40492. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40493. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40494. Animation._ANIMATIONTYPE_MATRIX = 3;
  40495. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40496. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40497. Animation._ANIMATIONTYPE_SIZE = 6;
  40498. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40499. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40500. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40501. return Animation;
  40502. }());
  40503. BABYLON.Animation = Animation;
  40504. })(BABYLON || (BABYLON = {}));
  40505. //# sourceMappingURL=babylon.animation.js.map
  40506. var BABYLON;
  40507. (function (BABYLON) {
  40508. var RuntimeAnimation = /** @class */ (function () {
  40509. function RuntimeAnimation(target, animation) {
  40510. this._offsetsCache = {};
  40511. this._highLimitsCache = {};
  40512. this._stopped = false;
  40513. this._blendingFactor = 0;
  40514. this._ratioOffset = 0;
  40515. this._animation = animation;
  40516. this._target = target;
  40517. animation._runtimeAnimations.push(this);
  40518. }
  40519. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40520. get: function () {
  40521. return this._animation;
  40522. },
  40523. enumerable: true,
  40524. configurable: true
  40525. });
  40526. RuntimeAnimation.prototype.reset = function () {
  40527. this._offsetsCache = {};
  40528. this._highLimitsCache = {};
  40529. this.currentFrame = 0;
  40530. this._blendingFactor = 0;
  40531. this._originalBlendValue = null;
  40532. };
  40533. RuntimeAnimation.prototype.isStopped = function () {
  40534. return this._stopped;
  40535. };
  40536. RuntimeAnimation.prototype.dispose = function () {
  40537. var index = this._animation.runtimeAnimations.indexOf(this);
  40538. if (index > -1) {
  40539. this._animation.runtimeAnimations.splice(index, 1);
  40540. }
  40541. };
  40542. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40543. if (typeof value === "function") {
  40544. return value();
  40545. }
  40546. return value;
  40547. };
  40548. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40549. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40550. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40551. }
  40552. this.currentFrame = currentFrame;
  40553. var keys = this._animation.getKeys();
  40554. // Try to get a hash to find the right key
  40555. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  40556. if (keys[startKeyIndex].frame >= currentFrame) {
  40557. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40558. startKeyIndex--;
  40559. }
  40560. }
  40561. for (var key = startKeyIndex; key < keys.length; key++) {
  40562. var endKey = keys[key + 1];
  40563. if (endKey.frame >= currentFrame) {
  40564. var startKey = keys[key];
  40565. var startValue = this._getKeyValue(startKey.value);
  40566. var endValue = this._getKeyValue(endKey.value);
  40567. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40568. var frameDelta = endKey.frame - startKey.frame;
  40569. // gradient : percent of currentFrame between the frame inf and the frame sup
  40570. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40571. // check for easingFunction and correction of gradient
  40572. var easingFunction = this._animation.getEasingFunction();
  40573. if (easingFunction != null) {
  40574. gradient = easingFunction.ease(gradient);
  40575. }
  40576. switch (this._animation.dataType) {
  40577. // Float
  40578. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40579. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40580. switch (loopMode) {
  40581. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40582. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40583. return floatValue;
  40584. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40585. return offsetValue * repeatCount + floatValue;
  40586. }
  40587. break;
  40588. // Quaternion
  40589. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40590. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40591. switch (loopMode) {
  40592. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40593. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40594. return quatValue;
  40595. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40596. return quatValue.add(offsetValue.scale(repeatCount));
  40597. }
  40598. return quatValue;
  40599. // Vector3
  40600. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40601. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40602. switch (loopMode) {
  40603. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40604. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40605. return vec3Value;
  40606. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40607. return vec3Value.add(offsetValue.scale(repeatCount));
  40608. }
  40609. // Vector2
  40610. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40611. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40612. switch (loopMode) {
  40613. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40614. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40615. return vec2Value;
  40616. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40617. return vec2Value.add(offsetValue.scale(repeatCount));
  40618. }
  40619. // Size
  40620. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40621. switch (loopMode) {
  40622. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40623. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40624. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40625. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40626. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40627. }
  40628. // Color3
  40629. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40630. switch (loopMode) {
  40631. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40632. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40633. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40634. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40635. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40636. }
  40637. // Matrix
  40638. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40639. switch (loopMode) {
  40640. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40641. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40642. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40643. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40644. }
  40645. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40646. return startValue;
  40647. }
  40648. default:
  40649. break;
  40650. }
  40651. break;
  40652. }
  40653. }
  40654. return this._getKeyValue(keys[keys.length - 1].value);
  40655. };
  40656. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40657. if (blend === void 0) { blend = false; }
  40658. // Set value
  40659. var path;
  40660. var destination;
  40661. var targetPropertyPath = this._animation.targetPropertyPath;
  40662. if (targetPropertyPath.length > 1) {
  40663. var property = this._target[targetPropertyPath[0]];
  40664. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40665. property = property[targetPropertyPath[index]];
  40666. }
  40667. path = targetPropertyPath[targetPropertyPath.length - 1];
  40668. destination = property;
  40669. }
  40670. else {
  40671. path = targetPropertyPath[0];
  40672. destination = this._target;
  40673. }
  40674. // Blending
  40675. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40676. if (!this._originalBlendValue) {
  40677. if (destination[path].clone) {
  40678. this._originalBlendValue = destination[path].clone();
  40679. }
  40680. else {
  40681. this._originalBlendValue = destination[path];
  40682. }
  40683. }
  40684. if (this._originalBlendValue.prototype) {
  40685. if (this._originalBlendValue.prototype.Lerp) {
  40686. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40687. }
  40688. else {
  40689. destination[path] = currentValue;
  40690. }
  40691. }
  40692. else if (this._originalBlendValue.m) {
  40693. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40694. }
  40695. else {
  40696. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40697. }
  40698. this._blendingFactor += this._animation.blendingSpeed;
  40699. }
  40700. else {
  40701. destination[path] = currentValue;
  40702. }
  40703. if (this._target.markAsDirty) {
  40704. this._target.markAsDirty(this._animation.targetProperty);
  40705. }
  40706. };
  40707. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40708. var keys = this._animation.getKeys();
  40709. if (frame < keys[0].frame) {
  40710. frame = keys[0].frame;
  40711. }
  40712. else if (frame > keys[keys.length - 1].frame) {
  40713. frame = keys[keys.length - 1].frame;
  40714. }
  40715. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40716. this.setValue(currentValue);
  40717. };
  40718. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40719. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40720. this._ratioOffset = this._previousRatio - newRatio;
  40721. };
  40722. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40723. if (blend === void 0) { blend = false; }
  40724. var targetPropertyPath = this._animation.targetPropertyPath;
  40725. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40726. this._stopped = true;
  40727. return false;
  40728. }
  40729. var returnValue = true;
  40730. var keys = this._animation.getKeys();
  40731. // Adding a start key at frame 0 if missing
  40732. if (keys[0].frame !== 0) {
  40733. var newKey = { frame: 0, value: keys[0].value };
  40734. keys.splice(0, 0, newKey);
  40735. }
  40736. // Check limits
  40737. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40738. from = keys[0].frame;
  40739. }
  40740. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40741. to = keys[keys.length - 1].frame;
  40742. }
  40743. //to and from cannot be the same key
  40744. if (from === to) {
  40745. if (from > keys[0].frame) {
  40746. from--;
  40747. }
  40748. else if (to < keys[keys.length - 1].frame) {
  40749. to++;
  40750. }
  40751. }
  40752. // Compute ratio
  40753. var range = to - from;
  40754. var offsetValue;
  40755. // ratio represents the frame delta between from and to
  40756. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40757. var highLimitValue = 0;
  40758. this._previousDelay = delay;
  40759. this._previousRatio = ratio;
  40760. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40761. returnValue = false;
  40762. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40763. }
  40764. else {
  40765. // Get max value if required
  40766. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40767. var keyOffset = to.toString() + from.toString();
  40768. if (!this._offsetsCache[keyOffset]) {
  40769. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40770. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40771. switch (this._animation.dataType) {
  40772. // Float
  40773. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40774. this._offsetsCache[keyOffset] = toValue - fromValue;
  40775. break;
  40776. // Quaternion
  40777. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40778. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40779. break;
  40780. // Vector3
  40781. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40782. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40783. // Vector2
  40784. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40785. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40786. // Size
  40787. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40788. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40789. // Color3
  40790. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40791. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40792. default:
  40793. break;
  40794. }
  40795. this._highLimitsCache[keyOffset] = toValue;
  40796. }
  40797. highLimitValue = this._highLimitsCache[keyOffset];
  40798. offsetValue = this._offsetsCache[keyOffset];
  40799. }
  40800. }
  40801. if (offsetValue === undefined) {
  40802. switch (this._animation.dataType) {
  40803. // Float
  40804. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40805. offsetValue = 0;
  40806. break;
  40807. // Quaternion
  40808. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40809. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40810. break;
  40811. // Vector3
  40812. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40813. offsetValue = BABYLON.Vector3.Zero();
  40814. break;
  40815. // Vector2
  40816. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40817. offsetValue = BABYLON.Vector2.Zero();
  40818. break;
  40819. // Size
  40820. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40821. offsetValue = BABYLON.Size.Zero();
  40822. break;
  40823. // Color3
  40824. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40825. offsetValue = BABYLON.Color3.Black();
  40826. }
  40827. }
  40828. // Compute value
  40829. var repeatCount = (ratio / range) >> 0;
  40830. var currentFrame = returnValue ? from + ratio % range : to;
  40831. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40832. // Set value
  40833. this.setValue(currentValue);
  40834. // Check events
  40835. var events = this._animation.getEvents();
  40836. for (var index = 0; index < events.length; index++) {
  40837. // Make sure current frame has passed event frame and that event frame is within the current range
  40838. // Also, handle both forward and reverse animations
  40839. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40840. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40841. var event = events[index];
  40842. if (!event.isDone) {
  40843. // If event should be done only once, remove it.
  40844. if (event.onlyOnce) {
  40845. events.splice(index, 1);
  40846. index--;
  40847. }
  40848. event.isDone = true;
  40849. event.action();
  40850. } // Don't do anything if the event has already be done.
  40851. }
  40852. else if (events[index].isDone && !events[index].onlyOnce) {
  40853. // reset event, the animation is looping
  40854. events[index].isDone = false;
  40855. }
  40856. }
  40857. if (!returnValue) {
  40858. this._stopped = true;
  40859. }
  40860. return returnValue;
  40861. };
  40862. return RuntimeAnimation;
  40863. }());
  40864. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40865. })(BABYLON || (BABYLON = {}));
  40866. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40867. var BABYLON;
  40868. (function (BABYLON) {
  40869. var Animatable = /** @class */ (function () {
  40870. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40871. if (fromFrame === void 0) { fromFrame = 0; }
  40872. if (toFrame === void 0) { toFrame = 100; }
  40873. if (loopAnimation === void 0) { loopAnimation = false; }
  40874. if (speedRatio === void 0) { speedRatio = 1.0; }
  40875. this.target = target;
  40876. this.fromFrame = fromFrame;
  40877. this.toFrame = toFrame;
  40878. this.loopAnimation = loopAnimation;
  40879. this.onAnimationEnd = onAnimationEnd;
  40880. this._localDelayOffset = null;
  40881. this._pausedDelay = null;
  40882. this._runtimeAnimations = new Array();
  40883. this._paused = false;
  40884. this._speedRatio = 1;
  40885. this.animationStarted = false;
  40886. if (animations) {
  40887. this.appendAnimations(target, animations);
  40888. }
  40889. this._speedRatio = speedRatio;
  40890. this._scene = scene;
  40891. scene._activeAnimatables.push(this);
  40892. }
  40893. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40894. get: function () {
  40895. return this._speedRatio;
  40896. },
  40897. set: function (value) {
  40898. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40899. var animation = this._runtimeAnimations[index];
  40900. animation._prepareForSpeedRatioChange(value);
  40901. }
  40902. this._speedRatio = value;
  40903. },
  40904. enumerable: true,
  40905. configurable: true
  40906. });
  40907. // Methods
  40908. Animatable.prototype.getAnimations = function () {
  40909. return this._runtimeAnimations;
  40910. };
  40911. Animatable.prototype.appendAnimations = function (target, animations) {
  40912. for (var index = 0; index < animations.length; index++) {
  40913. var animation = animations[index];
  40914. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40915. }
  40916. };
  40917. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40918. var runtimeAnimations = this._runtimeAnimations;
  40919. for (var index = 0; index < runtimeAnimations.length; index++) {
  40920. if (runtimeAnimations[index].animation.targetProperty === property) {
  40921. return runtimeAnimations[index].animation;
  40922. }
  40923. }
  40924. return null;
  40925. };
  40926. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40927. var runtimeAnimations = this._runtimeAnimations;
  40928. for (var index = 0; index < runtimeAnimations.length; index++) {
  40929. if (runtimeAnimations[index].animation.targetProperty === property) {
  40930. return runtimeAnimations[index];
  40931. }
  40932. }
  40933. return null;
  40934. };
  40935. Animatable.prototype.reset = function () {
  40936. var runtimeAnimations = this._runtimeAnimations;
  40937. for (var index = 0; index < runtimeAnimations.length; index++) {
  40938. runtimeAnimations[index].reset();
  40939. }
  40940. this._localDelayOffset = null;
  40941. this._pausedDelay = null;
  40942. };
  40943. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40944. var runtimeAnimations = this._runtimeAnimations;
  40945. for (var index = 0; index < runtimeAnimations.length; index++) {
  40946. runtimeAnimations[index].animation.enableBlending = true;
  40947. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40948. }
  40949. };
  40950. Animatable.prototype.disableBlending = function () {
  40951. var runtimeAnimations = this._runtimeAnimations;
  40952. for (var index = 0; index < runtimeAnimations.length; index++) {
  40953. runtimeAnimations[index].animation.enableBlending = false;
  40954. }
  40955. };
  40956. Animatable.prototype.goToFrame = function (frame) {
  40957. var runtimeAnimations = this._runtimeAnimations;
  40958. if (runtimeAnimations[0]) {
  40959. var fps = runtimeAnimations[0].animation.framePerSecond;
  40960. var currentFrame = runtimeAnimations[0].currentFrame;
  40961. var adjustTime = frame - currentFrame;
  40962. var delay = adjustTime * 1000 / fps;
  40963. if (this._localDelayOffset === null) {
  40964. this._localDelayOffset = 0;
  40965. }
  40966. this._localDelayOffset -= delay;
  40967. }
  40968. for (var index = 0; index < runtimeAnimations.length; index++) {
  40969. runtimeAnimations[index].goToFrame(frame);
  40970. }
  40971. };
  40972. Animatable.prototype.pause = function () {
  40973. if (this._paused) {
  40974. return;
  40975. }
  40976. this._paused = true;
  40977. };
  40978. Animatable.prototype.restart = function () {
  40979. this._paused = false;
  40980. };
  40981. Animatable.prototype.stop = function (animationName) {
  40982. if (animationName) {
  40983. var idx = this._scene._activeAnimatables.indexOf(this);
  40984. if (idx > -1) {
  40985. var runtimeAnimations = this._runtimeAnimations;
  40986. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40987. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40988. continue;
  40989. }
  40990. runtimeAnimations[index].dispose();
  40991. runtimeAnimations.splice(index, 1);
  40992. }
  40993. if (runtimeAnimations.length == 0) {
  40994. this._scene._activeAnimatables.splice(idx, 1);
  40995. if (this.onAnimationEnd) {
  40996. this.onAnimationEnd();
  40997. }
  40998. }
  40999. }
  41000. }
  41001. else {
  41002. var index = this._scene._activeAnimatables.indexOf(this);
  41003. if (index > -1) {
  41004. this._scene._activeAnimatables.splice(index, 1);
  41005. var runtimeAnimations = this._runtimeAnimations;
  41006. for (var index = 0; index < runtimeAnimations.length; index++) {
  41007. runtimeAnimations[index].dispose();
  41008. }
  41009. if (this.onAnimationEnd) {
  41010. this.onAnimationEnd();
  41011. }
  41012. }
  41013. }
  41014. };
  41015. Animatable.prototype._animate = function (delay) {
  41016. if (this._paused) {
  41017. this.animationStarted = false;
  41018. if (this._pausedDelay === null) {
  41019. this._pausedDelay = delay;
  41020. }
  41021. return true;
  41022. }
  41023. if (this._localDelayOffset === null) {
  41024. this._localDelayOffset = delay;
  41025. }
  41026. else if (this._pausedDelay !== null) {
  41027. this._localDelayOffset += delay - this._pausedDelay;
  41028. this._pausedDelay = null;
  41029. }
  41030. // Animating
  41031. var running = false;
  41032. var runtimeAnimations = this._runtimeAnimations;
  41033. var index;
  41034. for (index = 0; index < runtimeAnimations.length; index++) {
  41035. var animation = runtimeAnimations[index];
  41036. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41037. running = running || isRunning;
  41038. }
  41039. this.animationStarted = running;
  41040. if (!running) {
  41041. // Remove from active animatables
  41042. index = this._scene._activeAnimatables.indexOf(this);
  41043. this._scene._activeAnimatables.splice(index, 1);
  41044. // Dispose all runtime animations
  41045. for (index = 0; index < runtimeAnimations.length; index++) {
  41046. runtimeAnimations[index].dispose();
  41047. }
  41048. }
  41049. if (!running && this.onAnimationEnd) {
  41050. this.onAnimationEnd();
  41051. this.onAnimationEnd = null;
  41052. }
  41053. return running;
  41054. };
  41055. return Animatable;
  41056. }());
  41057. BABYLON.Animatable = Animatable;
  41058. })(BABYLON || (BABYLON = {}));
  41059. //# sourceMappingURL=babylon.animatable.js.map
  41060. var BABYLON;
  41061. (function (BABYLON) {
  41062. var EasingFunction = /** @class */ (function () {
  41063. function EasingFunction() {
  41064. // Properties
  41065. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41066. }
  41067. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41068. get: function () {
  41069. return EasingFunction._EASINGMODE_EASEIN;
  41070. },
  41071. enumerable: true,
  41072. configurable: true
  41073. });
  41074. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41075. get: function () {
  41076. return EasingFunction._EASINGMODE_EASEOUT;
  41077. },
  41078. enumerable: true,
  41079. configurable: true
  41080. });
  41081. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41082. get: function () {
  41083. return EasingFunction._EASINGMODE_EASEINOUT;
  41084. },
  41085. enumerable: true,
  41086. configurable: true
  41087. });
  41088. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41089. var n = Math.min(Math.max(easingMode, 0), 2);
  41090. this._easingMode = n;
  41091. };
  41092. EasingFunction.prototype.getEasingMode = function () {
  41093. return this._easingMode;
  41094. };
  41095. EasingFunction.prototype.easeInCore = function (gradient) {
  41096. throw new Error('You must implement this method');
  41097. };
  41098. EasingFunction.prototype.ease = function (gradient) {
  41099. switch (this._easingMode) {
  41100. case EasingFunction.EASINGMODE_EASEIN:
  41101. return this.easeInCore(gradient);
  41102. case EasingFunction.EASINGMODE_EASEOUT:
  41103. return (1 - this.easeInCore(1 - gradient));
  41104. }
  41105. if (gradient >= 0.5) {
  41106. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41107. }
  41108. return (this.easeInCore(gradient * 2) * 0.5);
  41109. };
  41110. //Statics
  41111. EasingFunction._EASINGMODE_EASEIN = 0;
  41112. EasingFunction._EASINGMODE_EASEOUT = 1;
  41113. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41114. return EasingFunction;
  41115. }());
  41116. BABYLON.EasingFunction = EasingFunction;
  41117. var CircleEase = /** @class */ (function (_super) {
  41118. __extends(CircleEase, _super);
  41119. function CircleEase() {
  41120. return _super !== null && _super.apply(this, arguments) || this;
  41121. }
  41122. CircleEase.prototype.easeInCore = function (gradient) {
  41123. gradient = Math.max(0, Math.min(1, gradient));
  41124. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41125. };
  41126. return CircleEase;
  41127. }(EasingFunction));
  41128. BABYLON.CircleEase = CircleEase;
  41129. var BackEase = /** @class */ (function (_super) {
  41130. __extends(BackEase, _super);
  41131. function BackEase(amplitude) {
  41132. if (amplitude === void 0) { amplitude = 1; }
  41133. var _this = _super.call(this) || this;
  41134. _this.amplitude = amplitude;
  41135. return _this;
  41136. }
  41137. BackEase.prototype.easeInCore = function (gradient) {
  41138. var num = Math.max(0, this.amplitude);
  41139. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41140. };
  41141. return BackEase;
  41142. }(EasingFunction));
  41143. BABYLON.BackEase = BackEase;
  41144. var BounceEase = /** @class */ (function (_super) {
  41145. __extends(BounceEase, _super);
  41146. function BounceEase(bounces, bounciness) {
  41147. if (bounces === void 0) { bounces = 3; }
  41148. if (bounciness === void 0) { bounciness = 2; }
  41149. var _this = _super.call(this) || this;
  41150. _this.bounces = bounces;
  41151. _this.bounciness = bounciness;
  41152. return _this;
  41153. }
  41154. BounceEase.prototype.easeInCore = function (gradient) {
  41155. var y = Math.max(0.0, this.bounces);
  41156. var bounciness = this.bounciness;
  41157. if (bounciness <= 1.0) {
  41158. bounciness = 1.001;
  41159. }
  41160. var num9 = Math.pow(bounciness, y);
  41161. var num5 = 1.0 - bounciness;
  41162. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41163. var num15 = gradient * num4;
  41164. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41165. var num3 = Math.floor(num65);
  41166. var num13 = num3 + 1.0;
  41167. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41168. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41169. var num7 = (num8 + num12) * 0.5;
  41170. var num6 = gradient - num7;
  41171. var num2 = num7 - num8;
  41172. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41173. };
  41174. return BounceEase;
  41175. }(EasingFunction));
  41176. BABYLON.BounceEase = BounceEase;
  41177. var CubicEase = /** @class */ (function (_super) {
  41178. __extends(CubicEase, _super);
  41179. function CubicEase() {
  41180. return _super !== null && _super.apply(this, arguments) || this;
  41181. }
  41182. CubicEase.prototype.easeInCore = function (gradient) {
  41183. return (gradient * gradient * gradient);
  41184. };
  41185. return CubicEase;
  41186. }(EasingFunction));
  41187. BABYLON.CubicEase = CubicEase;
  41188. var ElasticEase = /** @class */ (function (_super) {
  41189. __extends(ElasticEase, _super);
  41190. function ElasticEase(oscillations, springiness) {
  41191. if (oscillations === void 0) { oscillations = 3; }
  41192. if (springiness === void 0) { springiness = 3; }
  41193. var _this = _super.call(this) || this;
  41194. _this.oscillations = oscillations;
  41195. _this.springiness = springiness;
  41196. return _this;
  41197. }
  41198. ElasticEase.prototype.easeInCore = function (gradient) {
  41199. var num2;
  41200. var num3 = Math.max(0.0, this.oscillations);
  41201. var num = Math.max(0.0, this.springiness);
  41202. if (num == 0) {
  41203. num2 = gradient;
  41204. }
  41205. else {
  41206. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41207. }
  41208. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41209. };
  41210. return ElasticEase;
  41211. }(EasingFunction));
  41212. BABYLON.ElasticEase = ElasticEase;
  41213. var ExponentialEase = /** @class */ (function (_super) {
  41214. __extends(ExponentialEase, _super);
  41215. function ExponentialEase(exponent) {
  41216. if (exponent === void 0) { exponent = 2; }
  41217. var _this = _super.call(this) || this;
  41218. _this.exponent = exponent;
  41219. return _this;
  41220. }
  41221. ExponentialEase.prototype.easeInCore = function (gradient) {
  41222. if (this.exponent <= 0) {
  41223. return gradient;
  41224. }
  41225. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41226. };
  41227. return ExponentialEase;
  41228. }(EasingFunction));
  41229. BABYLON.ExponentialEase = ExponentialEase;
  41230. var PowerEase = /** @class */ (function (_super) {
  41231. __extends(PowerEase, _super);
  41232. function PowerEase(power) {
  41233. if (power === void 0) { power = 2; }
  41234. var _this = _super.call(this) || this;
  41235. _this.power = power;
  41236. return _this;
  41237. }
  41238. PowerEase.prototype.easeInCore = function (gradient) {
  41239. var y = Math.max(0.0, this.power);
  41240. return Math.pow(gradient, y);
  41241. };
  41242. return PowerEase;
  41243. }(EasingFunction));
  41244. BABYLON.PowerEase = PowerEase;
  41245. var QuadraticEase = /** @class */ (function (_super) {
  41246. __extends(QuadraticEase, _super);
  41247. function QuadraticEase() {
  41248. return _super !== null && _super.apply(this, arguments) || this;
  41249. }
  41250. QuadraticEase.prototype.easeInCore = function (gradient) {
  41251. return (gradient * gradient);
  41252. };
  41253. return QuadraticEase;
  41254. }(EasingFunction));
  41255. BABYLON.QuadraticEase = QuadraticEase;
  41256. var QuarticEase = /** @class */ (function (_super) {
  41257. __extends(QuarticEase, _super);
  41258. function QuarticEase() {
  41259. return _super !== null && _super.apply(this, arguments) || this;
  41260. }
  41261. QuarticEase.prototype.easeInCore = function (gradient) {
  41262. return (gradient * gradient * gradient * gradient);
  41263. };
  41264. return QuarticEase;
  41265. }(EasingFunction));
  41266. BABYLON.QuarticEase = QuarticEase;
  41267. var QuinticEase = /** @class */ (function (_super) {
  41268. __extends(QuinticEase, _super);
  41269. function QuinticEase() {
  41270. return _super !== null && _super.apply(this, arguments) || this;
  41271. }
  41272. QuinticEase.prototype.easeInCore = function (gradient) {
  41273. return (gradient * gradient * gradient * gradient * gradient);
  41274. };
  41275. return QuinticEase;
  41276. }(EasingFunction));
  41277. BABYLON.QuinticEase = QuinticEase;
  41278. var SineEase = /** @class */ (function (_super) {
  41279. __extends(SineEase, _super);
  41280. function SineEase() {
  41281. return _super !== null && _super.apply(this, arguments) || this;
  41282. }
  41283. SineEase.prototype.easeInCore = function (gradient) {
  41284. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41285. };
  41286. return SineEase;
  41287. }(EasingFunction));
  41288. BABYLON.SineEase = SineEase;
  41289. var BezierCurveEase = /** @class */ (function (_super) {
  41290. __extends(BezierCurveEase, _super);
  41291. function BezierCurveEase(x1, y1, x2, y2) {
  41292. if (x1 === void 0) { x1 = 0; }
  41293. if (y1 === void 0) { y1 = 0; }
  41294. if (x2 === void 0) { x2 = 1; }
  41295. if (y2 === void 0) { y2 = 1; }
  41296. var _this = _super.call(this) || this;
  41297. _this.x1 = x1;
  41298. _this.y1 = y1;
  41299. _this.x2 = x2;
  41300. _this.y2 = y2;
  41301. return _this;
  41302. }
  41303. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41304. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41305. };
  41306. return BezierCurveEase;
  41307. }(EasingFunction));
  41308. BABYLON.BezierCurveEase = BezierCurveEase;
  41309. })(BABYLON || (BABYLON = {}));
  41310. //# sourceMappingURL=babylon.easing.js.map
  41311. var BABYLON;
  41312. (function (BABYLON) {
  41313. var Condition = /** @class */ (function () {
  41314. function Condition(actionManager) {
  41315. this._actionManager = actionManager;
  41316. }
  41317. Condition.prototype.isValid = function () {
  41318. return true;
  41319. };
  41320. Condition.prototype._getProperty = function (propertyPath) {
  41321. return this._actionManager._getProperty(propertyPath);
  41322. };
  41323. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41324. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41325. };
  41326. Condition.prototype.serialize = function () {
  41327. };
  41328. Condition.prototype._serialize = function (serializedCondition) {
  41329. return {
  41330. type: 2,
  41331. children: [],
  41332. name: serializedCondition.name,
  41333. properties: serializedCondition.properties
  41334. };
  41335. };
  41336. return Condition;
  41337. }());
  41338. BABYLON.Condition = Condition;
  41339. var ValueCondition = /** @class */ (function (_super) {
  41340. __extends(ValueCondition, _super);
  41341. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41342. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41343. var _this = _super.call(this, actionManager) || this;
  41344. _this.propertyPath = propertyPath;
  41345. _this.value = value;
  41346. _this.operator = operator;
  41347. _this._target = target;
  41348. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41349. _this._property = _this._getProperty(_this.propertyPath);
  41350. return _this;
  41351. }
  41352. Object.defineProperty(ValueCondition, "IsEqual", {
  41353. get: function () {
  41354. return ValueCondition._IsEqual;
  41355. },
  41356. enumerable: true,
  41357. configurable: true
  41358. });
  41359. Object.defineProperty(ValueCondition, "IsDifferent", {
  41360. get: function () {
  41361. return ValueCondition._IsDifferent;
  41362. },
  41363. enumerable: true,
  41364. configurable: true
  41365. });
  41366. Object.defineProperty(ValueCondition, "IsGreater", {
  41367. get: function () {
  41368. return ValueCondition._IsGreater;
  41369. },
  41370. enumerable: true,
  41371. configurable: true
  41372. });
  41373. Object.defineProperty(ValueCondition, "IsLesser", {
  41374. get: function () {
  41375. return ValueCondition._IsLesser;
  41376. },
  41377. enumerable: true,
  41378. configurable: true
  41379. });
  41380. // Methods
  41381. ValueCondition.prototype.isValid = function () {
  41382. switch (this.operator) {
  41383. case ValueCondition.IsGreater:
  41384. return this._effectiveTarget[this._property] > this.value;
  41385. case ValueCondition.IsLesser:
  41386. return this._effectiveTarget[this._property] < this.value;
  41387. case ValueCondition.IsEqual:
  41388. case ValueCondition.IsDifferent:
  41389. var check;
  41390. if (this.value.equals) {
  41391. check = this.value.equals(this._effectiveTarget[this._property]);
  41392. }
  41393. else {
  41394. check = this.value === this._effectiveTarget[this._property];
  41395. }
  41396. return this.operator === ValueCondition.IsEqual ? check : !check;
  41397. }
  41398. return false;
  41399. };
  41400. ValueCondition.prototype.serialize = function () {
  41401. return this._serialize({
  41402. name: "ValueCondition",
  41403. properties: [
  41404. BABYLON.Action._GetTargetProperty(this._target),
  41405. { name: "propertyPath", value: this.propertyPath },
  41406. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41407. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41408. ]
  41409. });
  41410. };
  41411. ValueCondition.GetOperatorName = function (operator) {
  41412. switch (operator) {
  41413. case ValueCondition._IsEqual: return "IsEqual";
  41414. case ValueCondition._IsDifferent: return "IsDifferent";
  41415. case ValueCondition._IsGreater: return "IsGreater";
  41416. case ValueCondition._IsLesser: return "IsLesser";
  41417. default: return "";
  41418. }
  41419. };
  41420. // Statics
  41421. ValueCondition._IsEqual = 0;
  41422. ValueCondition._IsDifferent = 1;
  41423. ValueCondition._IsGreater = 2;
  41424. ValueCondition._IsLesser = 3;
  41425. return ValueCondition;
  41426. }(Condition));
  41427. BABYLON.ValueCondition = ValueCondition;
  41428. var PredicateCondition = /** @class */ (function (_super) {
  41429. __extends(PredicateCondition, _super);
  41430. function PredicateCondition(actionManager, predicate) {
  41431. var _this = _super.call(this, actionManager) || this;
  41432. _this.predicate = predicate;
  41433. return _this;
  41434. }
  41435. PredicateCondition.prototype.isValid = function () {
  41436. return this.predicate();
  41437. };
  41438. return PredicateCondition;
  41439. }(Condition));
  41440. BABYLON.PredicateCondition = PredicateCondition;
  41441. var StateCondition = /** @class */ (function (_super) {
  41442. __extends(StateCondition, _super);
  41443. function StateCondition(actionManager, target, value) {
  41444. var _this = _super.call(this, actionManager) || this;
  41445. _this.value = value;
  41446. _this._target = target;
  41447. return _this;
  41448. }
  41449. // Methods
  41450. StateCondition.prototype.isValid = function () {
  41451. return this._target.state === this.value;
  41452. };
  41453. StateCondition.prototype.serialize = function () {
  41454. return this._serialize({
  41455. name: "StateCondition",
  41456. properties: [
  41457. BABYLON.Action._GetTargetProperty(this._target),
  41458. { name: "value", value: this.value }
  41459. ]
  41460. });
  41461. };
  41462. return StateCondition;
  41463. }(Condition));
  41464. BABYLON.StateCondition = StateCondition;
  41465. })(BABYLON || (BABYLON = {}));
  41466. //# sourceMappingURL=babylon.condition.js.map
  41467. var BABYLON;
  41468. (function (BABYLON) {
  41469. var Action = /** @class */ (function () {
  41470. function Action(triggerOptions, condition) {
  41471. this.triggerOptions = triggerOptions;
  41472. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41473. if (triggerOptions.parameter) {
  41474. this.trigger = triggerOptions.trigger;
  41475. this._triggerParameter = triggerOptions.parameter;
  41476. }
  41477. else {
  41478. this.trigger = triggerOptions;
  41479. }
  41480. this._nextActiveAction = this;
  41481. this._condition = condition;
  41482. }
  41483. // Methods
  41484. Action.prototype._prepare = function () {
  41485. };
  41486. Action.prototype.getTriggerParameter = function () {
  41487. return this._triggerParameter;
  41488. };
  41489. Action.prototype._executeCurrent = function (evt) {
  41490. if (this._nextActiveAction._condition) {
  41491. var condition = this._nextActiveAction._condition;
  41492. var currentRenderId = this._actionManager.getScene().getRenderId();
  41493. // We cache the current evaluation for the current frame
  41494. if (condition._evaluationId === currentRenderId) {
  41495. if (!condition._currentResult) {
  41496. return;
  41497. }
  41498. }
  41499. else {
  41500. condition._evaluationId = currentRenderId;
  41501. if (!condition.isValid()) {
  41502. condition._currentResult = false;
  41503. return;
  41504. }
  41505. condition._currentResult = true;
  41506. }
  41507. }
  41508. this.onBeforeExecuteObservable.notifyObservers(this);
  41509. this._nextActiveAction.execute(evt);
  41510. this.skipToNextActiveAction();
  41511. };
  41512. Action.prototype.execute = function (evt) {
  41513. };
  41514. Action.prototype.skipToNextActiveAction = function () {
  41515. if (this._nextActiveAction._child) {
  41516. if (!this._nextActiveAction._child._actionManager) {
  41517. this._nextActiveAction._child._actionManager = this._actionManager;
  41518. }
  41519. this._nextActiveAction = this._nextActiveAction._child;
  41520. }
  41521. else {
  41522. this._nextActiveAction = this;
  41523. }
  41524. };
  41525. Action.prototype.then = function (action) {
  41526. this._child = action;
  41527. action._actionManager = this._actionManager;
  41528. action._prepare();
  41529. return action;
  41530. };
  41531. Action.prototype._getProperty = function (propertyPath) {
  41532. return this._actionManager._getProperty(propertyPath);
  41533. };
  41534. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41535. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41536. };
  41537. Action.prototype.serialize = function (parent) {
  41538. };
  41539. // Called by BABYLON.Action objects in serialize(...). Internal use
  41540. Action.prototype._serialize = function (serializedAction, parent) {
  41541. var serializationObject = {
  41542. type: 1,
  41543. children: [],
  41544. name: serializedAction.name,
  41545. properties: serializedAction.properties || []
  41546. };
  41547. // Serialize child
  41548. if (this._child) {
  41549. this._child.serialize(serializationObject);
  41550. }
  41551. // Check if "this" has a condition
  41552. if (this._condition) {
  41553. var serializedCondition = this._condition.serialize();
  41554. serializedCondition.children.push(serializationObject);
  41555. if (parent) {
  41556. parent.children.push(serializedCondition);
  41557. }
  41558. return serializedCondition;
  41559. }
  41560. if (parent) {
  41561. parent.children.push(serializationObject);
  41562. }
  41563. return serializationObject;
  41564. };
  41565. Action._SerializeValueAsString = function (value) {
  41566. if (typeof value === "number") {
  41567. return value.toString();
  41568. }
  41569. if (typeof value === "boolean") {
  41570. return value ? "true" : "false";
  41571. }
  41572. if (value instanceof BABYLON.Vector2) {
  41573. return value.x + ", " + value.y;
  41574. }
  41575. if (value instanceof BABYLON.Vector3) {
  41576. return value.x + ", " + value.y + ", " + value.z;
  41577. }
  41578. if (value instanceof BABYLON.Color3) {
  41579. return value.r + ", " + value.g + ", " + value.b;
  41580. }
  41581. if (value instanceof BABYLON.Color4) {
  41582. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41583. }
  41584. return value; // string
  41585. };
  41586. Action._GetTargetProperty = function (target) {
  41587. return {
  41588. name: "target",
  41589. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41590. : target instanceof BABYLON.Light ? "LightProperties"
  41591. : target instanceof BABYLON.Camera ? "CameraProperties"
  41592. : "SceneProperties",
  41593. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41594. };
  41595. };
  41596. return Action;
  41597. }());
  41598. BABYLON.Action = Action;
  41599. })(BABYLON || (BABYLON = {}));
  41600. //# sourceMappingURL=babylon.action.js.map
  41601. var BABYLON;
  41602. (function (BABYLON) {
  41603. /**
  41604. * ActionEvent is the event beint sent when an action is triggered.
  41605. */
  41606. var ActionEvent = /** @class */ (function () {
  41607. /**
  41608. * @param source The mesh or sprite that triggered the action.
  41609. * @param pointerX The X mouse cursor position at the time of the event
  41610. * @param pointerY The Y mouse cursor position at the time of the event
  41611. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41612. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41613. */
  41614. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41615. this.source = source;
  41616. this.pointerX = pointerX;
  41617. this.pointerY = pointerY;
  41618. this.meshUnderPointer = meshUnderPointer;
  41619. this.sourceEvent = sourceEvent;
  41620. this.additionalData = additionalData;
  41621. }
  41622. /**
  41623. * Helper function to auto-create an ActionEvent from a source mesh.
  41624. * @param source The source mesh that triggered the event
  41625. * @param evt {Event} The original (browser) event
  41626. */
  41627. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41628. var scene = source.getScene();
  41629. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41630. };
  41631. /**
  41632. * Helper function to auto-create an ActionEvent from a source mesh.
  41633. * @param source The source sprite that triggered the event
  41634. * @param scene Scene associated with the sprite
  41635. * @param evt {Event} The original (browser) event
  41636. */
  41637. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41638. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41639. };
  41640. /**
  41641. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41642. * @param scene the scene where the event occurred
  41643. * @param evt {Event} The original (browser) event
  41644. */
  41645. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41646. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41647. };
  41648. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41649. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41650. };
  41651. return ActionEvent;
  41652. }());
  41653. BABYLON.ActionEvent = ActionEvent;
  41654. /**
  41655. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41656. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41657. */
  41658. var ActionManager = /** @class */ (function () {
  41659. function ActionManager(scene) {
  41660. // Members
  41661. this.actions = new Array();
  41662. this.hoverCursor = '';
  41663. this._scene = scene;
  41664. scene._actionManagers.push(this);
  41665. }
  41666. Object.defineProperty(ActionManager, "NothingTrigger", {
  41667. get: function () {
  41668. return ActionManager._NothingTrigger;
  41669. },
  41670. enumerable: true,
  41671. configurable: true
  41672. });
  41673. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41674. get: function () {
  41675. return ActionManager._OnPickTrigger;
  41676. },
  41677. enumerable: true,
  41678. configurable: true
  41679. });
  41680. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41681. get: function () {
  41682. return ActionManager._OnLeftPickTrigger;
  41683. },
  41684. enumerable: true,
  41685. configurable: true
  41686. });
  41687. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41688. get: function () {
  41689. return ActionManager._OnRightPickTrigger;
  41690. },
  41691. enumerable: true,
  41692. configurable: true
  41693. });
  41694. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41695. get: function () {
  41696. return ActionManager._OnCenterPickTrigger;
  41697. },
  41698. enumerable: true,
  41699. configurable: true
  41700. });
  41701. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41702. get: function () {
  41703. return ActionManager._OnPickDownTrigger;
  41704. },
  41705. enumerable: true,
  41706. configurable: true
  41707. });
  41708. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41709. get: function () {
  41710. return ActionManager._OnDoublePickTrigger;
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41716. get: function () {
  41717. return ActionManager._OnPickUpTrigger;
  41718. },
  41719. enumerable: true,
  41720. configurable: true
  41721. });
  41722. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41723. /// This trigger will only be raised if you also declared a OnPickDown
  41724. get: function () {
  41725. return ActionManager._OnPickOutTrigger;
  41726. },
  41727. enumerable: true,
  41728. configurable: true
  41729. });
  41730. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41731. get: function () {
  41732. return ActionManager._OnLongPressTrigger;
  41733. },
  41734. enumerable: true,
  41735. configurable: true
  41736. });
  41737. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41738. get: function () {
  41739. return ActionManager._OnPointerOverTrigger;
  41740. },
  41741. enumerable: true,
  41742. configurable: true
  41743. });
  41744. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41745. get: function () {
  41746. return ActionManager._OnPointerOutTrigger;
  41747. },
  41748. enumerable: true,
  41749. configurable: true
  41750. });
  41751. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41752. get: function () {
  41753. return ActionManager._OnEveryFrameTrigger;
  41754. },
  41755. enumerable: true,
  41756. configurable: true
  41757. });
  41758. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41759. get: function () {
  41760. return ActionManager._OnIntersectionEnterTrigger;
  41761. },
  41762. enumerable: true,
  41763. configurable: true
  41764. });
  41765. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41766. get: function () {
  41767. return ActionManager._OnIntersectionExitTrigger;
  41768. },
  41769. enumerable: true,
  41770. configurable: true
  41771. });
  41772. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41773. get: function () {
  41774. return ActionManager._OnKeyDownTrigger;
  41775. },
  41776. enumerable: true,
  41777. configurable: true
  41778. });
  41779. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41780. get: function () {
  41781. return ActionManager._OnKeyUpTrigger;
  41782. },
  41783. enumerable: true,
  41784. configurable: true
  41785. });
  41786. // Methods
  41787. ActionManager.prototype.dispose = function () {
  41788. var index = this._scene._actionManagers.indexOf(this);
  41789. for (var i = 0; i < this.actions.length; i++) {
  41790. var action = this.actions[i];
  41791. ActionManager.Triggers[action.trigger]--;
  41792. if (ActionManager.Triggers[action.trigger] === 0) {
  41793. delete ActionManager.Triggers[action.trigger];
  41794. }
  41795. }
  41796. if (index > -1) {
  41797. this._scene._actionManagers.splice(index, 1);
  41798. }
  41799. };
  41800. ActionManager.prototype.getScene = function () {
  41801. return this._scene;
  41802. };
  41803. /**
  41804. * Does this action manager handles actions of any of the given triggers
  41805. * @param {number[]} triggers - the triggers to be tested
  41806. * @return {boolean} whether one (or more) of the triggers is handeled
  41807. */
  41808. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41809. for (var index = 0; index < this.actions.length; index++) {
  41810. var action = this.actions[index];
  41811. if (triggers.indexOf(action.trigger) > -1) {
  41812. return true;
  41813. }
  41814. }
  41815. return false;
  41816. };
  41817. /**
  41818. * Does this action manager handles actions of a given trigger
  41819. * @param {number} trigger - the trigger to be tested
  41820. * @return {boolean} whether the trigger is handeled
  41821. */
  41822. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41823. for (var index = 0; index < this.actions.length; index++) {
  41824. var action = this.actions[index];
  41825. if (action.trigger === trigger) {
  41826. return true;
  41827. }
  41828. }
  41829. return false;
  41830. };
  41831. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41832. /**
  41833. * Does this action manager has pointer triggers
  41834. * @return {boolean} whether or not it has pointer triggers
  41835. */
  41836. get: function () {
  41837. for (var index = 0; index < this.actions.length; index++) {
  41838. var action = this.actions[index];
  41839. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41840. return true;
  41841. }
  41842. }
  41843. return false;
  41844. },
  41845. enumerable: true,
  41846. configurable: true
  41847. });
  41848. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41849. /**
  41850. * Does this action manager has pick triggers
  41851. * @return {boolean} whether or not it has pick triggers
  41852. */
  41853. get: function () {
  41854. for (var index = 0; index < this.actions.length; index++) {
  41855. var action = this.actions[index];
  41856. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41857. return true;
  41858. }
  41859. }
  41860. return false;
  41861. },
  41862. enumerable: true,
  41863. configurable: true
  41864. });
  41865. Object.defineProperty(ActionManager, "HasTriggers", {
  41866. /**
  41867. * Does exist one action manager with at least one trigger
  41868. * @return {boolean} whether or not it exists one action manager with one trigger
  41869. **/
  41870. get: function () {
  41871. for (var t in ActionManager.Triggers) {
  41872. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41873. return true;
  41874. }
  41875. }
  41876. return false;
  41877. },
  41878. enumerable: true,
  41879. configurable: true
  41880. });
  41881. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41882. /**
  41883. * Does exist one action manager with at least one pick trigger
  41884. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41885. **/
  41886. get: function () {
  41887. for (var t in ActionManager.Triggers) {
  41888. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41889. var t_int = parseInt(t);
  41890. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41891. return true;
  41892. }
  41893. }
  41894. }
  41895. return false;
  41896. },
  41897. enumerable: true,
  41898. configurable: true
  41899. });
  41900. /**
  41901. * Does exist one action manager that handles actions of a given trigger
  41902. * @param {number} trigger - the trigger to be tested
  41903. * @return {boolean} whether the trigger is handeled by at least one action manager
  41904. **/
  41905. ActionManager.HasSpecificTrigger = function (trigger) {
  41906. for (var t in ActionManager.Triggers) {
  41907. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41908. var t_int = parseInt(t);
  41909. if (t_int === trigger) {
  41910. return true;
  41911. }
  41912. }
  41913. }
  41914. return false;
  41915. };
  41916. /**
  41917. * Registers an action to this action manager
  41918. * @param {BABYLON.Action} action - the action to be registered
  41919. * @return {BABYLON.Action} the action amended (prepared) after registration
  41920. */
  41921. ActionManager.prototype.registerAction = function (action) {
  41922. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41923. if (this.getScene().actionManager !== this) {
  41924. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41925. return null;
  41926. }
  41927. }
  41928. this.actions.push(action);
  41929. if (ActionManager.Triggers[action.trigger]) {
  41930. ActionManager.Triggers[action.trigger]++;
  41931. }
  41932. else {
  41933. ActionManager.Triggers[action.trigger] = 1;
  41934. }
  41935. action._actionManager = this;
  41936. action._prepare();
  41937. return action;
  41938. };
  41939. /**
  41940. * Process a specific trigger
  41941. * @param {number} trigger - the trigger to process
  41942. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41943. */
  41944. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41945. for (var index = 0; index < this.actions.length; index++) {
  41946. var action = this.actions[index];
  41947. if (action.trigger === trigger) {
  41948. if (evt) {
  41949. if (trigger === ActionManager.OnKeyUpTrigger
  41950. || trigger === ActionManager.OnKeyDownTrigger) {
  41951. var parameter = action.getTriggerParameter();
  41952. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41953. if (!parameter.toLowerCase) {
  41954. continue;
  41955. }
  41956. var lowerCase = parameter.toLowerCase();
  41957. if (lowerCase !== evt.sourceEvent.key) {
  41958. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41959. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41960. if (actualkey !== lowerCase) {
  41961. continue;
  41962. }
  41963. }
  41964. }
  41965. }
  41966. }
  41967. action._executeCurrent(evt);
  41968. }
  41969. }
  41970. };
  41971. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41972. var properties = propertyPath.split(".");
  41973. for (var index = 0; index < properties.length - 1; index++) {
  41974. target = target[properties[index]];
  41975. }
  41976. return target;
  41977. };
  41978. ActionManager.prototype._getProperty = function (propertyPath) {
  41979. var properties = propertyPath.split(".");
  41980. return properties[properties.length - 1];
  41981. };
  41982. ActionManager.prototype.serialize = function (name) {
  41983. var root = {
  41984. children: new Array(),
  41985. name: name,
  41986. type: 3,
  41987. properties: new Array() // Empty for root but required
  41988. };
  41989. for (var i = 0; i < this.actions.length; i++) {
  41990. var triggerObject = {
  41991. type: 0,
  41992. children: new Array(),
  41993. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41994. properties: new Array()
  41995. };
  41996. var triggerOptions = this.actions[i].triggerOptions;
  41997. if (triggerOptions && typeof triggerOptions !== "number") {
  41998. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41999. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42000. }
  42001. else {
  42002. var parameter = {};
  42003. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42004. if (triggerOptions.parameter.mesh) {
  42005. parameter._meshId = triggerOptions.parameter.mesh.id;
  42006. }
  42007. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42008. }
  42009. }
  42010. // Serialize child action, recursively
  42011. this.actions[i].serialize(triggerObject);
  42012. // Add serialized trigger
  42013. root.children.push(triggerObject);
  42014. }
  42015. return root;
  42016. };
  42017. ActionManager.Parse = function (parsedActions, object, scene) {
  42018. var actionManager = new BABYLON.ActionManager(scene);
  42019. if (object === null)
  42020. scene.actionManager = actionManager;
  42021. else
  42022. object.actionManager = actionManager;
  42023. // instanciate a new object
  42024. var instanciate = function (name, params) {
  42025. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  42026. newInstance.constructor.apply(newInstance, params);
  42027. return newInstance;
  42028. };
  42029. var parseParameter = function (name, value, target, propertyPath) {
  42030. if (propertyPath === null) {
  42031. // String, boolean or float
  42032. var floatValue = parseFloat(value);
  42033. if (value === "true" || value === "false")
  42034. return value === "true";
  42035. else
  42036. return isNaN(floatValue) ? value : floatValue;
  42037. }
  42038. var effectiveTarget = propertyPath.split(".");
  42039. var values = value.split(",");
  42040. // Get effective Target
  42041. for (var i = 0; i < effectiveTarget.length; i++) {
  42042. target = target[effectiveTarget[i]];
  42043. }
  42044. // Return appropriate value with its type
  42045. if (typeof (target) === "boolean")
  42046. return values[0] === "true";
  42047. if (typeof (target) === "string")
  42048. return values[0];
  42049. // Parameters with multiple values such as Vector3 etc.
  42050. var split = new Array();
  42051. for (var i = 0; i < values.length; i++)
  42052. split.push(parseFloat(values[i]));
  42053. if (target instanceof BABYLON.Vector3)
  42054. return BABYLON.Vector3.FromArray(split);
  42055. if (target instanceof BABYLON.Vector4)
  42056. return BABYLON.Vector4.FromArray(split);
  42057. if (target instanceof BABYLON.Color3)
  42058. return BABYLON.Color3.FromArray(split);
  42059. if (target instanceof BABYLON.Color4)
  42060. return BABYLON.Color4.FromArray(split);
  42061. return parseFloat(values[0]);
  42062. };
  42063. // traverse graph per trigger
  42064. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42065. if (combineArray === void 0) { combineArray = null; }
  42066. if (parsedAction.detached)
  42067. return;
  42068. var parameters = new Array();
  42069. var target = null;
  42070. var propertyPath = null;
  42071. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42072. // Parameters
  42073. if (parsedAction.type === 2)
  42074. parameters.push(actionManager);
  42075. else
  42076. parameters.push(trigger);
  42077. if (combine) {
  42078. var actions = new Array();
  42079. for (var j = 0; j < parsedAction.combine.length; j++) {
  42080. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42081. }
  42082. parameters.push(actions);
  42083. }
  42084. else {
  42085. for (var i = 0; i < parsedAction.properties.length; i++) {
  42086. var value = parsedAction.properties[i].value;
  42087. var name = parsedAction.properties[i].name;
  42088. var targetType = parsedAction.properties[i].targetType;
  42089. if (name === "target")
  42090. if (targetType !== null && targetType === "SceneProperties")
  42091. value = target = scene;
  42092. else
  42093. value = target = scene.getNodeByName(value);
  42094. else if (name === "parent")
  42095. value = scene.getNodeByName(value);
  42096. else if (name === "sound")
  42097. value = scene.getSoundByName(value);
  42098. else if (name !== "propertyPath") {
  42099. if (parsedAction.type === 2 && name === "operator")
  42100. value = BABYLON.ValueCondition[value];
  42101. else
  42102. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42103. }
  42104. else {
  42105. propertyPath = value;
  42106. }
  42107. parameters.push(value);
  42108. }
  42109. }
  42110. if (combineArray === null) {
  42111. parameters.push(condition);
  42112. }
  42113. else {
  42114. parameters.push(null);
  42115. }
  42116. // If interpolate value action
  42117. if (parsedAction.name === "InterpolateValueAction") {
  42118. var param = parameters[parameters.length - 2];
  42119. parameters[parameters.length - 1] = param;
  42120. parameters[parameters.length - 2] = condition;
  42121. }
  42122. // Action or condition(s) and not CombineAction
  42123. var newAction = instanciate(parsedAction.name, parameters);
  42124. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42125. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42126. if (action)
  42127. action.then(nothing);
  42128. else
  42129. actionManager.registerAction(nothing);
  42130. action = nothing;
  42131. }
  42132. if (combineArray === null) {
  42133. if (newAction instanceof BABYLON.Condition) {
  42134. condition = newAction;
  42135. newAction = action;
  42136. }
  42137. else {
  42138. condition = null;
  42139. if (action)
  42140. action.then(newAction);
  42141. else
  42142. actionManager.registerAction(newAction);
  42143. }
  42144. }
  42145. else {
  42146. combineArray.push(newAction);
  42147. }
  42148. for (var i = 0; i < parsedAction.children.length; i++)
  42149. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42150. };
  42151. // triggers
  42152. for (var i = 0; i < parsedActions.children.length; i++) {
  42153. var triggerParams;
  42154. var trigger = parsedActions.children[i];
  42155. if (trigger.properties.length > 0) {
  42156. var param = trigger.properties[0].value;
  42157. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42158. if (value._meshId) {
  42159. value.mesh = scene.getMeshByID(value._meshId);
  42160. }
  42161. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42162. }
  42163. else
  42164. triggerParams = ActionManager[trigger.name];
  42165. for (var j = 0; j < trigger.children.length; j++) {
  42166. if (!trigger.detached)
  42167. traverse(trigger.children[j], triggerParams, null, null);
  42168. }
  42169. }
  42170. };
  42171. ActionManager.GetTriggerName = function (trigger) {
  42172. switch (trigger) {
  42173. case 0: return "NothingTrigger";
  42174. case 1: return "OnPickTrigger";
  42175. case 2: return "OnLeftPickTrigger";
  42176. case 3: return "OnRightPickTrigger";
  42177. case 4: return "OnCenterPickTrigger";
  42178. case 5: return "OnPickDownTrigger";
  42179. case 6: return "OnPickUpTrigger";
  42180. case 7: return "OnLongPressTrigger";
  42181. case 8: return "OnPointerOverTrigger";
  42182. case 9: return "OnPointerOutTrigger";
  42183. case 10: return "OnEveryFrameTrigger";
  42184. case 11: return "OnIntersectionEnterTrigger";
  42185. case 12: return "OnIntersectionExitTrigger";
  42186. case 13: return "OnKeyDownTrigger";
  42187. case 14: return "OnKeyUpTrigger";
  42188. case 15: return "OnPickOutTrigger";
  42189. default: return "";
  42190. }
  42191. };
  42192. // Statics
  42193. ActionManager._NothingTrigger = 0;
  42194. ActionManager._OnPickTrigger = 1;
  42195. ActionManager._OnLeftPickTrigger = 2;
  42196. ActionManager._OnRightPickTrigger = 3;
  42197. ActionManager._OnCenterPickTrigger = 4;
  42198. ActionManager._OnPickDownTrigger = 5;
  42199. ActionManager._OnDoublePickTrigger = 6;
  42200. ActionManager._OnPickUpTrigger = 7;
  42201. ActionManager._OnLongPressTrigger = 8;
  42202. ActionManager._OnPointerOverTrigger = 9;
  42203. ActionManager._OnPointerOutTrigger = 10;
  42204. ActionManager._OnEveryFrameTrigger = 11;
  42205. ActionManager._OnIntersectionEnterTrigger = 12;
  42206. ActionManager._OnIntersectionExitTrigger = 13;
  42207. ActionManager._OnKeyDownTrigger = 14;
  42208. ActionManager._OnKeyUpTrigger = 15;
  42209. ActionManager._OnPickOutTrigger = 16;
  42210. ActionManager.Triggers = {};
  42211. return ActionManager;
  42212. }());
  42213. BABYLON.ActionManager = ActionManager;
  42214. })(BABYLON || (BABYLON = {}));
  42215. //# sourceMappingURL=babylon.actionManager.js.map
  42216. var BABYLON;
  42217. (function (BABYLON) {
  42218. var InterpolateValueAction = /** @class */ (function (_super) {
  42219. __extends(InterpolateValueAction, _super);
  42220. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42221. if (duration === void 0) { duration = 1000; }
  42222. var _this = _super.call(this, triggerOptions, condition) || this;
  42223. _this.propertyPath = propertyPath;
  42224. _this.value = value;
  42225. _this.duration = duration;
  42226. _this.stopOtherAnimations = stopOtherAnimations;
  42227. _this.onInterpolationDone = onInterpolationDone;
  42228. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42229. _this._target = _this._effectiveTarget = target;
  42230. return _this;
  42231. }
  42232. InterpolateValueAction.prototype._prepare = function () {
  42233. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42234. this._property = this._getProperty(this.propertyPath);
  42235. };
  42236. InterpolateValueAction.prototype.execute = function () {
  42237. var _this = this;
  42238. var scene = this._actionManager.getScene();
  42239. var keys = [
  42240. {
  42241. frame: 0,
  42242. value: this._effectiveTarget[this._property]
  42243. }, {
  42244. frame: 100,
  42245. value: this.value
  42246. }
  42247. ];
  42248. var dataType;
  42249. if (typeof this.value === "number") {
  42250. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42251. }
  42252. else if (this.value instanceof BABYLON.Color3) {
  42253. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42254. }
  42255. else if (this.value instanceof BABYLON.Vector3) {
  42256. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42257. }
  42258. else if (this.value instanceof BABYLON.Matrix) {
  42259. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42260. }
  42261. else if (this.value instanceof BABYLON.Quaternion) {
  42262. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42263. }
  42264. else {
  42265. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42266. return;
  42267. }
  42268. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42269. animation.setKeys(keys);
  42270. if (this.stopOtherAnimations) {
  42271. scene.stopAnimation(this._effectiveTarget);
  42272. }
  42273. var wrapper = function () {
  42274. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42275. if (_this.onInterpolationDone) {
  42276. _this.onInterpolationDone();
  42277. }
  42278. };
  42279. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42280. };
  42281. InterpolateValueAction.prototype.serialize = function (parent) {
  42282. return _super.prototype._serialize.call(this, {
  42283. name: "InterpolateValueAction",
  42284. properties: [
  42285. BABYLON.Action._GetTargetProperty(this._target),
  42286. { name: "propertyPath", value: this.propertyPath },
  42287. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42288. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42289. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42290. ]
  42291. }, parent);
  42292. };
  42293. return InterpolateValueAction;
  42294. }(BABYLON.Action));
  42295. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42296. })(BABYLON || (BABYLON = {}));
  42297. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42298. var BABYLON;
  42299. (function (BABYLON) {
  42300. var SwitchBooleanAction = /** @class */ (function (_super) {
  42301. __extends(SwitchBooleanAction, _super);
  42302. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42303. var _this = _super.call(this, triggerOptions, condition) || this;
  42304. _this.propertyPath = propertyPath;
  42305. _this._target = _this._effectiveTarget = target;
  42306. return _this;
  42307. }
  42308. SwitchBooleanAction.prototype._prepare = function () {
  42309. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42310. this._property = this._getProperty(this.propertyPath);
  42311. };
  42312. SwitchBooleanAction.prototype.execute = function () {
  42313. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42314. };
  42315. SwitchBooleanAction.prototype.serialize = function (parent) {
  42316. return _super.prototype._serialize.call(this, {
  42317. name: "SwitchBooleanAction",
  42318. properties: [
  42319. BABYLON.Action._GetTargetProperty(this._target),
  42320. { name: "propertyPath", value: this.propertyPath }
  42321. ]
  42322. }, parent);
  42323. };
  42324. return SwitchBooleanAction;
  42325. }(BABYLON.Action));
  42326. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42327. var SetStateAction = /** @class */ (function (_super) {
  42328. __extends(SetStateAction, _super);
  42329. function SetStateAction(triggerOptions, target, value, condition) {
  42330. var _this = _super.call(this, triggerOptions, condition) || this;
  42331. _this.value = value;
  42332. _this._target = target;
  42333. return _this;
  42334. }
  42335. SetStateAction.prototype.execute = function () {
  42336. this._target.state = this.value;
  42337. };
  42338. SetStateAction.prototype.serialize = function (parent) {
  42339. return _super.prototype._serialize.call(this, {
  42340. name: "SetStateAction",
  42341. properties: [
  42342. BABYLON.Action._GetTargetProperty(this._target),
  42343. { name: "value", value: this.value }
  42344. ]
  42345. }, parent);
  42346. };
  42347. return SetStateAction;
  42348. }(BABYLON.Action));
  42349. BABYLON.SetStateAction = SetStateAction;
  42350. var SetValueAction = /** @class */ (function (_super) {
  42351. __extends(SetValueAction, _super);
  42352. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42353. var _this = _super.call(this, triggerOptions, condition) || this;
  42354. _this.propertyPath = propertyPath;
  42355. _this.value = value;
  42356. _this._target = _this._effectiveTarget = target;
  42357. return _this;
  42358. }
  42359. SetValueAction.prototype._prepare = function () {
  42360. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42361. this._property = this._getProperty(this.propertyPath);
  42362. };
  42363. SetValueAction.prototype.execute = function () {
  42364. this._effectiveTarget[this._property] = this.value;
  42365. if (this._target.markAsDirty) {
  42366. this._target.markAsDirty(this._property);
  42367. }
  42368. };
  42369. SetValueAction.prototype.serialize = function (parent) {
  42370. return _super.prototype._serialize.call(this, {
  42371. name: "SetValueAction",
  42372. properties: [
  42373. BABYLON.Action._GetTargetProperty(this._target),
  42374. { name: "propertyPath", value: this.propertyPath },
  42375. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42376. ]
  42377. }, parent);
  42378. };
  42379. return SetValueAction;
  42380. }(BABYLON.Action));
  42381. BABYLON.SetValueAction = SetValueAction;
  42382. var IncrementValueAction = /** @class */ (function (_super) {
  42383. __extends(IncrementValueAction, _super);
  42384. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42385. var _this = _super.call(this, triggerOptions, condition) || this;
  42386. _this.propertyPath = propertyPath;
  42387. _this.value = value;
  42388. _this._target = _this._effectiveTarget = target;
  42389. return _this;
  42390. }
  42391. IncrementValueAction.prototype._prepare = function () {
  42392. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42393. this._property = this._getProperty(this.propertyPath);
  42394. if (typeof this._effectiveTarget[this._property] !== "number") {
  42395. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42396. }
  42397. };
  42398. IncrementValueAction.prototype.execute = function () {
  42399. this._effectiveTarget[this._property] += this.value;
  42400. if (this._target.markAsDirty) {
  42401. this._target.markAsDirty(this._property);
  42402. }
  42403. };
  42404. IncrementValueAction.prototype.serialize = function (parent) {
  42405. return _super.prototype._serialize.call(this, {
  42406. name: "IncrementValueAction",
  42407. properties: [
  42408. BABYLON.Action._GetTargetProperty(this._target),
  42409. { name: "propertyPath", value: this.propertyPath },
  42410. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42411. ]
  42412. }, parent);
  42413. };
  42414. return IncrementValueAction;
  42415. }(BABYLON.Action));
  42416. BABYLON.IncrementValueAction = IncrementValueAction;
  42417. var PlayAnimationAction = /** @class */ (function (_super) {
  42418. __extends(PlayAnimationAction, _super);
  42419. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42420. var _this = _super.call(this, triggerOptions, condition) || this;
  42421. _this.from = from;
  42422. _this.to = to;
  42423. _this.loop = loop;
  42424. _this._target = target;
  42425. return _this;
  42426. }
  42427. PlayAnimationAction.prototype._prepare = function () {
  42428. };
  42429. PlayAnimationAction.prototype.execute = function () {
  42430. var scene = this._actionManager.getScene();
  42431. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42432. };
  42433. PlayAnimationAction.prototype.serialize = function (parent) {
  42434. return _super.prototype._serialize.call(this, {
  42435. name: "PlayAnimationAction",
  42436. properties: [
  42437. BABYLON.Action._GetTargetProperty(this._target),
  42438. { name: "from", value: String(this.from) },
  42439. { name: "to", value: String(this.to) },
  42440. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42441. ]
  42442. }, parent);
  42443. };
  42444. return PlayAnimationAction;
  42445. }(BABYLON.Action));
  42446. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42447. var StopAnimationAction = /** @class */ (function (_super) {
  42448. __extends(StopAnimationAction, _super);
  42449. function StopAnimationAction(triggerOptions, target, condition) {
  42450. var _this = _super.call(this, triggerOptions, condition) || this;
  42451. _this._target = target;
  42452. return _this;
  42453. }
  42454. StopAnimationAction.prototype._prepare = function () {
  42455. };
  42456. StopAnimationAction.prototype.execute = function () {
  42457. var scene = this._actionManager.getScene();
  42458. scene.stopAnimation(this._target);
  42459. };
  42460. StopAnimationAction.prototype.serialize = function (parent) {
  42461. return _super.prototype._serialize.call(this, {
  42462. name: "StopAnimationAction",
  42463. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42464. }, parent);
  42465. };
  42466. return StopAnimationAction;
  42467. }(BABYLON.Action));
  42468. BABYLON.StopAnimationAction = StopAnimationAction;
  42469. var DoNothingAction = /** @class */ (function (_super) {
  42470. __extends(DoNothingAction, _super);
  42471. function DoNothingAction(triggerOptions, condition) {
  42472. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42473. return _super.call(this, triggerOptions, condition) || this;
  42474. }
  42475. DoNothingAction.prototype.execute = function () {
  42476. };
  42477. DoNothingAction.prototype.serialize = function (parent) {
  42478. return _super.prototype._serialize.call(this, {
  42479. name: "DoNothingAction",
  42480. properties: []
  42481. }, parent);
  42482. };
  42483. return DoNothingAction;
  42484. }(BABYLON.Action));
  42485. BABYLON.DoNothingAction = DoNothingAction;
  42486. var CombineAction = /** @class */ (function (_super) {
  42487. __extends(CombineAction, _super);
  42488. function CombineAction(triggerOptions, children, condition) {
  42489. var _this = _super.call(this, triggerOptions, condition) || this;
  42490. _this.children = children;
  42491. return _this;
  42492. }
  42493. CombineAction.prototype._prepare = function () {
  42494. for (var index = 0; index < this.children.length; index++) {
  42495. this.children[index]._actionManager = this._actionManager;
  42496. this.children[index]._prepare();
  42497. }
  42498. };
  42499. CombineAction.prototype.execute = function (evt) {
  42500. for (var index = 0; index < this.children.length; index++) {
  42501. this.children[index].execute(evt);
  42502. }
  42503. };
  42504. CombineAction.prototype.serialize = function (parent) {
  42505. var serializationObject = _super.prototype._serialize.call(this, {
  42506. name: "CombineAction",
  42507. properties: [],
  42508. combine: []
  42509. }, parent);
  42510. for (var i = 0; i < this.children.length; i++) {
  42511. serializationObject.combine.push(this.children[i].serialize(null));
  42512. }
  42513. return serializationObject;
  42514. };
  42515. return CombineAction;
  42516. }(BABYLON.Action));
  42517. BABYLON.CombineAction = CombineAction;
  42518. var ExecuteCodeAction = /** @class */ (function (_super) {
  42519. __extends(ExecuteCodeAction, _super);
  42520. function ExecuteCodeAction(triggerOptions, func, condition) {
  42521. var _this = _super.call(this, triggerOptions, condition) || this;
  42522. _this.func = func;
  42523. return _this;
  42524. }
  42525. ExecuteCodeAction.prototype.execute = function (evt) {
  42526. this.func(evt);
  42527. };
  42528. return ExecuteCodeAction;
  42529. }(BABYLON.Action));
  42530. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42531. var SetParentAction = /** @class */ (function (_super) {
  42532. __extends(SetParentAction, _super);
  42533. function SetParentAction(triggerOptions, target, parent, condition) {
  42534. var _this = _super.call(this, triggerOptions, condition) || this;
  42535. _this._target = target;
  42536. _this._parent = parent;
  42537. return _this;
  42538. }
  42539. SetParentAction.prototype._prepare = function () {
  42540. };
  42541. SetParentAction.prototype.execute = function () {
  42542. if (this._target.parent === this._parent) {
  42543. return;
  42544. }
  42545. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42546. invertParentWorldMatrix.invert();
  42547. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42548. this._target.parent = this._parent;
  42549. };
  42550. SetParentAction.prototype.serialize = function (parent) {
  42551. return _super.prototype._serialize.call(this, {
  42552. name: "SetParentAction",
  42553. properties: [
  42554. BABYLON.Action._GetTargetProperty(this._target),
  42555. BABYLON.Action._GetTargetProperty(this._parent),
  42556. ]
  42557. }, parent);
  42558. };
  42559. return SetParentAction;
  42560. }(BABYLON.Action));
  42561. BABYLON.SetParentAction = SetParentAction;
  42562. var PlaySoundAction = /** @class */ (function (_super) {
  42563. __extends(PlaySoundAction, _super);
  42564. function PlaySoundAction(triggerOptions, sound, condition) {
  42565. var _this = _super.call(this, triggerOptions, condition) || this;
  42566. _this._sound = sound;
  42567. return _this;
  42568. }
  42569. PlaySoundAction.prototype._prepare = function () {
  42570. };
  42571. PlaySoundAction.prototype.execute = function () {
  42572. if (this._sound !== undefined)
  42573. this._sound.play();
  42574. };
  42575. PlaySoundAction.prototype.serialize = function (parent) {
  42576. return _super.prototype._serialize.call(this, {
  42577. name: "PlaySoundAction",
  42578. properties: [{ name: "sound", value: this._sound.name }]
  42579. }, parent);
  42580. };
  42581. return PlaySoundAction;
  42582. }(BABYLON.Action));
  42583. BABYLON.PlaySoundAction = PlaySoundAction;
  42584. var StopSoundAction = /** @class */ (function (_super) {
  42585. __extends(StopSoundAction, _super);
  42586. function StopSoundAction(triggerOptions, sound, condition) {
  42587. var _this = _super.call(this, triggerOptions, condition) || this;
  42588. _this._sound = sound;
  42589. return _this;
  42590. }
  42591. StopSoundAction.prototype._prepare = function () {
  42592. };
  42593. StopSoundAction.prototype.execute = function () {
  42594. if (this._sound !== undefined)
  42595. this._sound.stop();
  42596. };
  42597. StopSoundAction.prototype.serialize = function (parent) {
  42598. return _super.prototype._serialize.call(this, {
  42599. name: "StopSoundAction",
  42600. properties: [{ name: "sound", value: this._sound.name }]
  42601. }, parent);
  42602. };
  42603. return StopSoundAction;
  42604. }(BABYLON.Action));
  42605. BABYLON.StopSoundAction = StopSoundAction;
  42606. })(BABYLON || (BABYLON = {}));
  42607. //# sourceMappingURL=babylon.directActions.js.map
  42608. var BABYLON;
  42609. (function (BABYLON) {
  42610. var SpriteManager = /** @class */ (function () {
  42611. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42612. if (epsilon === void 0) { epsilon = 0.01; }
  42613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42614. this.name = name;
  42615. this.sprites = new Array();
  42616. this.renderingGroupId = 0;
  42617. this.layerMask = 0x0FFFFFFF;
  42618. this.fogEnabled = true;
  42619. this.isPickable = false;
  42620. /**
  42621. * An event triggered when the manager is disposed.
  42622. * @type {BABYLON.Observable}
  42623. */
  42624. this.onDisposeObservable = new BABYLON.Observable();
  42625. this._vertexBuffers = {};
  42626. this._capacity = capacity;
  42627. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42628. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42629. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42630. if (cellSize.width && cellSize.height) {
  42631. this.cellWidth = cellSize.width;
  42632. this.cellHeight = cellSize.height;
  42633. }
  42634. else if (cellSize !== undefined) {
  42635. this.cellWidth = cellSize;
  42636. this.cellHeight = cellSize;
  42637. }
  42638. else {
  42639. return;
  42640. }
  42641. this._epsilon = epsilon;
  42642. this._scene = scene;
  42643. this._scene.spriteManagers.push(this);
  42644. var indices = [];
  42645. var index = 0;
  42646. for (var count = 0; count < capacity; count++) {
  42647. indices.push(index);
  42648. indices.push(index + 1);
  42649. indices.push(index + 2);
  42650. indices.push(index);
  42651. indices.push(index + 2);
  42652. indices.push(index + 3);
  42653. index += 4;
  42654. }
  42655. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42656. // VBO
  42657. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42658. this._vertexData = new Float32Array(capacity * 16 * 4);
  42659. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42660. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42661. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42662. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42663. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42664. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42665. this._vertexBuffers["options"] = options;
  42666. this._vertexBuffers["cellInfo"] = cellInfo;
  42667. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42668. // Effects
  42669. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42670. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42671. }
  42672. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42673. set: function (callback) {
  42674. if (this._onDisposeObserver) {
  42675. this.onDisposeObservable.remove(this._onDisposeObserver);
  42676. }
  42677. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42678. },
  42679. enumerable: true,
  42680. configurable: true
  42681. });
  42682. Object.defineProperty(SpriteManager.prototype, "texture", {
  42683. get: function () {
  42684. return this._spriteTexture;
  42685. },
  42686. set: function (value) {
  42687. this._spriteTexture = value;
  42688. },
  42689. enumerable: true,
  42690. configurable: true
  42691. });
  42692. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42693. var arrayOffset = index * 16;
  42694. if (offsetX === 0)
  42695. offsetX = this._epsilon;
  42696. else if (offsetX === 1)
  42697. offsetX = 1 - this._epsilon;
  42698. if (offsetY === 0)
  42699. offsetY = this._epsilon;
  42700. else if (offsetY === 1)
  42701. offsetY = 1 - this._epsilon;
  42702. this._vertexData[arrayOffset] = sprite.position.x;
  42703. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42704. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42705. this._vertexData[arrayOffset + 3] = sprite.angle;
  42706. this._vertexData[arrayOffset + 4] = sprite.width;
  42707. this._vertexData[arrayOffset + 5] = sprite.height;
  42708. this._vertexData[arrayOffset + 6] = offsetX;
  42709. this._vertexData[arrayOffset + 7] = offsetY;
  42710. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42711. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42712. var offset = (sprite.cellIndex / rowSize) >> 0;
  42713. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42714. this._vertexData[arrayOffset + 11] = offset;
  42715. // Color
  42716. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42717. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42718. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42719. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42720. };
  42721. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42722. var count = Math.min(this._capacity, this.sprites.length);
  42723. var min = BABYLON.Vector3.Zero();
  42724. var max = BABYLON.Vector3.Zero();
  42725. var distance = Number.MAX_VALUE;
  42726. var currentSprite = null;
  42727. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42728. var cameraView = camera.getViewMatrix();
  42729. for (var index = 0; index < count; index++) {
  42730. var sprite = this.sprites[index];
  42731. if (!sprite) {
  42732. continue;
  42733. }
  42734. if (predicate) {
  42735. if (!predicate(sprite)) {
  42736. continue;
  42737. }
  42738. }
  42739. else if (!sprite.isPickable) {
  42740. continue;
  42741. }
  42742. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42743. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42744. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42745. if (ray.intersectsBoxMinMax(min, max)) {
  42746. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42747. if (distance > currentDistance) {
  42748. distance = currentDistance;
  42749. currentSprite = sprite;
  42750. if (fastCheck) {
  42751. break;
  42752. }
  42753. }
  42754. }
  42755. }
  42756. if (currentSprite) {
  42757. var result = new BABYLON.PickingInfo();
  42758. result.hit = true;
  42759. result.pickedSprite = currentSprite;
  42760. result.distance = distance;
  42761. return result;
  42762. }
  42763. return null;
  42764. };
  42765. SpriteManager.prototype.render = function () {
  42766. // Check
  42767. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42768. return;
  42769. var engine = this._scene.getEngine();
  42770. var baseSize = this._spriteTexture.getBaseSize();
  42771. // Sprites
  42772. var deltaTime = engine.getDeltaTime();
  42773. var max = Math.min(this._capacity, this.sprites.length);
  42774. var rowSize = baseSize.width / this.cellWidth;
  42775. var offset = 0;
  42776. for (var index = 0; index < max; index++) {
  42777. var sprite = this.sprites[index];
  42778. if (!sprite) {
  42779. continue;
  42780. }
  42781. sprite._animate(deltaTime);
  42782. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42783. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42784. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42785. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42786. }
  42787. this._buffer.update(this._vertexData);
  42788. // Render
  42789. var effect = this._effectBase;
  42790. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42791. effect = this._effectFog;
  42792. }
  42793. engine.enableEffect(effect);
  42794. var viewMatrix = this._scene.getViewMatrix();
  42795. effect.setTexture("diffuseSampler", this._spriteTexture);
  42796. effect.setMatrix("view", viewMatrix);
  42797. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42798. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42799. // Fog
  42800. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42801. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42802. effect.setColor3("vFogColor", this._scene.fogColor);
  42803. }
  42804. // VBOs
  42805. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42806. // Draw order
  42807. engine.setDepthFunctionToLessOrEqual();
  42808. effect.setBool("alphaTest", true);
  42809. engine.setColorWrite(false);
  42810. engine.draw(true, 0, max * 6);
  42811. engine.setColorWrite(true);
  42812. effect.setBool("alphaTest", false);
  42813. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42814. engine.draw(true, 0, max * 6);
  42815. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42816. };
  42817. SpriteManager.prototype.dispose = function () {
  42818. if (this._buffer) {
  42819. this._buffer.dispose();
  42820. this._buffer = null;
  42821. }
  42822. if (this._indexBuffer) {
  42823. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42824. this._indexBuffer = null;
  42825. }
  42826. if (this._spriteTexture) {
  42827. this._spriteTexture.dispose();
  42828. this._spriteTexture = null;
  42829. }
  42830. // Remove from scene
  42831. var index = this._scene.spriteManagers.indexOf(this);
  42832. this._scene.spriteManagers.splice(index, 1);
  42833. // Callback
  42834. this.onDisposeObservable.notifyObservers(this);
  42835. this.onDisposeObservable.clear();
  42836. };
  42837. return SpriteManager;
  42838. }());
  42839. BABYLON.SpriteManager = SpriteManager;
  42840. })(BABYLON || (BABYLON = {}));
  42841. //# sourceMappingURL=babylon.spriteManager.js.map
  42842. var BABYLON;
  42843. (function (BABYLON) {
  42844. var Sprite = /** @class */ (function () {
  42845. function Sprite(name, manager) {
  42846. this.name = name;
  42847. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42848. this.width = 1.0;
  42849. this.height = 1.0;
  42850. this.angle = 0;
  42851. this.cellIndex = 0;
  42852. this.invertU = 0;
  42853. this.invertV = 0;
  42854. this.animations = new Array();
  42855. this.isPickable = false;
  42856. this._animationStarted = false;
  42857. this._loopAnimation = false;
  42858. this._fromIndex = 0;
  42859. this._toIndex = 0;
  42860. this._delay = 0;
  42861. this._direction = 1;
  42862. this._time = 0;
  42863. this._manager = manager;
  42864. this._manager.sprites.push(this);
  42865. this.position = BABYLON.Vector3.Zero();
  42866. }
  42867. Object.defineProperty(Sprite.prototype, "size", {
  42868. get: function () {
  42869. return this.width;
  42870. },
  42871. set: function (value) {
  42872. this.width = value;
  42873. this.height = value;
  42874. },
  42875. enumerable: true,
  42876. configurable: true
  42877. });
  42878. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42879. this._fromIndex = from;
  42880. this._toIndex = to;
  42881. this._loopAnimation = loop;
  42882. this._delay = delay;
  42883. this._animationStarted = true;
  42884. this._direction = from < to ? 1 : -1;
  42885. this.cellIndex = from;
  42886. this._time = 0;
  42887. this._onAnimationEnd = onAnimationEnd;
  42888. };
  42889. Sprite.prototype.stopAnimation = function () {
  42890. this._animationStarted = false;
  42891. };
  42892. Sprite.prototype._animate = function (deltaTime) {
  42893. if (!this._animationStarted)
  42894. return;
  42895. this._time += deltaTime;
  42896. if (this._time > this._delay) {
  42897. this._time = this._time % this._delay;
  42898. this.cellIndex += this._direction;
  42899. if (this.cellIndex > this._toIndex) {
  42900. if (this._loopAnimation) {
  42901. this.cellIndex = this._fromIndex;
  42902. }
  42903. else {
  42904. this.cellIndex = this._toIndex;
  42905. this._animationStarted = false;
  42906. if (this._onAnimationEnd) {
  42907. this._onAnimationEnd();
  42908. }
  42909. if (this.disposeWhenFinishedAnimating) {
  42910. this.dispose();
  42911. }
  42912. }
  42913. }
  42914. }
  42915. };
  42916. Sprite.prototype.dispose = function () {
  42917. for (var i = 0; i < this._manager.sprites.length; i++) {
  42918. if (this._manager.sprites[i] == this) {
  42919. this._manager.sprites.splice(i, 1);
  42920. }
  42921. }
  42922. };
  42923. return Sprite;
  42924. }());
  42925. BABYLON.Sprite = Sprite;
  42926. })(BABYLON || (BABYLON = {}));
  42927. //# sourceMappingURL=babylon.sprite.js.map
  42928. var BABYLON;
  42929. (function (BABYLON) {
  42930. var IntersectionInfo = /** @class */ (function () {
  42931. function IntersectionInfo(bu, bv, distance) {
  42932. this.bu = bu;
  42933. this.bv = bv;
  42934. this.distance = distance;
  42935. this.faceId = 0;
  42936. this.subMeshId = 0;
  42937. }
  42938. return IntersectionInfo;
  42939. }());
  42940. BABYLON.IntersectionInfo = IntersectionInfo;
  42941. var PickingInfo = /** @class */ (function () {
  42942. function PickingInfo() {
  42943. this.hit = false;
  42944. this.distance = 0;
  42945. this.pickedPoint = null;
  42946. this.pickedMesh = null;
  42947. this.bu = 0;
  42948. this.bv = 0;
  42949. this.faceId = -1;
  42950. this.subMeshId = 0;
  42951. this.pickedSprite = null;
  42952. }
  42953. // Methods
  42954. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42955. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42956. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42957. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42958. return null;
  42959. }
  42960. var indices = this.pickedMesh.getIndices();
  42961. if (!indices) {
  42962. return null;
  42963. }
  42964. var result;
  42965. if (useVerticesNormals) {
  42966. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42967. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42968. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42969. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42970. normal0 = normal0.scale(this.bu);
  42971. normal1 = normal1.scale(this.bv);
  42972. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42973. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42974. }
  42975. else {
  42976. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42977. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42978. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42979. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42980. var p1p2 = vertex1.subtract(vertex2);
  42981. var p3p2 = vertex3.subtract(vertex2);
  42982. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42983. }
  42984. if (useWorldCoordinates) {
  42985. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42986. }
  42987. return BABYLON.Vector3.Normalize(result);
  42988. };
  42989. PickingInfo.prototype.getTextureCoordinates = function () {
  42990. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42991. return null;
  42992. }
  42993. var indices = this.pickedMesh.getIndices();
  42994. if (!indices) {
  42995. return null;
  42996. }
  42997. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42998. if (!uvs) {
  42999. return null;
  43000. }
  43001. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  43002. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  43003. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  43004. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  43005. uv1 = uv1.scale(this.bu);
  43006. uv2 = uv2.scale(this.bv);
  43007. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  43008. };
  43009. return PickingInfo;
  43010. }());
  43011. BABYLON.PickingInfo = PickingInfo;
  43012. })(BABYLON || (BABYLON = {}));
  43013. //# sourceMappingURL=babylon.pickingInfo.js.map
  43014. var BABYLON;
  43015. (function (BABYLON) {
  43016. var Ray = /** @class */ (function () {
  43017. function Ray(origin, direction, length) {
  43018. if (length === void 0) { length = Number.MAX_VALUE; }
  43019. this.origin = origin;
  43020. this.direction = direction;
  43021. this.length = length;
  43022. }
  43023. // Methods
  43024. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  43025. var d = 0.0;
  43026. var maxValue = Number.MAX_VALUE;
  43027. var inv;
  43028. var min;
  43029. var max;
  43030. var temp;
  43031. if (Math.abs(this.direction.x) < 0.0000001) {
  43032. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43033. return false;
  43034. }
  43035. }
  43036. else {
  43037. inv = 1.0 / this.direction.x;
  43038. min = (minimum.x - this.origin.x) * inv;
  43039. max = (maximum.x - this.origin.x) * inv;
  43040. if (max === -Infinity) {
  43041. max = Infinity;
  43042. }
  43043. if (min > max) {
  43044. temp = min;
  43045. min = max;
  43046. max = temp;
  43047. }
  43048. d = Math.max(min, d);
  43049. maxValue = Math.min(max, maxValue);
  43050. if (d > maxValue) {
  43051. return false;
  43052. }
  43053. }
  43054. if (Math.abs(this.direction.y) < 0.0000001) {
  43055. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43056. return false;
  43057. }
  43058. }
  43059. else {
  43060. inv = 1.0 / this.direction.y;
  43061. min = (minimum.y - this.origin.y) * inv;
  43062. max = (maximum.y - this.origin.y) * inv;
  43063. if (max === -Infinity) {
  43064. max = Infinity;
  43065. }
  43066. if (min > max) {
  43067. temp = min;
  43068. min = max;
  43069. max = temp;
  43070. }
  43071. d = Math.max(min, d);
  43072. maxValue = Math.min(max, maxValue);
  43073. if (d > maxValue) {
  43074. return false;
  43075. }
  43076. }
  43077. if (Math.abs(this.direction.z) < 0.0000001) {
  43078. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43079. return false;
  43080. }
  43081. }
  43082. else {
  43083. inv = 1.0 / this.direction.z;
  43084. min = (minimum.z - this.origin.z) * inv;
  43085. max = (maximum.z - this.origin.z) * inv;
  43086. if (max === -Infinity) {
  43087. max = Infinity;
  43088. }
  43089. if (min > max) {
  43090. temp = min;
  43091. min = max;
  43092. max = temp;
  43093. }
  43094. d = Math.max(min, d);
  43095. maxValue = Math.min(max, maxValue);
  43096. if (d > maxValue) {
  43097. return false;
  43098. }
  43099. }
  43100. return true;
  43101. };
  43102. Ray.prototype.intersectsBox = function (box) {
  43103. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43104. };
  43105. Ray.prototype.intersectsSphere = function (sphere) {
  43106. var x = sphere.center.x - this.origin.x;
  43107. var y = sphere.center.y - this.origin.y;
  43108. var z = sphere.center.z - this.origin.z;
  43109. var pyth = (x * x) + (y * y) + (z * z);
  43110. var rr = sphere.radius * sphere.radius;
  43111. if (pyth <= rr) {
  43112. return true;
  43113. }
  43114. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43115. if (dot < 0.0) {
  43116. return false;
  43117. }
  43118. var temp = pyth - (dot * dot);
  43119. return temp <= rr;
  43120. };
  43121. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43122. if (!this._edge1) {
  43123. this._edge1 = BABYLON.Vector3.Zero();
  43124. this._edge2 = BABYLON.Vector3.Zero();
  43125. this._pvec = BABYLON.Vector3.Zero();
  43126. this._tvec = BABYLON.Vector3.Zero();
  43127. this._qvec = BABYLON.Vector3.Zero();
  43128. }
  43129. vertex1.subtractToRef(vertex0, this._edge1);
  43130. vertex2.subtractToRef(vertex0, this._edge2);
  43131. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43132. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43133. if (det === 0) {
  43134. return null;
  43135. }
  43136. var invdet = 1 / det;
  43137. this.origin.subtractToRef(vertex0, this._tvec);
  43138. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43139. if (bu < 0 || bu > 1.0) {
  43140. return null;
  43141. }
  43142. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43143. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43144. if (bv < 0 || bu + bv > 1.0) {
  43145. return null;
  43146. }
  43147. //check if the distance is longer than the predefined length.
  43148. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43149. if (distance > this.length) {
  43150. return null;
  43151. }
  43152. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43153. };
  43154. Ray.prototype.intersectsPlane = function (plane) {
  43155. var distance;
  43156. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43157. if (Math.abs(result1) < 9.99999997475243E-07) {
  43158. return null;
  43159. }
  43160. else {
  43161. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43162. distance = (-plane.d - result2) / result1;
  43163. if (distance < 0.0) {
  43164. if (distance < -9.99999997475243E-07) {
  43165. return null;
  43166. }
  43167. else {
  43168. return 0;
  43169. }
  43170. }
  43171. return distance;
  43172. }
  43173. };
  43174. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43175. var tm = BABYLON.Tmp.Matrix[0];
  43176. mesh.getWorldMatrix().invertToRef(tm);
  43177. if (this._tmpRay) {
  43178. Ray.TransformToRef(this, tm, this._tmpRay);
  43179. }
  43180. else {
  43181. this._tmpRay = Ray.Transform(this, tm);
  43182. }
  43183. return mesh.intersects(this._tmpRay, fastCheck);
  43184. };
  43185. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43186. if (results) {
  43187. results.length = 0;
  43188. }
  43189. else {
  43190. results = [];
  43191. }
  43192. for (var i = 0; i < meshes.length; i++) {
  43193. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43194. if (pickInfo.hit) {
  43195. results.push(pickInfo);
  43196. }
  43197. }
  43198. results.sort(this._comparePickingInfo);
  43199. return results;
  43200. };
  43201. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43202. if (pickingInfoA.distance < pickingInfoB.distance) {
  43203. return -1;
  43204. }
  43205. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43206. return 1;
  43207. }
  43208. else {
  43209. return 0;
  43210. }
  43211. };
  43212. /**
  43213. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43214. * @param sega the first point of the segment to test the intersection against
  43215. * @param segb the second point of the segment to test the intersection against
  43216. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43217. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43218. */
  43219. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43220. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43221. var u = segb.subtract(sega);
  43222. var v = rsegb.subtract(this.origin);
  43223. var w = sega.subtract(this.origin);
  43224. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43225. var b = BABYLON.Vector3.Dot(u, v);
  43226. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43227. var d = BABYLON.Vector3.Dot(u, w);
  43228. var e = BABYLON.Vector3.Dot(v, w);
  43229. var D = a * c - b * b; // always >= 0
  43230. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43231. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43232. // compute the line parameters of the two closest points
  43233. if (D < Ray.smallnum) {
  43234. sN = 0.0; // force using point P0 on segment S1
  43235. sD = 1.0; // to prevent possible division by 0.0 later
  43236. tN = e;
  43237. tD = c;
  43238. }
  43239. else {
  43240. sN = (b * e - c * d);
  43241. tN = (a * e - b * d);
  43242. if (sN < 0.0) {
  43243. sN = 0.0;
  43244. tN = e;
  43245. tD = c;
  43246. }
  43247. else if (sN > sD) {
  43248. sN = sD;
  43249. tN = e + b;
  43250. tD = c;
  43251. }
  43252. }
  43253. if (tN < 0.0) {
  43254. tN = 0.0;
  43255. // recompute sc for this edge
  43256. if (-d < 0.0) {
  43257. sN = 0.0;
  43258. }
  43259. else if (-d > a)
  43260. sN = sD;
  43261. else {
  43262. sN = -d;
  43263. sD = a;
  43264. }
  43265. }
  43266. else if (tN > tD) {
  43267. tN = tD;
  43268. // recompute sc for this edge
  43269. if ((-d + b) < 0.0) {
  43270. sN = 0;
  43271. }
  43272. else if ((-d + b) > a) {
  43273. sN = sD;
  43274. }
  43275. else {
  43276. sN = (-d + b);
  43277. sD = a;
  43278. }
  43279. }
  43280. // finally do the division to get sc and tc
  43281. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43282. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43283. // get the difference of the two closest points
  43284. var qtc = v.multiplyByFloats(tc, tc, tc);
  43285. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43286. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43287. if (isIntersected) {
  43288. return qtc.length();
  43289. }
  43290. return -1;
  43291. };
  43292. // Statics
  43293. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43294. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43295. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43296. var direction = end.subtract(start);
  43297. direction.normalize();
  43298. return new Ray(start, direction);
  43299. };
  43300. /**
  43301. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  43302. * transformed to the given world matrix.
  43303. * @param origin The origin point
  43304. * @param end The end point
  43305. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43306. */
  43307. Ray.CreateNewFromTo = function (origin, end, world) {
  43308. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43309. var direction = end.subtract(origin);
  43310. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43311. direction.normalize();
  43312. return Ray.Transform(new Ray(origin, direction, length), world);
  43313. };
  43314. Ray.Transform = function (ray, matrix) {
  43315. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43316. Ray.TransformToRef(ray, matrix, result);
  43317. return result;
  43318. };
  43319. Ray.TransformToRef = function (ray, matrix, result) {
  43320. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43321. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43322. result.length = ray.length;
  43323. var dir = result.direction;
  43324. var len = dir.length();
  43325. if (!(len === 0 || len === 1)) {
  43326. var num = 1.0 / len;
  43327. dir.x *= num;
  43328. dir.y *= num;
  43329. dir.z *= num;
  43330. result.length *= len;
  43331. }
  43332. };
  43333. Ray.smallnum = 0.00000001;
  43334. Ray.rayl = 10e8;
  43335. return Ray;
  43336. }());
  43337. BABYLON.Ray = Ray;
  43338. })(BABYLON || (BABYLON = {}));
  43339. //# sourceMappingURL=babylon.ray.js.map
  43340. var BABYLON;
  43341. (function (BABYLON) {
  43342. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43343. if (boxMin.x > sphereCenter.x + sphereRadius)
  43344. return false;
  43345. if (sphereCenter.x - sphereRadius > boxMax.x)
  43346. return false;
  43347. if (boxMin.y > sphereCenter.y + sphereRadius)
  43348. return false;
  43349. if (sphereCenter.y - sphereRadius > boxMax.y)
  43350. return false;
  43351. if (boxMin.z > sphereCenter.z + sphereRadius)
  43352. return false;
  43353. if (sphereCenter.z - sphereRadius > boxMax.z)
  43354. return false;
  43355. return true;
  43356. };
  43357. var getLowestRoot = (function () {
  43358. var result = { root: 0, found: false };
  43359. return function (a, b, c, maxR) {
  43360. result.root = 0;
  43361. result.found = false;
  43362. var determinant = b * b - 4.0 * a * c;
  43363. if (determinant < 0)
  43364. return result;
  43365. var sqrtD = Math.sqrt(determinant);
  43366. var r1 = (-b - sqrtD) / (2.0 * a);
  43367. var r2 = (-b + sqrtD) / (2.0 * a);
  43368. if (r1 > r2) {
  43369. var temp = r2;
  43370. r2 = r1;
  43371. r1 = temp;
  43372. }
  43373. if (r1 > 0 && r1 < maxR) {
  43374. result.root = r1;
  43375. result.found = true;
  43376. return result;
  43377. }
  43378. if (r2 > 0 && r2 < maxR) {
  43379. result.root = r2;
  43380. result.found = true;
  43381. return result;
  43382. }
  43383. return result;
  43384. };
  43385. })();
  43386. var Collider = /** @class */ (function () {
  43387. function Collider() {
  43388. this.radius = BABYLON.Vector3.One();
  43389. this.retry = 0;
  43390. this.basePointWorld = BABYLON.Vector3.Zero();
  43391. this.velocityWorld = BABYLON.Vector3.Zero();
  43392. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43393. this._collisionPoint = BABYLON.Vector3.Zero();
  43394. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43395. this._tempVector = BABYLON.Vector3.Zero();
  43396. this._tempVector2 = BABYLON.Vector3.Zero();
  43397. this._tempVector3 = BABYLON.Vector3.Zero();
  43398. this._tempVector4 = BABYLON.Vector3.Zero();
  43399. this._edge = BABYLON.Vector3.Zero();
  43400. this._baseToVertex = BABYLON.Vector3.Zero();
  43401. this._destinationPoint = BABYLON.Vector3.Zero();
  43402. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43403. this._displacementVector = BABYLON.Vector3.Zero();
  43404. this._collisionMask = -1;
  43405. }
  43406. Object.defineProperty(Collider.prototype, "collisionMask", {
  43407. get: function () {
  43408. return this._collisionMask;
  43409. },
  43410. set: function (mask) {
  43411. this._collisionMask = !isNaN(mask) ? mask : -1;
  43412. },
  43413. enumerable: true,
  43414. configurable: true
  43415. });
  43416. // Methods
  43417. Collider.prototype._initialize = function (source, dir, e) {
  43418. this.velocity = dir;
  43419. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43420. this.basePoint = source;
  43421. source.multiplyToRef(this.radius, this.basePointWorld);
  43422. dir.multiplyToRef(this.radius, this.velocityWorld);
  43423. this.velocityWorldLength = this.velocityWorld.length();
  43424. this.epsilon = e;
  43425. this.collisionFound = false;
  43426. };
  43427. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43428. pa.subtractToRef(point, this._tempVector);
  43429. pb.subtractToRef(point, this._tempVector2);
  43430. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43431. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43432. if (d < 0)
  43433. return false;
  43434. pc.subtractToRef(point, this._tempVector3);
  43435. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43436. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43437. if (d < 0)
  43438. return false;
  43439. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43440. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43441. return d >= 0;
  43442. };
  43443. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43444. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43445. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43446. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43447. return false;
  43448. }
  43449. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43450. return false;
  43451. return true;
  43452. };
  43453. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43454. var t0;
  43455. var embeddedInPlane = false;
  43456. //defensive programming, actually not needed.
  43457. if (!trianglePlaneArray) {
  43458. trianglePlaneArray = [];
  43459. }
  43460. if (!trianglePlaneArray[faceIndex]) {
  43461. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43462. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43463. }
  43464. var trianglePlane = trianglePlaneArray[faceIndex];
  43465. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43466. return;
  43467. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43468. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43469. if (normalDotVelocity == 0) {
  43470. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43471. return;
  43472. embeddedInPlane = true;
  43473. t0 = 0;
  43474. }
  43475. else {
  43476. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43477. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43478. if (t0 > t1) {
  43479. var temp = t1;
  43480. t1 = t0;
  43481. t0 = temp;
  43482. }
  43483. if (t0 > 1.0 || t1 < 0.0)
  43484. return;
  43485. if (t0 < 0)
  43486. t0 = 0;
  43487. if (t0 > 1.0)
  43488. t0 = 1.0;
  43489. }
  43490. this._collisionPoint.copyFromFloats(0, 0, 0);
  43491. var found = false;
  43492. var t = 1.0;
  43493. if (!embeddedInPlane) {
  43494. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43495. this.velocity.scaleToRef(t0, this._tempVector);
  43496. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43497. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43498. found = true;
  43499. t = t0;
  43500. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43501. }
  43502. }
  43503. if (!found) {
  43504. var velocitySquaredLength = this.velocity.lengthSquared();
  43505. var a = velocitySquaredLength;
  43506. this.basePoint.subtractToRef(p1, this._tempVector);
  43507. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43508. var c = this._tempVector.lengthSquared() - 1.0;
  43509. var lowestRoot = getLowestRoot(a, b, c, t);
  43510. if (lowestRoot.found) {
  43511. t = lowestRoot.root;
  43512. found = true;
  43513. this._collisionPoint.copyFrom(p1);
  43514. }
  43515. this.basePoint.subtractToRef(p2, this._tempVector);
  43516. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43517. c = this._tempVector.lengthSquared() - 1.0;
  43518. lowestRoot = getLowestRoot(a, b, c, t);
  43519. if (lowestRoot.found) {
  43520. t = lowestRoot.root;
  43521. found = true;
  43522. this._collisionPoint.copyFrom(p2);
  43523. }
  43524. this.basePoint.subtractToRef(p3, this._tempVector);
  43525. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43526. c = this._tempVector.lengthSquared() - 1.0;
  43527. lowestRoot = getLowestRoot(a, b, c, t);
  43528. if (lowestRoot.found) {
  43529. t = lowestRoot.root;
  43530. found = true;
  43531. this._collisionPoint.copyFrom(p3);
  43532. }
  43533. p2.subtractToRef(p1, this._edge);
  43534. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43535. var edgeSquaredLength = this._edge.lengthSquared();
  43536. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43537. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43538. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43539. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43540. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43541. lowestRoot = getLowestRoot(a, b, c, t);
  43542. if (lowestRoot.found) {
  43543. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43544. if (f >= 0.0 && f <= 1.0) {
  43545. t = lowestRoot.root;
  43546. found = true;
  43547. this._edge.scaleInPlace(f);
  43548. p1.addToRef(this._edge, this._collisionPoint);
  43549. }
  43550. }
  43551. p3.subtractToRef(p2, this._edge);
  43552. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43553. edgeSquaredLength = this._edge.lengthSquared();
  43554. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43555. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43556. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43557. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43558. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43559. lowestRoot = getLowestRoot(a, b, c, t);
  43560. if (lowestRoot.found) {
  43561. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43562. if (f >= 0.0 && f <= 1.0) {
  43563. t = lowestRoot.root;
  43564. found = true;
  43565. this._edge.scaleInPlace(f);
  43566. p2.addToRef(this._edge, this._collisionPoint);
  43567. }
  43568. }
  43569. p1.subtractToRef(p3, this._edge);
  43570. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43571. edgeSquaredLength = this._edge.lengthSquared();
  43572. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43573. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43574. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43575. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43576. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43577. lowestRoot = getLowestRoot(a, b, c, t);
  43578. if (lowestRoot.found) {
  43579. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43580. if (f >= 0.0 && f <= 1.0) {
  43581. t = lowestRoot.root;
  43582. found = true;
  43583. this._edge.scaleInPlace(f);
  43584. p3.addToRef(this._edge, this._collisionPoint);
  43585. }
  43586. }
  43587. }
  43588. if (found) {
  43589. var distToCollision = t * this.velocity.length();
  43590. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43591. if (!this.intersectionPoint) {
  43592. this.intersectionPoint = this._collisionPoint.clone();
  43593. }
  43594. else {
  43595. this.intersectionPoint.copyFrom(this._collisionPoint);
  43596. }
  43597. this.nearestDistance = distToCollision;
  43598. this.collisionFound = true;
  43599. }
  43600. }
  43601. };
  43602. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43603. for (var i = indexStart; i < indexEnd; i += 3) {
  43604. var p1 = pts[indices[i] - decal];
  43605. var p2 = pts[indices[i + 1] - decal];
  43606. var p3 = pts[indices[i + 2] - decal];
  43607. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43608. }
  43609. };
  43610. Collider.prototype._getResponse = function (pos, vel) {
  43611. pos.addToRef(vel, this._destinationPoint);
  43612. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43613. this.basePoint.addToRef(vel, pos);
  43614. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43615. this._slidePlaneNormal.normalize();
  43616. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43617. pos.addInPlace(this._displacementVector);
  43618. this.intersectionPoint.addInPlace(this._displacementVector);
  43619. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43620. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43621. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43622. };
  43623. return Collider;
  43624. }());
  43625. BABYLON.Collider = Collider;
  43626. })(BABYLON || (BABYLON = {}));
  43627. //# sourceMappingURL=babylon.collider.js.map
  43628. var BABYLON;
  43629. (function (BABYLON) {
  43630. //WebWorker code will be inserted to this variable.
  43631. BABYLON.CollisionWorker = "";
  43632. var WorkerTaskType;
  43633. (function (WorkerTaskType) {
  43634. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43635. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43636. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43637. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43638. var WorkerReplyType;
  43639. (function (WorkerReplyType) {
  43640. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43641. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43642. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43643. var CollisionCoordinatorWorker = /** @class */ (function () {
  43644. function CollisionCoordinatorWorker() {
  43645. var _this = this;
  43646. this._scaledPosition = BABYLON.Vector3.Zero();
  43647. this._scaledVelocity = BABYLON.Vector3.Zero();
  43648. this.onMeshUpdated = function (mesh) {
  43649. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43650. };
  43651. this.onGeometryUpdated = function (geometry) {
  43652. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43653. };
  43654. this._afterRender = function () {
  43655. if (!_this._init)
  43656. return;
  43657. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43658. return;
  43659. }
  43660. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43661. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43662. if (_this._runningUpdated > 4) {
  43663. return;
  43664. }
  43665. ++_this._runningUpdated;
  43666. var payload = {
  43667. updatedMeshes: _this._addUpdateMeshesList,
  43668. updatedGeometries: _this._addUpdateGeometriesList,
  43669. removedGeometries: _this._toRemoveGeometryArray,
  43670. removedMeshes: _this._toRemoveMeshesArray
  43671. };
  43672. var message = {
  43673. payload: payload,
  43674. taskType: WorkerTaskType.UPDATE
  43675. };
  43676. var serializable = [];
  43677. for (var id in payload.updatedGeometries) {
  43678. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43679. //prepare transferables
  43680. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43681. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43682. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43683. }
  43684. }
  43685. _this._worker.postMessage(message, serializable);
  43686. _this._addUpdateMeshesList = {};
  43687. _this._addUpdateGeometriesList = {};
  43688. _this._toRemoveGeometryArray = [];
  43689. _this._toRemoveMeshesArray = [];
  43690. };
  43691. this._onMessageFromWorker = function (e) {
  43692. var returnData = e.data;
  43693. if (returnData.error != WorkerReplyType.SUCCESS) {
  43694. //TODO what errors can be returned from the worker?
  43695. BABYLON.Tools.Warn("error returned from worker!");
  43696. return;
  43697. }
  43698. switch (returnData.taskType) {
  43699. case WorkerTaskType.INIT:
  43700. _this._init = true;
  43701. //Update the worked with ALL of the scene's current state
  43702. _this._scene.meshes.forEach(function (mesh) {
  43703. _this.onMeshAdded(mesh);
  43704. });
  43705. _this._scene.getGeometries().forEach(function (geometry) {
  43706. _this.onGeometryAdded(geometry);
  43707. });
  43708. break;
  43709. case WorkerTaskType.UPDATE:
  43710. _this._runningUpdated--;
  43711. break;
  43712. case WorkerTaskType.COLLIDE:
  43713. _this._runningCollisionTask = false;
  43714. var returnPayload = returnData.payload;
  43715. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43716. return;
  43717. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43718. if (callback) {
  43719. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43720. if (mesh) {
  43721. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43722. }
  43723. }
  43724. //cleanup
  43725. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43726. break;
  43727. }
  43728. };
  43729. this._collisionsCallbackArray = [];
  43730. this._init = false;
  43731. this._runningUpdated = 0;
  43732. this._runningCollisionTask = false;
  43733. this._addUpdateMeshesList = {};
  43734. this._addUpdateGeometriesList = {};
  43735. this._toRemoveGeometryArray = [];
  43736. this._toRemoveMeshesArray = [];
  43737. }
  43738. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43739. if (!this._init)
  43740. return;
  43741. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43742. return;
  43743. position.divideToRef(collider.radius, this._scaledPosition);
  43744. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43745. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43746. var payload = {
  43747. collider: {
  43748. position: this._scaledPosition.asArray(),
  43749. velocity: this._scaledVelocity.asArray(),
  43750. radius: collider.radius.asArray()
  43751. },
  43752. collisionId: collisionIndex,
  43753. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43754. maximumRetry: maximumRetry
  43755. };
  43756. var message = {
  43757. payload: payload,
  43758. taskType: WorkerTaskType.COLLIDE
  43759. };
  43760. this._worker.postMessage(message);
  43761. };
  43762. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43763. this._scene = scene;
  43764. this._scene.registerAfterRender(this._afterRender);
  43765. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43766. this._worker = new Worker(workerUrl);
  43767. this._worker.onmessage = this._onMessageFromWorker;
  43768. var message = {
  43769. payload: {},
  43770. taskType: WorkerTaskType.INIT
  43771. };
  43772. this._worker.postMessage(message);
  43773. };
  43774. CollisionCoordinatorWorker.prototype.destroy = function () {
  43775. this._scene.unregisterAfterRender(this._afterRender);
  43776. this._worker.terminate();
  43777. };
  43778. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43779. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43780. this.onMeshUpdated(mesh);
  43781. };
  43782. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43783. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43784. };
  43785. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43786. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43787. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43788. this.onGeometryUpdated(geometry);
  43789. };
  43790. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43791. this._toRemoveGeometryArray.push(geometry.id);
  43792. };
  43793. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43794. var submeshes = [];
  43795. if (mesh.subMeshes) {
  43796. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43797. var boundingInfo = sm.getBoundingInfo();
  43798. return {
  43799. position: idx,
  43800. verticesStart: sm.verticesStart,
  43801. verticesCount: sm.verticesCount,
  43802. indexStart: sm.indexStart,
  43803. indexCount: sm.indexCount,
  43804. hasMaterial: !!sm.getMaterial(),
  43805. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43806. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43807. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43808. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43809. };
  43810. });
  43811. }
  43812. var geometryId = null;
  43813. if (mesh instanceof BABYLON.Mesh) {
  43814. var geometry = mesh.geometry;
  43815. geometryId = geometry ? geometry.id : null;
  43816. }
  43817. else if (mesh instanceof BABYLON.InstancedMesh) {
  43818. var geometry = mesh.sourceMesh.geometry;
  43819. geometryId = geometry ? geometry.id : null;
  43820. }
  43821. var boundingInfo = mesh.getBoundingInfo();
  43822. return {
  43823. uniqueId: mesh.uniqueId,
  43824. id: mesh.id,
  43825. name: mesh.name,
  43826. geometryId: geometryId,
  43827. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43828. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43829. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43830. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43831. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43832. subMeshes: submeshes,
  43833. checkCollisions: mesh.checkCollisions
  43834. };
  43835. };
  43836. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43837. return {
  43838. id: geometry.id,
  43839. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43840. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43841. indices: new Uint32Array(geometry.getIndices() || []),
  43842. };
  43843. };
  43844. return CollisionCoordinatorWorker;
  43845. }());
  43846. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43847. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43848. function CollisionCoordinatorLegacy() {
  43849. this._scaledPosition = BABYLON.Vector3.Zero();
  43850. this._scaledVelocity = BABYLON.Vector3.Zero();
  43851. this._finalPosition = BABYLON.Vector3.Zero();
  43852. }
  43853. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43854. position.divideToRef(collider.radius, this._scaledPosition);
  43855. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43856. collider.collidedMesh = null;
  43857. collider.retry = 0;
  43858. collider.initialVelocity = this._scaledVelocity;
  43859. collider.initialPosition = this._scaledPosition;
  43860. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43861. this._finalPosition.multiplyInPlace(collider.radius);
  43862. //run the callback
  43863. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43864. };
  43865. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43866. this._scene = scene;
  43867. };
  43868. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43869. //Legacy need no destruction method.
  43870. };
  43871. //No update in legacy mode
  43872. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43873. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43874. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43875. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43876. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43877. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43878. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43879. if (excludedMesh === void 0) { excludedMesh = null; }
  43880. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43881. if (collider.retry >= maximumRetry) {
  43882. finalPosition.copyFrom(position);
  43883. return;
  43884. }
  43885. // Check if this is a mesh else camera or -1
  43886. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43887. collider._initialize(position, velocity, closeDistance);
  43888. // Check all meshes
  43889. for (var index = 0; index < this._scene.meshes.length; index++) {
  43890. var mesh = this._scene.meshes[index];
  43891. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43892. mesh._checkCollision(collider);
  43893. }
  43894. }
  43895. if (!collider.collisionFound) {
  43896. position.addToRef(velocity, finalPosition);
  43897. return;
  43898. }
  43899. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43900. collider._getResponse(position, velocity);
  43901. }
  43902. if (velocity.length() <= closeDistance) {
  43903. finalPosition.copyFrom(position);
  43904. return;
  43905. }
  43906. collider.retry++;
  43907. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43908. };
  43909. return CollisionCoordinatorLegacy;
  43910. }());
  43911. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43912. })(BABYLON || (BABYLON = {}));
  43913. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43914. var BABYLON;
  43915. (function (BABYLON) {
  43916. var Particle = /** @class */ (function () {
  43917. function Particle(particleSystem) {
  43918. this.particleSystem = particleSystem;
  43919. this.position = BABYLON.Vector3.Zero();
  43920. this.direction = BABYLON.Vector3.Zero();
  43921. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43922. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43923. this.lifeTime = 1.0;
  43924. this.age = 0;
  43925. this.size = 0;
  43926. this.angle = 0;
  43927. this.angularSpeed = 0;
  43928. this._currentFrameCounter = 0;
  43929. this.cellIndex = 0;
  43930. if (!this.particleSystem.isAnimationSheetEnabled) {
  43931. return;
  43932. }
  43933. this.cellIndex = this.particleSystem.startSpriteCellID;
  43934. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43935. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43936. }
  43937. else {
  43938. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43939. }
  43940. }
  43941. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43942. // (ageOffset / scaledUpdateSpeed) / available cells
  43943. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43944. this._currentFrameCounter += scaledUpdateSpeed;
  43945. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43946. this._currentFrameCounter = 0;
  43947. this.cellIndex++;
  43948. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43949. this.cellIndex = this.particleSystem.endSpriteCellID;
  43950. }
  43951. }
  43952. };
  43953. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43954. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43955. this.cellIndex++;
  43956. this._currentFrameCounter = 0;
  43957. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43958. if (this.particleSystem.spriteCellLoop) {
  43959. this.cellIndex = this.particleSystem.startSpriteCellID;
  43960. }
  43961. else {
  43962. this.cellIndex = this.particleSystem.endSpriteCellID;
  43963. }
  43964. }
  43965. }
  43966. else {
  43967. this._currentFrameCounter++;
  43968. }
  43969. };
  43970. Particle.prototype.copyTo = function (other) {
  43971. other.position.copyFrom(this.position);
  43972. other.direction.copyFrom(this.direction);
  43973. other.color.copyFrom(this.color);
  43974. other.colorStep.copyFrom(this.colorStep);
  43975. other.lifeTime = this.lifeTime;
  43976. other.age = this.age;
  43977. other.size = this.size;
  43978. other.angle = this.angle;
  43979. other.angularSpeed = this.angularSpeed;
  43980. other.particleSystem = this.particleSystem;
  43981. other.cellIndex = this.cellIndex;
  43982. };
  43983. return Particle;
  43984. }());
  43985. BABYLON.Particle = Particle;
  43986. })(BABYLON || (BABYLON = {}));
  43987. //# sourceMappingURL=babylon.particle.js.map
  43988. var BABYLON;
  43989. (function (BABYLON) {
  43990. var randomNumber = function (min, max) {
  43991. if (min === max) {
  43992. return (min);
  43993. }
  43994. var random = Math.random();
  43995. return ((random * (max - min)) + min);
  43996. };
  43997. var ParticleSystem = /** @class */ (function () {
  43998. // end of sheet animation
  43999. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  44000. if (customEffect === void 0) { customEffect = null; }
  44001. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  44002. if (epsilon === void 0) { epsilon = 0.01; }
  44003. var _this = this;
  44004. this.name = name;
  44005. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  44006. // Members
  44007. this.animations = [];
  44008. this.renderingGroupId = 0;
  44009. this.emitter = null;
  44010. this.emitRate = 10;
  44011. this.manualEmitCount = -1;
  44012. this.updateSpeed = 0.01;
  44013. this.targetStopDuration = 0;
  44014. this.disposeOnStop = false;
  44015. this.minEmitPower = 1;
  44016. this.maxEmitPower = 1;
  44017. this.minLifeTime = 1;
  44018. this.maxLifeTime = 1;
  44019. this.minSize = 1;
  44020. this.maxSize = 1;
  44021. this.minAngularSpeed = 0;
  44022. this.maxAngularSpeed = 0;
  44023. this.layerMask = 0x0FFFFFFF;
  44024. this.customShader = null;
  44025. this.preventAutoStart = false;
  44026. /**
  44027. * An event triggered when the system is disposed.
  44028. * @type {BABYLON.Observable}
  44029. */
  44030. this.onDisposeObservable = new BABYLON.Observable();
  44031. this.onAnimationEnd = null;
  44032. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44033. this.forceDepthWrite = false;
  44034. this.gravity = BABYLON.Vector3.Zero();
  44035. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44036. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44037. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44038. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44039. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44040. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44041. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44042. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44043. this.particles = new Array();
  44044. this._stockParticles = new Array();
  44045. this._newPartsExcess = 0;
  44046. this._vertexBuffers = {};
  44047. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44048. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44049. this._scaledDirection = BABYLON.Vector3.Zero();
  44050. this._scaledGravity = BABYLON.Vector3.Zero();
  44051. this._currentRenderId = -1;
  44052. this._started = false;
  44053. this._stopped = false;
  44054. this._actualFrame = 0;
  44055. // sheet animation
  44056. this.startSpriteCellID = 0;
  44057. this.endSpriteCellID = 0;
  44058. this.spriteCellLoop = true;
  44059. this.spriteCellChangeSpeed = 0;
  44060. this.spriteCellWidth = 0;
  44061. this.spriteCellHeight = 0;
  44062. this._vertexBufferSize = 11;
  44063. this.appendParticleVertexes = null;
  44064. this.id = name;
  44065. this._capacity = capacity;
  44066. this._epsilon = epsilon;
  44067. if (_isAnimationSheetEnabled) {
  44068. this._vertexBufferSize = 12;
  44069. }
  44070. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44071. this._customEffect = customEffect;
  44072. scene.particleSystems.push(this);
  44073. this._createIndexBuffer();
  44074. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44075. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44076. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44077. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44078. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44079. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44080. if (this._isAnimationSheetEnabled) {
  44081. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44082. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44083. }
  44084. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44085. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44086. this._vertexBuffers["options"] = options;
  44087. // Default behaviors
  44088. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44089. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44090. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44091. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44092. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44093. };
  44094. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44095. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44096. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44097. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44098. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44099. };
  44100. this.updateFunction = function (particles) {
  44101. for (var index = 0; index < particles.length; index++) {
  44102. var particle = particles[index];
  44103. particle.age += _this._scaledUpdateSpeed;
  44104. if (particle.age >= particle.lifeTime) {
  44105. _this.recycleParticle(particle);
  44106. index--;
  44107. continue;
  44108. }
  44109. else {
  44110. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44111. particle.color.addInPlace(_this._scaledColorStep);
  44112. if (particle.color.a < 0)
  44113. particle.color.a = 0;
  44114. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44115. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44116. particle.position.addInPlace(_this._scaledDirection);
  44117. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44118. particle.direction.addInPlace(_this._scaledGravity);
  44119. if (_this._isAnimationSheetEnabled) {
  44120. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44121. }
  44122. }
  44123. }
  44124. };
  44125. }
  44126. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44127. set: function (callback) {
  44128. if (this._onDisposeObserver) {
  44129. this.onDisposeObservable.remove(this._onDisposeObserver);
  44130. }
  44131. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44132. },
  44133. enumerable: true,
  44134. configurable: true
  44135. });
  44136. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44137. get: function () {
  44138. return this._isAnimationSheetEnabled;
  44139. },
  44140. enumerable: true,
  44141. configurable: true
  44142. });
  44143. ParticleSystem.prototype._createIndexBuffer = function () {
  44144. var indices = [];
  44145. var index = 0;
  44146. for (var count = 0; count < this._capacity; count++) {
  44147. indices.push(index);
  44148. indices.push(index + 1);
  44149. indices.push(index + 2);
  44150. indices.push(index);
  44151. indices.push(index + 2);
  44152. indices.push(index + 3);
  44153. index += 4;
  44154. }
  44155. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44156. };
  44157. ParticleSystem.prototype.recycleParticle = function (particle) {
  44158. var lastParticle = this.particles.pop();
  44159. if (lastParticle !== particle) {
  44160. lastParticle.copyTo(particle);
  44161. this._stockParticles.push(lastParticle);
  44162. }
  44163. };
  44164. ParticleSystem.prototype.getCapacity = function () {
  44165. return this._capacity;
  44166. };
  44167. ParticleSystem.prototype.isAlive = function () {
  44168. return this._alive;
  44169. };
  44170. ParticleSystem.prototype.isStarted = function () {
  44171. return this._started;
  44172. };
  44173. ParticleSystem.prototype.start = function () {
  44174. this._started = true;
  44175. this._stopped = false;
  44176. this._actualFrame = 0;
  44177. };
  44178. ParticleSystem.prototype.stop = function () {
  44179. this._stopped = true;
  44180. };
  44181. // animation sheet
  44182. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44183. var offset = index * this._vertexBufferSize;
  44184. this._vertexData[offset] = particle.position.x;
  44185. this._vertexData[offset + 1] = particle.position.y;
  44186. this._vertexData[offset + 2] = particle.position.z;
  44187. this._vertexData[offset + 3] = particle.color.r;
  44188. this._vertexData[offset + 4] = particle.color.g;
  44189. this._vertexData[offset + 5] = particle.color.b;
  44190. this._vertexData[offset + 6] = particle.color.a;
  44191. this._vertexData[offset + 7] = particle.angle;
  44192. this._vertexData[offset + 8] = particle.size;
  44193. this._vertexData[offset + 9] = offsetX;
  44194. this._vertexData[offset + 10] = offsetY;
  44195. };
  44196. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44197. if (offsetX === 0)
  44198. offsetX = this._epsilon;
  44199. else if (offsetX === 1)
  44200. offsetX = 1 - this._epsilon;
  44201. if (offsetY === 0)
  44202. offsetY = this._epsilon;
  44203. else if (offsetY === 1)
  44204. offsetY = 1 - this._epsilon;
  44205. var offset = index * this._vertexBufferSize;
  44206. this._vertexData[offset] = particle.position.x;
  44207. this._vertexData[offset + 1] = particle.position.y;
  44208. this._vertexData[offset + 2] = particle.position.z;
  44209. this._vertexData[offset + 3] = particle.color.r;
  44210. this._vertexData[offset + 4] = particle.color.g;
  44211. this._vertexData[offset + 5] = particle.color.b;
  44212. this._vertexData[offset + 6] = particle.color.a;
  44213. this._vertexData[offset + 7] = particle.angle;
  44214. this._vertexData[offset + 8] = particle.size;
  44215. this._vertexData[offset + 9] = offsetX;
  44216. this._vertexData[offset + 10] = offsetY;
  44217. this._vertexData[offset + 11] = particle.cellIndex;
  44218. };
  44219. ParticleSystem.prototype._update = function (newParticles) {
  44220. // Update current
  44221. this._alive = this.particles.length > 0;
  44222. this.updateFunction(this.particles);
  44223. // Add new ones
  44224. var worldMatrix;
  44225. if (this.emitter.position) {
  44226. var emitterMesh = this.emitter;
  44227. worldMatrix = emitterMesh.getWorldMatrix();
  44228. }
  44229. else {
  44230. var emitterPosition = this.emitter;
  44231. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44232. }
  44233. var particle;
  44234. for (var index = 0; index < newParticles; index++) {
  44235. if (this.particles.length === this._capacity) {
  44236. break;
  44237. }
  44238. if (this._stockParticles.length !== 0) {
  44239. particle = this._stockParticles.pop();
  44240. particle.age = 0;
  44241. particle.cellIndex = this.startSpriteCellID;
  44242. }
  44243. else {
  44244. particle = new BABYLON.Particle(this);
  44245. }
  44246. this.particles.push(particle);
  44247. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44248. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44249. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44250. particle.size = randomNumber(this.minSize, this.maxSize);
  44251. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44252. this.startPositionFunction(worldMatrix, particle.position, particle);
  44253. var step = randomNumber(0, 1.0);
  44254. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44255. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44256. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44257. }
  44258. };
  44259. ParticleSystem.prototype._getEffect = function () {
  44260. if (this._customEffect) {
  44261. return this._customEffect;
  44262. }
  44263. ;
  44264. var defines = [];
  44265. if (this._scene.clipPlane) {
  44266. defines.push("#define CLIPPLANE");
  44267. }
  44268. if (this._isAnimationSheetEnabled) {
  44269. defines.push("#define ANIMATESHEET");
  44270. }
  44271. // Effect
  44272. var join = defines.join("\n");
  44273. if (this._cachedDefines !== join) {
  44274. this._cachedDefines = join;
  44275. var attributesNamesOrOptions;
  44276. var effectCreationOption;
  44277. if (this._isAnimationSheetEnabled) {
  44278. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44279. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44280. }
  44281. else {
  44282. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44283. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44284. }
  44285. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44286. }
  44287. return this._effect;
  44288. };
  44289. ParticleSystem.prototype.animate = function () {
  44290. if (!this._started)
  44291. return;
  44292. var effect = this._getEffect();
  44293. // Check
  44294. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44295. return;
  44296. if (this._currentRenderId === this._scene.getRenderId()) {
  44297. return;
  44298. }
  44299. this._currentRenderId = this._scene.getRenderId();
  44300. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44301. // determine the number of particles we need to create
  44302. var newParticles;
  44303. if (this.manualEmitCount > -1) {
  44304. newParticles = this.manualEmitCount;
  44305. this._newPartsExcess = 0;
  44306. this.manualEmitCount = 0;
  44307. }
  44308. else {
  44309. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44310. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44311. }
  44312. if (this._newPartsExcess > 1.0) {
  44313. newParticles += this._newPartsExcess >> 0;
  44314. this._newPartsExcess -= this._newPartsExcess >> 0;
  44315. }
  44316. this._alive = false;
  44317. if (!this._stopped) {
  44318. this._actualFrame += this._scaledUpdateSpeed;
  44319. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44320. this.stop();
  44321. }
  44322. else {
  44323. newParticles = 0;
  44324. }
  44325. this._update(newParticles);
  44326. // Stopped?
  44327. if (this._stopped) {
  44328. if (!this._alive) {
  44329. this._started = false;
  44330. if (this.onAnimationEnd) {
  44331. this.onAnimationEnd();
  44332. }
  44333. if (this.disposeOnStop) {
  44334. this._scene._toBeDisposed.push(this);
  44335. }
  44336. }
  44337. }
  44338. // Animation sheet
  44339. if (this._isAnimationSheetEnabled) {
  44340. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44341. }
  44342. else {
  44343. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44344. }
  44345. // Update VBO
  44346. var offset = 0;
  44347. for (var index = 0; index < this.particles.length; index++) {
  44348. var particle = this.particles[index];
  44349. this.appendParticleVertexes(offset, particle);
  44350. offset += 4;
  44351. }
  44352. if (this._vertexBuffer) {
  44353. this._vertexBuffer.update(this._vertexData);
  44354. }
  44355. };
  44356. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44357. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44358. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44359. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44360. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44361. };
  44362. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44363. this._appendParticleVertex(offset++, particle, 0, 0);
  44364. this._appendParticleVertex(offset++, particle, 1, 0);
  44365. this._appendParticleVertex(offset++, particle, 1, 1);
  44366. this._appendParticleVertex(offset++, particle, 0, 1);
  44367. };
  44368. ParticleSystem.prototype.rebuild = function () {
  44369. this._createIndexBuffer();
  44370. if (this._vertexBuffer) {
  44371. this._vertexBuffer._rebuild();
  44372. }
  44373. };
  44374. ParticleSystem.prototype.render = function () {
  44375. var effect = this._getEffect();
  44376. // Check
  44377. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44378. return 0;
  44379. var engine = this._scene.getEngine();
  44380. // Render
  44381. engine.enableEffect(effect);
  44382. engine.setState(false);
  44383. var viewMatrix = this._scene.getViewMatrix();
  44384. effect.setTexture("diffuseSampler", this.particleTexture);
  44385. effect.setMatrix("view", viewMatrix);
  44386. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44387. if (this._isAnimationSheetEnabled) {
  44388. var baseSize = this.particleTexture.getBaseSize();
  44389. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44390. }
  44391. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44392. if (this._scene.clipPlane) {
  44393. var clipPlane = this._scene.clipPlane;
  44394. var invView = viewMatrix.clone();
  44395. invView.invert();
  44396. effect.setMatrix("invView", invView);
  44397. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44398. }
  44399. // VBOs
  44400. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44401. // Draw order
  44402. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44403. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44404. }
  44405. else {
  44406. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44407. }
  44408. if (this.forceDepthWrite) {
  44409. engine.setDepthWrite(true);
  44410. }
  44411. engine.draw(true, 0, this.particles.length * 6);
  44412. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44413. return this.particles.length;
  44414. };
  44415. ParticleSystem.prototype.dispose = function () {
  44416. if (this._vertexBuffer) {
  44417. this._vertexBuffer.dispose();
  44418. this._vertexBuffer = null;
  44419. }
  44420. if (this._indexBuffer) {
  44421. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44422. this._indexBuffer = null;
  44423. }
  44424. if (this.particleTexture) {
  44425. this.particleTexture.dispose();
  44426. this.particleTexture = null;
  44427. }
  44428. // Remove from scene
  44429. var index = this._scene.particleSystems.indexOf(this);
  44430. if (index > -1) {
  44431. this._scene.particleSystems.splice(index, 1);
  44432. }
  44433. // Callback
  44434. this.onDisposeObservable.notifyObservers(this);
  44435. this.onDisposeObservable.clear();
  44436. };
  44437. // Clone
  44438. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44439. var custom = null;
  44440. var program = null;
  44441. if (this.customShader != null) {
  44442. program = this.customShader;
  44443. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44444. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44445. }
  44446. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44447. result.customShader = program;
  44448. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44449. if (newEmitter === undefined) {
  44450. newEmitter = this.emitter;
  44451. }
  44452. result.emitter = newEmitter;
  44453. if (this.particleTexture) {
  44454. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44455. }
  44456. if (!this.preventAutoStart) {
  44457. result.start();
  44458. }
  44459. return result;
  44460. };
  44461. ParticleSystem.prototype.serialize = function () {
  44462. var serializationObject = {};
  44463. serializationObject.name = this.name;
  44464. serializationObject.id = this.id;
  44465. // Emitter
  44466. if (this.emitter.position) {
  44467. var emitterMesh = this.emitter;
  44468. serializationObject.emitterId = emitterMesh.id;
  44469. }
  44470. else {
  44471. var emitterPosition = this.emitter;
  44472. serializationObject.emitter = emitterPosition.asArray();
  44473. }
  44474. serializationObject.capacity = this.getCapacity();
  44475. if (this.particleTexture) {
  44476. serializationObject.textureName = this.particleTexture.name;
  44477. }
  44478. // Animations
  44479. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44480. // Particle system
  44481. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44482. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44483. serializationObject.minSize = this.minSize;
  44484. serializationObject.maxSize = this.maxSize;
  44485. serializationObject.minEmitPower = this.minEmitPower;
  44486. serializationObject.maxEmitPower = this.maxEmitPower;
  44487. serializationObject.minLifeTime = this.minLifeTime;
  44488. serializationObject.maxLifeTime = this.maxLifeTime;
  44489. serializationObject.emitRate = this.emitRate;
  44490. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44491. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44492. serializationObject.gravity = this.gravity.asArray();
  44493. serializationObject.direction1 = this.direction1.asArray();
  44494. serializationObject.direction2 = this.direction2.asArray();
  44495. serializationObject.color1 = this.color1.asArray();
  44496. serializationObject.color2 = this.color2.asArray();
  44497. serializationObject.colorDead = this.colorDead.asArray();
  44498. serializationObject.updateSpeed = this.updateSpeed;
  44499. serializationObject.targetStopDuration = this.targetStopDuration;
  44500. serializationObject.textureMask = this.textureMask.asArray();
  44501. serializationObject.blendMode = this.blendMode;
  44502. serializationObject.customShader = this.customShader;
  44503. serializationObject.preventAutoStart = this.preventAutoStart;
  44504. return serializationObject;
  44505. };
  44506. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44507. var name = parsedParticleSystem.name;
  44508. var custom = null;
  44509. var program = null;
  44510. if (parsedParticleSystem.customShader) {
  44511. program = parsedParticleSystem.customShader;
  44512. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44513. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44514. }
  44515. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44516. particleSystem.customShader = program;
  44517. if (parsedParticleSystem.id) {
  44518. particleSystem.id = parsedParticleSystem.id;
  44519. }
  44520. // Auto start
  44521. if (parsedParticleSystem.preventAutoStart) {
  44522. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44523. }
  44524. // Texture
  44525. if (parsedParticleSystem.textureName) {
  44526. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44527. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44528. }
  44529. // Emitter
  44530. if (parsedParticleSystem.emitterId) {
  44531. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44532. }
  44533. else {
  44534. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44535. }
  44536. // Animations
  44537. if (parsedParticleSystem.animations) {
  44538. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44539. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44540. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44541. }
  44542. }
  44543. if (parsedParticleSystem.autoAnimate) {
  44544. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44545. }
  44546. // Particle system
  44547. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44548. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44549. particleSystem.minSize = parsedParticleSystem.minSize;
  44550. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44551. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44552. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44553. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44554. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44555. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44556. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44557. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44558. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44559. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44560. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44561. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44562. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44563. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44564. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44565. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44566. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44567. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44568. if (!particleSystem.preventAutoStart) {
  44569. particleSystem.start();
  44570. }
  44571. return particleSystem;
  44572. };
  44573. // Statics
  44574. ParticleSystem.BLENDMODE_ONEONE = 0;
  44575. ParticleSystem.BLENDMODE_STANDARD = 1;
  44576. return ParticleSystem;
  44577. }());
  44578. BABYLON.ParticleSystem = ParticleSystem;
  44579. })(BABYLON || (BABYLON = {}));
  44580. //# sourceMappingURL=babylon.particleSystem.js.map
  44581. var BABYLON;
  44582. (function (BABYLON) {
  44583. var SolidParticle = /** @class */ (function () {
  44584. /**
  44585. * Creates a Solid Particle object.
  44586. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44587. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44588. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44589. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44590. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44591. * `shapeId` (integer) is the model shape identifier in the SPS.
  44592. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44593. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44594. */
  44595. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44596. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44597. this.idx = 0; // particle global index
  44598. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44599. this.position = BABYLON.Vector3.Zero(); // position
  44600. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44601. this.scaling = BABYLON.Vector3.One(); // scaling
  44602. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44603. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44604. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44605. this.alive = true; // alive
  44606. this.isVisible = true; // visibility
  44607. this._pos = 0; // index of this particle in the global "positions" array
  44608. this._ind = 0; // index of this particle in the global "indices" array
  44609. this.shapeId = 0; // model shape id
  44610. this.idxInShape = 0; // index of the particle in its shape id
  44611. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44612. this.idx = particleIndex;
  44613. this._pos = positionIndex;
  44614. this._ind = indiceIndex;
  44615. this._model = model;
  44616. this.shapeId = shapeId;
  44617. this.idxInShape = idxInShape;
  44618. this._sps = sps;
  44619. if (modelBoundingInfo) {
  44620. this._modelBoundingInfo = modelBoundingInfo;
  44621. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44622. }
  44623. }
  44624. Object.defineProperty(SolidParticle.prototype, "scale", {
  44625. /**
  44626. * legacy support, changed scale to scaling
  44627. */
  44628. get: function () {
  44629. return this.scaling;
  44630. },
  44631. set: function (scale) {
  44632. this.scaling = scale;
  44633. },
  44634. enumerable: true,
  44635. configurable: true
  44636. });
  44637. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44638. /**
  44639. * legacy support, changed quaternion to rotationQuaternion
  44640. */
  44641. get: function () {
  44642. return this.rotationQuaternion;
  44643. },
  44644. set: function (q) {
  44645. this.rotationQuaternion = q;
  44646. },
  44647. enumerable: true,
  44648. configurable: true
  44649. });
  44650. /**
  44651. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44652. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44653. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44654. */
  44655. SolidParticle.prototype.intersectsMesh = function (target) {
  44656. if (!this._boundingInfo || !target._boundingInfo) {
  44657. return false;
  44658. }
  44659. if (this._sps._bSphereOnly) {
  44660. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44661. }
  44662. return this._boundingInfo.intersects(target._boundingInfo, false);
  44663. };
  44664. return SolidParticle;
  44665. }());
  44666. BABYLON.SolidParticle = SolidParticle;
  44667. var ModelShape = /** @class */ (function () {
  44668. /**
  44669. * 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.
  44670. * SPS internal tool, don't use it manually.
  44671. */
  44672. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44673. this._indicesLength = 0; // length of the shape in the model indices array
  44674. this.shapeID = id;
  44675. this._shape = shape;
  44676. this._indicesLength = indicesLength;
  44677. this._shapeUV = shapeUV;
  44678. this._positionFunction = posFunction;
  44679. this._vertexFunction = vtxFunction;
  44680. }
  44681. return ModelShape;
  44682. }());
  44683. BABYLON.ModelShape = ModelShape;
  44684. var DepthSortedParticle = /** @class */ (function () {
  44685. function DepthSortedParticle() {
  44686. this.ind = 0; // index of the particle in the "indices" array
  44687. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44688. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44689. }
  44690. return DepthSortedParticle;
  44691. }());
  44692. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44693. })(BABYLON || (BABYLON = {}));
  44694. //# sourceMappingURL=babylon.solidParticle.js.map
  44695. var BABYLON;
  44696. (function (BABYLON) {
  44697. /**
  44698. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44699. */
  44700. var SolidParticleSystem = /** @class */ (function () {
  44701. /**
  44702. * Creates a SPS (Solid Particle System) object.
  44703. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44704. * `scene` (Scene) is the scene in which the SPS is added.
  44705. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44706. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44707. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44708. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44709. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44710. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44711. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44712. */
  44713. function SolidParticleSystem(name, scene, options) {
  44714. // public members
  44715. /**
  44716. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44717. * Example : var p = SPS.particles[i];
  44718. */
  44719. this.particles = new Array();
  44720. /**
  44721. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44722. */
  44723. this.nbParticles = 0;
  44724. /**
  44725. * If the particles must ever face the camera (default false). Useful for planar particles.
  44726. */
  44727. this.billboard = false;
  44728. /**
  44729. * Recompute normals when adding a shape
  44730. */
  44731. this.recomputeNormals = true;
  44732. /**
  44733. * This a counter ofr your own usage. It's not set by any SPS functions.
  44734. */
  44735. this.counter = 0;
  44736. /**
  44737. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44738. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44739. */
  44740. this.vars = {};
  44741. this._positions = new Array();
  44742. this._indices = new Array();
  44743. this._normals = new Array();
  44744. this._colors = new Array();
  44745. this._uvs = new Array();
  44746. this._index = 0; // indices index
  44747. this._updatable = true;
  44748. this._pickable = false;
  44749. this._isVisibilityBoxLocked = false;
  44750. this._alwaysVisible = false;
  44751. this._depthSort = false;
  44752. this._shapeCounter = 0;
  44753. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44754. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44755. this._computeParticleColor = true;
  44756. this._computeParticleTexture = true;
  44757. this._computeParticleRotation = true;
  44758. this._computeParticleVertex = false;
  44759. this._computeBoundingBox = false;
  44760. this._depthSortParticles = true;
  44761. this._cam_axisZ = BABYLON.Vector3.Zero();
  44762. this._cam_axisY = BABYLON.Vector3.Zero();
  44763. this._cam_axisX = BABYLON.Vector3.Zero();
  44764. this._axisZ = BABYLON.Axis.Z;
  44765. this._camDir = BABYLON.Vector3.Zero();
  44766. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44767. this._rotMatrix = new BABYLON.Matrix();
  44768. this._invertMatrix = new BABYLON.Matrix();
  44769. this._rotated = BABYLON.Vector3.Zero();
  44770. this._quaternion = new BABYLON.Quaternion();
  44771. this._vertex = BABYLON.Vector3.Zero();
  44772. this._normal = BABYLON.Vector3.Zero();
  44773. this._yaw = 0.0;
  44774. this._pitch = 0.0;
  44775. this._roll = 0.0;
  44776. this._halfroll = 0.0;
  44777. this._halfpitch = 0.0;
  44778. this._halfyaw = 0.0;
  44779. this._sinRoll = 0.0;
  44780. this._cosRoll = 0.0;
  44781. this._sinPitch = 0.0;
  44782. this._cosPitch = 0.0;
  44783. this._sinYaw = 0.0;
  44784. this._cosYaw = 0.0;
  44785. this._mustUnrotateFixedNormals = false;
  44786. this._minimum = BABYLON.Tmp.Vector3[0];
  44787. this._maximum = BABYLON.Tmp.Vector3[1];
  44788. this._minBbox = BABYLON.Tmp.Vector3[4];
  44789. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44790. this._particlesIntersect = false;
  44791. this._depthSortFunction = function (p1, p2) {
  44792. return (p2.sqDistance - p1.sqDistance);
  44793. };
  44794. this._needs32Bits = false;
  44795. this._bSphereOnly = false;
  44796. this._bSphereRadiusFactor = 1.0;
  44797. this.name = name;
  44798. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44799. this._camera = scene.activeCamera;
  44800. this._pickable = options ? options.isPickable : false;
  44801. this._depthSort = options ? options.enableDepthSort : false;
  44802. this._particlesIntersect = options ? options.particleIntersection : false;
  44803. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44804. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44805. if (options && options.updatable) {
  44806. this._updatable = options.updatable;
  44807. }
  44808. else {
  44809. this._updatable = true;
  44810. }
  44811. if (this._pickable) {
  44812. this.pickedParticles = [];
  44813. }
  44814. if (this._depthSort) {
  44815. this.depthSortedParticles = [];
  44816. }
  44817. }
  44818. /**
  44819. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44820. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44821. */
  44822. SolidParticleSystem.prototype.buildMesh = function () {
  44823. if (this.nbParticles === 0) {
  44824. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44825. this.addShape(triangle, 1);
  44826. triangle.dispose();
  44827. }
  44828. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44829. this._positions32 = new Float32Array(this._positions);
  44830. this._uvs32 = new Float32Array(this._uvs);
  44831. this._colors32 = new Float32Array(this._colors);
  44832. if (this.recomputeNormals) {
  44833. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44834. }
  44835. this._normals32 = new Float32Array(this._normals);
  44836. this._fixedNormal32 = new Float32Array(this._normals);
  44837. if (this._mustUnrotateFixedNormals) {
  44838. this._unrotateFixedNormals();
  44839. }
  44840. var vertexData = new BABYLON.VertexData();
  44841. vertexData.indices = this._indices32;
  44842. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44843. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44844. if (this._uvs32) {
  44845. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44846. ;
  44847. }
  44848. if (this._colors32) {
  44849. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44850. }
  44851. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44852. vertexData.applyToMesh(mesh, this._updatable);
  44853. this.mesh = mesh;
  44854. this.mesh.isPickable = this._pickable;
  44855. // free memory
  44856. if (!this._depthSort) {
  44857. this._indices = null;
  44858. }
  44859. this._positions = null;
  44860. this._normals = null;
  44861. this._uvs = null;
  44862. this._colors = null;
  44863. if (!this._updatable) {
  44864. this.particles.length = 0;
  44865. }
  44866. return mesh;
  44867. };
  44868. /**
  44869. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44870. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44871. * Thus the particles generated from `digest()` have their property `position` set yet.
  44872. * `mesh` ( Mesh ) is the mesh to be digested
  44873. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44874. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44875. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44876. */
  44877. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44878. var size = (options && options.facetNb) || 1;
  44879. var number = (options && options.number) || 0;
  44880. var delta = (options && options.delta) || 0;
  44881. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44882. var meshInd = mesh.getIndices();
  44883. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44884. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44885. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44886. var f = 0; // facet counter
  44887. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44888. // compute size from number
  44889. if (number) {
  44890. number = (number > totalFacets) ? totalFacets : number;
  44891. size = Math.round(totalFacets / number);
  44892. delta = 0;
  44893. }
  44894. else {
  44895. size = (size > totalFacets) ? totalFacets : size;
  44896. }
  44897. var facetPos = []; // submesh positions
  44898. var facetInd = []; // submesh indices
  44899. var facetUV = []; // submesh UV
  44900. var facetCol = []; // submesh colors
  44901. var barycenter = BABYLON.Tmp.Vector3[0];
  44902. var sizeO = size;
  44903. while (f < totalFacets) {
  44904. size = sizeO + Math.floor((1 + delta) * Math.random());
  44905. if (f > totalFacets - size) {
  44906. size = totalFacets - f;
  44907. }
  44908. // reset temp arrays
  44909. facetPos.length = 0;
  44910. facetInd.length = 0;
  44911. facetUV.length = 0;
  44912. facetCol.length = 0;
  44913. // iterate over "size" facets
  44914. var fi = 0;
  44915. for (var j = f * 3; j < (f + size) * 3; j++) {
  44916. facetInd.push(fi);
  44917. var i = meshInd[j];
  44918. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44919. if (meshUV) {
  44920. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44921. }
  44922. if (meshCol) {
  44923. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44924. }
  44925. fi++;
  44926. }
  44927. // create a model shape for each single particle
  44928. var idx = this.nbParticles;
  44929. var shape = this._posToShape(facetPos);
  44930. var shapeUV = this._uvsToShapeUV(facetUV);
  44931. // compute the barycenter of the shape
  44932. var v;
  44933. for (v = 0; v < shape.length; v++) {
  44934. barycenter.addInPlace(shape[v]);
  44935. }
  44936. barycenter.scaleInPlace(1 / shape.length);
  44937. // shift the shape from its barycenter to the origin
  44938. for (v = 0; v < shape.length; v++) {
  44939. shape[v].subtractInPlace(barycenter);
  44940. }
  44941. var bInfo;
  44942. if (this._particlesIntersect) {
  44943. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44944. }
  44945. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44946. // add the particle in the SPS
  44947. var currentPos = this._positions.length;
  44948. var currentInd = this._indices.length;
  44949. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44950. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44951. // initialize the particle position
  44952. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44953. this._index += shape.length;
  44954. idx++;
  44955. this.nbParticles++;
  44956. this._shapeCounter++;
  44957. f += size;
  44958. }
  44959. return this;
  44960. };
  44961. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  44962. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  44963. var index = 0;
  44964. var idx = 0;
  44965. for (var p = 0; p < this.particles.length; p++) {
  44966. this._particle = this.particles[p];
  44967. this._shape = this._particle._model._shape;
  44968. if (this._particle.rotationQuaternion) {
  44969. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44970. }
  44971. else {
  44972. this._yaw = this._particle.rotation.y;
  44973. this._pitch = this._particle.rotation.x;
  44974. this._roll = this._particle.rotation.z;
  44975. this._quaternionRotationYPR();
  44976. }
  44977. this._quaternionToRotationMatrix();
  44978. this._rotMatrix.invertToRef(this._invertMatrix);
  44979. for (var pt = 0; pt < this._shape.length; pt++) {
  44980. idx = index + pt * 3;
  44981. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  44982. this._fixedNormal32[idx] = this._normal.x;
  44983. this._fixedNormal32[idx + 1] = this._normal.y;
  44984. this._fixedNormal32[idx + 2] = this._normal.z;
  44985. }
  44986. index = idx + 3;
  44987. }
  44988. };
  44989. //reset copy
  44990. SolidParticleSystem.prototype._resetCopy = function () {
  44991. this._copy.position.x = 0;
  44992. this._copy.position.y = 0;
  44993. this._copy.position.z = 0;
  44994. this._copy.rotation.x = 0;
  44995. this._copy.rotation.y = 0;
  44996. this._copy.rotation.z = 0;
  44997. this._copy.rotationQuaternion = null;
  44998. this._copy.scaling.x = 1.0;
  44999. this._copy.scaling.y = 1.0;
  45000. this._copy.scaling.z = 1.0;
  45001. this._copy.uvs.x = 0;
  45002. this._copy.uvs.y = 0;
  45003. this._copy.uvs.z = 1.0;
  45004. this._copy.uvs.w = 1.0;
  45005. this._copy.color = null;
  45006. };
  45007. // _meshBuilder : inserts the shape model in the global SPS mesh
  45008. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  45009. var i;
  45010. var u = 0;
  45011. var c = 0;
  45012. var n = 0;
  45013. this._resetCopy();
  45014. if (options && options.positionFunction) {
  45015. options.positionFunction(this._copy, idx, idxInShape);
  45016. this._mustUnrotateFixedNormals = true;
  45017. }
  45018. if (this._copy.rotationQuaternion) {
  45019. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45020. }
  45021. else {
  45022. this._yaw = this._copy.rotation.y;
  45023. this._pitch = this._copy.rotation.x;
  45024. this._roll = this._copy.rotation.z;
  45025. this._quaternionRotationYPR();
  45026. }
  45027. this._quaternionToRotationMatrix();
  45028. for (i = 0; i < shape.length; i++) {
  45029. this._vertex.x = shape[i].x;
  45030. this._vertex.y = shape[i].y;
  45031. this._vertex.z = shape[i].z;
  45032. if (options && options.vertexFunction) {
  45033. options.vertexFunction(this._copy, this._vertex, i);
  45034. }
  45035. this._vertex.x *= this._copy.scaling.x;
  45036. this._vertex.y *= this._copy.scaling.y;
  45037. this._vertex.z *= this._copy.scaling.z;
  45038. this._vertex.x += this._copy.pivot.x;
  45039. this._vertex.y += this._copy.pivot.y;
  45040. this._vertex.z += this._copy.pivot.z;
  45041. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45042. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45043. if (meshUV) {
  45044. 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);
  45045. u += 2;
  45046. }
  45047. if (this._copy.color) {
  45048. this._color = this._copy.color;
  45049. }
  45050. else if (meshCol && meshCol[c] !== undefined) {
  45051. this._color.r = meshCol[c];
  45052. this._color.g = meshCol[c + 1];
  45053. this._color.b = meshCol[c + 2];
  45054. this._color.a = meshCol[c + 3];
  45055. }
  45056. else {
  45057. this._color.r = 1.0;
  45058. this._color.g = 1.0;
  45059. this._color.b = 1.0;
  45060. this._color.a = 1.0;
  45061. }
  45062. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45063. c += 4;
  45064. if (!this.recomputeNormals && meshNor) {
  45065. this._normal.x = meshNor[n];
  45066. this._normal.y = meshNor[n + 1];
  45067. this._normal.z = meshNor[n + 2];
  45068. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45069. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45070. n += 3;
  45071. }
  45072. }
  45073. for (i = 0; i < meshInd.length; i++) {
  45074. var current_ind = p + meshInd[i];
  45075. indices.push(current_ind);
  45076. if (current_ind > 65535) {
  45077. this._needs32Bits = true;
  45078. }
  45079. }
  45080. if (this._pickable) {
  45081. var nbfaces = meshInd.length / 3;
  45082. for (i = 0; i < nbfaces; i++) {
  45083. this.pickedParticles.push({ idx: idx, faceId: i });
  45084. }
  45085. }
  45086. if (this._depthSort) {
  45087. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45088. }
  45089. return this._copy;
  45090. };
  45091. // returns a shape array from positions array
  45092. SolidParticleSystem.prototype._posToShape = function (positions) {
  45093. var shape = [];
  45094. for (var i = 0; i < positions.length; i += 3) {
  45095. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45096. }
  45097. return shape;
  45098. };
  45099. // returns a shapeUV array from a Vector4 uvs
  45100. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45101. var shapeUV = [];
  45102. if (uvs) {
  45103. for (var i = 0; i < uvs.length; i++)
  45104. shapeUV.push(uvs[i]);
  45105. }
  45106. return shapeUV;
  45107. };
  45108. // adds a new particle object in the particles array
  45109. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45110. if (bInfo === void 0) { bInfo = null; }
  45111. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45112. this.particles.push(sp);
  45113. return sp;
  45114. };
  45115. /**
  45116. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45117. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45118. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45119. * `nb` (positive integer) the number of particles to be created from this model
  45120. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45121. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45122. */
  45123. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45124. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45125. var meshInd = mesh.getIndices();
  45126. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45127. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45128. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45129. var bbInfo;
  45130. if (this._particlesIntersect) {
  45131. bbInfo = mesh.getBoundingInfo();
  45132. }
  45133. var shape = this._posToShape(meshPos);
  45134. var shapeUV = this._uvsToShapeUV(meshUV);
  45135. var posfunc = options ? options.positionFunction : null;
  45136. var vtxfunc = options ? options.vertexFunction : null;
  45137. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45138. // particles
  45139. var sp;
  45140. var currentCopy;
  45141. var idx = this.nbParticles;
  45142. for (var i = 0; i < nb; i++) {
  45143. var currentPos = this._positions.length;
  45144. var currentInd = this._indices.length;
  45145. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45146. if (this._updatable) {
  45147. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45148. sp.position.copyFrom(currentCopy.position);
  45149. sp.rotation.copyFrom(currentCopy.rotation);
  45150. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45151. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45152. }
  45153. if (currentCopy.color && sp.color) {
  45154. sp.color.copyFrom(currentCopy.color);
  45155. }
  45156. sp.scaling.copyFrom(currentCopy.scaling);
  45157. sp.uvs.copyFrom(currentCopy.uvs);
  45158. }
  45159. this._index += shape.length;
  45160. idx++;
  45161. }
  45162. this.nbParticles += nb;
  45163. this._shapeCounter++;
  45164. return this._shapeCounter - 1;
  45165. };
  45166. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45167. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45168. this._resetCopy();
  45169. if (particle._model._positionFunction) {
  45170. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45171. }
  45172. if (this._copy.rotationQuaternion) {
  45173. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45174. }
  45175. else {
  45176. this._yaw = this._copy.rotation.y;
  45177. this._pitch = this._copy.rotation.x;
  45178. this._roll = this._copy.rotation.z;
  45179. this._quaternionRotationYPR();
  45180. }
  45181. this._quaternionToRotationMatrix();
  45182. this._shape = particle._model._shape;
  45183. for (var pt = 0; pt < this._shape.length; pt++) {
  45184. this._vertex.x = this._shape[pt].x;
  45185. this._vertex.y = this._shape[pt].y;
  45186. this._vertex.z = this._shape[pt].z;
  45187. if (particle._model._vertexFunction) {
  45188. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45189. }
  45190. this._vertex.x *= this._copy.scaling.x;
  45191. this._vertex.y *= this._copy.scaling.y;
  45192. this._vertex.z *= this._copy.scaling.z;
  45193. this._vertex.x += this._copy.pivot.x;
  45194. this._vertex.y += this._copy.pivot.y;
  45195. this._vertex.z += this._copy.pivot.z;
  45196. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45197. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45198. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45199. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45200. }
  45201. particle.position.x = 0.0;
  45202. particle.position.y = 0.0;
  45203. particle.position.z = 0.0;
  45204. particle.rotation.x = 0.0;
  45205. particle.rotation.y = 0.0;
  45206. particle.rotation.z = 0.0;
  45207. particle.rotationQuaternion = null;
  45208. particle.scaling.x = 1.0;
  45209. particle.scaling.y = 1.0;
  45210. particle.scaling.z = 1.0;
  45211. };
  45212. /**
  45213. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45214. * Returns the SPS.
  45215. */
  45216. SolidParticleSystem.prototype.rebuildMesh = function () {
  45217. for (var p = 0; p < this.particles.length; p++) {
  45218. this._rebuildParticle(this.particles[p]);
  45219. }
  45220. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45221. return this;
  45222. };
  45223. /**
  45224. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45225. * This method calls `updateParticle()` for each particle of the SPS.
  45226. * For an animated SPS, it is usually called within the render loop.
  45227. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45228. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45229. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45230. * Returns the SPS.
  45231. */
  45232. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45233. if (start === void 0) { start = 0; }
  45234. if (end === void 0) { end = this.nbParticles - 1; }
  45235. if (update === void 0) { update = true; }
  45236. if (!this._updatable) {
  45237. return this;
  45238. }
  45239. // custom beforeUpdate
  45240. this.beforeUpdateParticles(start, end, update);
  45241. this._cam_axisX.x = 1.0;
  45242. this._cam_axisX.y = 0.0;
  45243. this._cam_axisX.z = 0.0;
  45244. this._cam_axisY.x = 0.0;
  45245. this._cam_axisY.y = 1.0;
  45246. this._cam_axisY.z = 0.0;
  45247. this._cam_axisZ.x = 0.0;
  45248. this._cam_axisZ.y = 0.0;
  45249. this._cam_axisZ.z = 1.0;
  45250. // cases when the World Matrix is to be computed first
  45251. if (this.billboard || this._depthSort) {
  45252. this.mesh.computeWorldMatrix(true);
  45253. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45254. }
  45255. // if the particles will always face the camera
  45256. if (this.billboard) {
  45257. // compute the camera position and un-rotate it by the current mesh rotation
  45258. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45259. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45260. this._cam_axisZ.normalize();
  45261. // same for camera up vector extracted from the cam view matrix
  45262. var view = this._camera.getViewMatrix(true);
  45263. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45264. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45265. this._cam_axisY.normalize();
  45266. this._cam_axisX.normalize();
  45267. }
  45268. // if depthSort, compute the camera global position in the mesh local system
  45269. if (this._depthSort) {
  45270. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45271. }
  45272. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45273. var idx = 0; // current position index in the global array positions32
  45274. var index = 0; // position start index in the global array positions32 of the current particle
  45275. var colidx = 0; // current color index in the global array colors32
  45276. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45277. var uvidx = 0; // current uv index in the global array uvs32
  45278. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45279. var pt = 0; // current index in the particle model shape
  45280. if (this.mesh.isFacetDataEnabled) {
  45281. this._computeBoundingBox = true;
  45282. }
  45283. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45284. if (this._computeBoundingBox) {
  45285. if (start == 0 && end == this.nbParticles - 1) {
  45286. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45287. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45288. }
  45289. else {
  45290. if (this.mesh._boundingInfo) {
  45291. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45292. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45293. }
  45294. }
  45295. }
  45296. // particle loop
  45297. index = this.particles[start]._pos;
  45298. var vpos = (index / 3) | 0;
  45299. colorIndex = vpos * 4;
  45300. uvIndex = vpos * 2;
  45301. for (var p = start; p <= end; p++) {
  45302. this._particle = this.particles[p];
  45303. this._shape = this._particle._model._shape;
  45304. this._shapeUV = this._particle._model._shapeUV;
  45305. // call to custom user function to update the particle properties
  45306. this.updateParticle(this._particle);
  45307. // camera-particle distance for depth sorting
  45308. if (this._depthSort && this._depthSortParticles) {
  45309. var dsp = this.depthSortedParticles[p];
  45310. dsp.ind = this._particle._ind;
  45311. dsp.indicesLength = this._particle._model._indicesLength;
  45312. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45313. }
  45314. // skip the computations for inactive or already invisible particles
  45315. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45316. // increment indexes for the next particle
  45317. pt = this._shape.length;
  45318. index += pt * 3;
  45319. colorIndex += pt * 4;
  45320. uvIndex += pt * 2;
  45321. continue;
  45322. }
  45323. if (this._particle.isVisible) {
  45324. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45325. // particle rotation matrix
  45326. if (this.billboard) {
  45327. this._particle.rotation.x = 0.0;
  45328. this._particle.rotation.y = 0.0;
  45329. }
  45330. if (this._computeParticleRotation || this.billboard) {
  45331. if (this._particle.rotationQuaternion) {
  45332. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45333. }
  45334. else {
  45335. this._yaw = this._particle.rotation.y;
  45336. this._pitch = this._particle.rotation.x;
  45337. this._roll = this._particle.rotation.z;
  45338. this._quaternionRotationYPR();
  45339. }
  45340. this._quaternionToRotationMatrix();
  45341. }
  45342. // particle vertex loop
  45343. for (pt = 0; pt < this._shape.length; pt++) {
  45344. idx = index + pt * 3;
  45345. colidx = colorIndex + pt * 4;
  45346. uvidx = uvIndex + pt * 2;
  45347. this._vertex.x = this._shape[pt].x;
  45348. this._vertex.y = this._shape[pt].y;
  45349. this._vertex.z = this._shape[pt].z;
  45350. if (this._computeParticleVertex) {
  45351. this.updateParticleVertex(this._particle, this._vertex, pt);
  45352. }
  45353. // positions
  45354. this._vertex.x *= this._particle.scaling.x;
  45355. this._vertex.y *= this._particle.scaling.y;
  45356. this._vertex.z *= this._particle.scaling.z;
  45357. this._vertex.x += this._particle.pivot.x;
  45358. this._vertex.y += this._particle.pivot.y;
  45359. this._vertex.z += this._particle.pivot.z;
  45360. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45361. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45362. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45363. 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;
  45364. 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;
  45365. 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;
  45366. if (this._computeBoundingBox) {
  45367. if (this._positions32[idx] < this._minimum.x) {
  45368. this._minimum.x = this._positions32[idx];
  45369. }
  45370. if (this._positions32[idx] > this._maximum.x) {
  45371. this._maximum.x = this._positions32[idx];
  45372. }
  45373. if (this._positions32[idx + 1] < this._minimum.y) {
  45374. this._minimum.y = this._positions32[idx + 1];
  45375. }
  45376. if (this._positions32[idx + 1] > this._maximum.y) {
  45377. this._maximum.y = this._positions32[idx + 1];
  45378. }
  45379. if (this._positions32[idx + 2] < this._minimum.z) {
  45380. this._minimum.z = this._positions32[idx + 2];
  45381. }
  45382. if (this._positions32[idx + 2] > this._maximum.z) {
  45383. this._maximum.z = this._positions32[idx + 2];
  45384. }
  45385. }
  45386. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45387. if (!this._computeParticleVertex) {
  45388. this._normal.x = this._fixedNormal32[idx];
  45389. this._normal.y = this._fixedNormal32[idx + 1];
  45390. this._normal.z = this._fixedNormal32[idx + 2];
  45391. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45392. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45393. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45394. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45395. 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;
  45396. 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;
  45397. }
  45398. if (this._computeParticleColor && this._particle.color) {
  45399. this._colors32[colidx] = this._particle.color.r;
  45400. this._colors32[colidx + 1] = this._particle.color.g;
  45401. this._colors32[colidx + 2] = this._particle.color.b;
  45402. this._colors32[colidx + 3] = this._particle.color.a;
  45403. }
  45404. if (this._computeParticleTexture) {
  45405. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45406. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45407. }
  45408. }
  45409. }
  45410. else {
  45411. this._particle._stillInvisible = true; // mark the particle as invisible
  45412. for (pt = 0; pt < this._shape.length; pt++) {
  45413. idx = index + pt * 3;
  45414. colidx = colorIndex + pt * 4;
  45415. uvidx = uvIndex + pt * 2;
  45416. this._positions32[idx] = 0.0;
  45417. this._positions32[idx + 1] = 0.0;
  45418. this._positions32[idx + 2] = 0.0;
  45419. this._normals32[idx] = 0.0;
  45420. this._normals32[idx + 1] = 0.0;
  45421. this._normals32[idx + 2] = 0.0;
  45422. if (this._computeParticleColor && this._particle.color) {
  45423. this._colors32[colidx] = this._particle.color.r;
  45424. this._colors32[colidx + 1] = this._particle.color.g;
  45425. this._colors32[colidx + 2] = this._particle.color.b;
  45426. this._colors32[colidx + 3] = this._particle.color.a;
  45427. }
  45428. if (this._computeParticleTexture) {
  45429. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45430. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45431. }
  45432. }
  45433. }
  45434. // if the particle intersections must be computed : update the bbInfo
  45435. if (this._particlesIntersect) {
  45436. var bInfo = this._particle._boundingInfo;
  45437. var bBox = bInfo.boundingBox;
  45438. var bSphere = bInfo.boundingSphere;
  45439. if (!this._bSphereOnly) {
  45440. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45441. for (var b = 0; b < bBox.vectors.length; b++) {
  45442. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45443. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45444. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45445. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45446. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45447. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45448. 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;
  45449. 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;
  45450. 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;
  45451. }
  45452. bBox._update(this.mesh._worldMatrix);
  45453. }
  45454. // place and scale the particle bouding sphere in the SPS local system, then update it
  45455. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45456. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45457. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45458. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45459. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45460. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45461. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45462. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45463. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45464. 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));
  45465. bSphere._update(this.mesh._worldMatrix);
  45466. }
  45467. // increment indexes for the next particle
  45468. index = idx + 3;
  45469. colorIndex = colidx + 4;
  45470. uvIndex = uvidx + 2;
  45471. }
  45472. // if the VBO must be updated
  45473. if (update) {
  45474. if (this._computeParticleColor) {
  45475. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45476. }
  45477. if (this._computeParticleTexture) {
  45478. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45479. }
  45480. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45481. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45482. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45483. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45484. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45485. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45486. for (var i = 0; i < this._normals32.length; i++) {
  45487. this._fixedNormal32[i] = this._normals32[i];
  45488. }
  45489. }
  45490. if (!this.mesh.areNormalsFrozen) {
  45491. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45492. }
  45493. }
  45494. if (this._depthSort && this._depthSortParticles) {
  45495. this.depthSortedParticles.sort(this._depthSortFunction);
  45496. var dspl = this.depthSortedParticles.length;
  45497. var sorted = 0;
  45498. var lind = 0;
  45499. var sind = 0;
  45500. var sid = 0;
  45501. for (sorted = 0; sorted < dspl; sorted++) {
  45502. lind = this.depthSortedParticles[sorted].indicesLength;
  45503. sind = this.depthSortedParticles[sorted].ind;
  45504. for (var i = 0; i < lind; i++) {
  45505. this._indices32[sid] = this._indices[sind + i];
  45506. sid++;
  45507. }
  45508. }
  45509. this.mesh.updateIndices(this._indices32);
  45510. }
  45511. }
  45512. if (this._computeBoundingBox) {
  45513. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45514. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45515. }
  45516. this.afterUpdateParticles(start, end, update);
  45517. return this;
  45518. };
  45519. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45520. this._halfroll = this._roll * 0.5;
  45521. this._halfpitch = this._pitch * 0.5;
  45522. this._halfyaw = this._yaw * 0.5;
  45523. this._sinRoll = Math.sin(this._halfroll);
  45524. this._cosRoll = Math.cos(this._halfroll);
  45525. this._sinPitch = Math.sin(this._halfpitch);
  45526. this._cosPitch = Math.cos(this._halfpitch);
  45527. this._sinYaw = Math.sin(this._halfyaw);
  45528. this._cosYaw = Math.cos(this._halfyaw);
  45529. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45530. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45531. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45532. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45533. };
  45534. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45535. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45536. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45537. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45538. this._rotMatrix.m[3] = 0;
  45539. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45540. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45541. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45542. this._rotMatrix.m[7] = 0;
  45543. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45544. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45545. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45546. this._rotMatrix.m[11] = 0;
  45547. this._rotMatrix.m[12] = 0;
  45548. this._rotMatrix.m[13] = 0;
  45549. this._rotMatrix.m[14] = 0;
  45550. this._rotMatrix.m[15] = 1.0;
  45551. };
  45552. /**
  45553. * Disposes the SPS.
  45554. * Returns nothing.
  45555. */
  45556. SolidParticleSystem.prototype.dispose = function () {
  45557. this.mesh.dispose();
  45558. this.vars = null;
  45559. // drop references to internal big arrays for the GC
  45560. this._positions = null;
  45561. this._indices = null;
  45562. this._normals = null;
  45563. this._uvs = null;
  45564. this._colors = null;
  45565. this._indices32 = null;
  45566. this._positions32 = null;
  45567. this._normals32 = null;
  45568. this._fixedNormal32 = null;
  45569. this._uvs32 = null;
  45570. this._colors32 = null;
  45571. this.pickedParticles = null;
  45572. };
  45573. /**
  45574. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45575. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45576. * Returns the SPS.
  45577. */
  45578. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45579. if (!this._isVisibilityBoxLocked) {
  45580. this.mesh.refreshBoundingInfo();
  45581. }
  45582. return this;
  45583. };
  45584. /**
  45585. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45586. * @param size the size (float) of the visibility box
  45587. * note : this doesn't lock the SPS mesh bounding box.
  45588. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45589. */
  45590. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45591. var vis = size / 2;
  45592. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45593. };
  45594. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45595. // getter and setter
  45596. get: function () {
  45597. return this._alwaysVisible;
  45598. },
  45599. /**
  45600. * Sets the SPS as always visible or not
  45601. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45602. */
  45603. set: function (val) {
  45604. this._alwaysVisible = val;
  45605. this.mesh.alwaysSelectAsActiveMesh = val;
  45606. },
  45607. enumerable: true,
  45608. configurable: true
  45609. });
  45610. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45611. get: function () {
  45612. return this._isVisibilityBoxLocked;
  45613. },
  45614. /**
  45615. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45616. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45617. */
  45618. set: function (val) {
  45619. this._isVisibilityBoxLocked = val;
  45620. var boundingInfo = this.mesh.getBoundingInfo();
  45621. if (boundingInfo) {
  45622. boundingInfo.isLocked = val;
  45623. }
  45624. },
  45625. enumerable: true,
  45626. configurable: true
  45627. });
  45628. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45629. // getters
  45630. get: function () {
  45631. return this._computeParticleRotation;
  45632. },
  45633. // Optimizer setters
  45634. /**
  45635. * Tells to `setParticles()` to compute the particle rotations or not.
  45636. * Default value : true. The SPS is faster when it's set to false.
  45637. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45638. */
  45639. set: function (val) {
  45640. this._computeParticleRotation = val;
  45641. },
  45642. enumerable: true,
  45643. configurable: true
  45644. });
  45645. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45646. get: function () {
  45647. return this._computeParticleColor;
  45648. },
  45649. /**
  45650. * Tells to `setParticles()` to compute the particle colors or not.
  45651. * Default value : true. The SPS is faster when it's set to false.
  45652. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45653. */
  45654. set: function (val) {
  45655. this._computeParticleColor = val;
  45656. },
  45657. enumerable: true,
  45658. configurable: true
  45659. });
  45660. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45661. get: function () {
  45662. return this._computeParticleTexture;
  45663. },
  45664. /**
  45665. * Tells to `setParticles()` to compute the particle textures or not.
  45666. * Default value : true. The SPS is faster when it's set to false.
  45667. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45668. */
  45669. set: function (val) {
  45670. this._computeParticleTexture = val;
  45671. },
  45672. enumerable: true,
  45673. configurable: true
  45674. });
  45675. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45676. get: function () {
  45677. return this._computeParticleVertex;
  45678. },
  45679. /**
  45680. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45681. * Default value : false. The SPS is faster when it's set to false.
  45682. * Note : the particle custom vertex positions aren't stored values.
  45683. */
  45684. set: function (val) {
  45685. this._computeParticleVertex = val;
  45686. },
  45687. enumerable: true,
  45688. configurable: true
  45689. });
  45690. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45691. get: function () {
  45692. return this._computeBoundingBox;
  45693. },
  45694. /**
  45695. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45696. */
  45697. set: function (val) {
  45698. this._computeBoundingBox = val;
  45699. },
  45700. enumerable: true,
  45701. configurable: true
  45702. });
  45703. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45704. get: function () {
  45705. return this._depthSortParticles;
  45706. },
  45707. /**
  45708. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45709. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45710. * Default : `true`
  45711. */
  45712. set: function (val) {
  45713. this._depthSortParticles = val;
  45714. },
  45715. enumerable: true,
  45716. configurable: true
  45717. });
  45718. // =======================================================================
  45719. // Particle behavior logic
  45720. // these following methods may be overwritten by the user to fit his needs
  45721. /**
  45722. * This function does nothing. It may be overwritten to set all the particle first values.
  45723. * The SPS doesn't call this function, you may have to call it by your own.
  45724. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45725. */
  45726. SolidParticleSystem.prototype.initParticles = function () {
  45727. };
  45728. /**
  45729. * This function does nothing. It may be overwritten to recycle a particle.
  45730. * The SPS doesn't call this function, you may have to call it by your own.
  45731. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45732. */
  45733. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45734. return particle;
  45735. };
  45736. /**
  45737. * Updates a particle : this function should be overwritten by the user.
  45738. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45739. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45740. * ex : just set a particle position or velocity and recycle conditions
  45741. */
  45742. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45743. return particle;
  45744. };
  45745. /**
  45746. * Updates a vertex of a particle : it can be overwritten by the user.
  45747. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45748. * @param particle the current particle
  45749. * @param vertex the current index of the current particle
  45750. * @param pt the index of the current vertex in the particle shape
  45751. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45752. * ex : just set a vertex particle position
  45753. */
  45754. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45755. return vertex;
  45756. };
  45757. /**
  45758. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45759. * This does nothing and may be overwritten by the user.
  45760. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45761. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45762. * @param update the boolean update value actually passed to setParticles()
  45763. */
  45764. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45765. };
  45766. /**
  45767. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45768. * This will be passed three parameters.
  45769. * This does nothing and may be overwritten by the user.
  45770. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45771. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45772. * @param update the boolean update value actually passed to setParticles()
  45773. */
  45774. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45775. };
  45776. return SolidParticleSystem;
  45777. }());
  45778. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45779. })(BABYLON || (BABYLON = {}));
  45780. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45781. var BABYLON;
  45782. (function (BABYLON) {
  45783. var GroundMesh = /** @class */ (function (_super) {
  45784. __extends(GroundMesh, _super);
  45785. function GroundMesh(name, scene) {
  45786. var _this = _super.call(this, name, scene) || this;
  45787. _this.generateOctree = false;
  45788. return _this;
  45789. }
  45790. GroundMesh.prototype.getClassName = function () {
  45791. return "GroundMesh";
  45792. };
  45793. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45794. get: function () {
  45795. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45796. },
  45797. enumerable: true,
  45798. configurable: true
  45799. });
  45800. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45801. get: function () {
  45802. return this._subdivisionsX;
  45803. },
  45804. enumerable: true,
  45805. configurable: true
  45806. });
  45807. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45808. get: function () {
  45809. return this._subdivisionsY;
  45810. },
  45811. enumerable: true,
  45812. configurable: true
  45813. });
  45814. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45815. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45816. this._subdivisionsX = chunksCount;
  45817. this._subdivisionsY = chunksCount;
  45818. this.subdivide(chunksCount);
  45819. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45820. };
  45821. /**
  45822. * Returns a height (y) value in the Worl system :
  45823. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45824. * Returns the ground y position if (x, z) are outside the ground surface.
  45825. */
  45826. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45827. var world = this.getWorldMatrix();
  45828. var invMat = BABYLON.Tmp.Matrix[5];
  45829. world.invertToRef(invMat);
  45830. var tmpVect = BABYLON.Tmp.Vector3[8];
  45831. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45832. x = tmpVect.x;
  45833. z = tmpVect.z;
  45834. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45835. return this.position.y;
  45836. }
  45837. if (!this._heightQuads || this._heightQuads.length == 0) {
  45838. this._initHeightQuads();
  45839. this._computeHeightQuads();
  45840. }
  45841. var facet = this._getFacetAt(x, z);
  45842. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45843. // return y in the World system
  45844. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45845. return tmpVect.y;
  45846. };
  45847. /**
  45848. * Returns a normalized vector (Vector3) orthogonal to the ground
  45849. * at the ground coordinates (x, z) expressed in the World system.
  45850. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45851. */
  45852. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45853. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45854. this.getNormalAtCoordinatesToRef(x, z, normal);
  45855. return normal;
  45856. };
  45857. /**
  45858. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45859. * at the ground coordinates (x, z) expressed in the World system.
  45860. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45861. * Returns the GroundMesh.
  45862. */
  45863. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45864. var world = this.getWorldMatrix();
  45865. var tmpMat = BABYLON.Tmp.Matrix[5];
  45866. world.invertToRef(tmpMat);
  45867. var tmpVect = BABYLON.Tmp.Vector3[8];
  45868. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45869. x = tmpVect.x;
  45870. z = tmpVect.z;
  45871. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45872. return this;
  45873. }
  45874. if (!this._heightQuads || this._heightQuads.length == 0) {
  45875. this._initHeightQuads();
  45876. this._computeHeightQuads();
  45877. }
  45878. var facet = this._getFacetAt(x, z);
  45879. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45880. return this;
  45881. };
  45882. /**
  45883. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45884. * if the ground has been updated.
  45885. * This can be used in the render loop.
  45886. * Returns the GroundMesh.
  45887. */
  45888. GroundMesh.prototype.updateCoordinateHeights = function () {
  45889. if (!this._heightQuads || this._heightQuads.length == 0) {
  45890. this._initHeightQuads();
  45891. }
  45892. this._computeHeightQuads();
  45893. return this;
  45894. };
  45895. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45896. GroundMesh.prototype._getFacetAt = function (x, z) {
  45897. // retrieve col and row from x, z coordinates in the ground local system
  45898. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45899. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45900. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45901. var facet;
  45902. if (z < quad.slope.x * x + quad.slope.y) {
  45903. facet = quad.facet1;
  45904. }
  45905. else {
  45906. facet = quad.facet2;
  45907. }
  45908. return facet;
  45909. };
  45910. // Creates and populates the heightMap array with "facet" elements :
  45911. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45912. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45913. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45914. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45915. // Returns the GroundMesh.
  45916. GroundMesh.prototype._initHeightQuads = function () {
  45917. var subdivisionsX = this._subdivisionsX;
  45918. var subdivisionsY = this._subdivisionsY;
  45919. this._heightQuads = new Array();
  45920. for (var row = 0; row < subdivisionsY; row++) {
  45921. for (var col = 0; col < subdivisionsX; col++) {
  45922. 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) };
  45923. this._heightQuads[row * subdivisionsX + col] = quad;
  45924. }
  45925. }
  45926. return this;
  45927. };
  45928. // Compute each quad element values and update the the heightMap array :
  45929. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45930. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45931. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45932. // Returns the GroundMesh.
  45933. GroundMesh.prototype._computeHeightQuads = function () {
  45934. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45935. if (!positions) {
  45936. return this;
  45937. }
  45938. var v1 = BABYLON.Tmp.Vector3[3];
  45939. var v2 = BABYLON.Tmp.Vector3[2];
  45940. var v3 = BABYLON.Tmp.Vector3[1];
  45941. var v4 = BABYLON.Tmp.Vector3[0];
  45942. var v1v2 = BABYLON.Tmp.Vector3[4];
  45943. var v1v3 = BABYLON.Tmp.Vector3[5];
  45944. var v1v4 = BABYLON.Tmp.Vector3[6];
  45945. var norm1 = BABYLON.Tmp.Vector3[7];
  45946. var norm2 = BABYLON.Tmp.Vector3[8];
  45947. var i = 0;
  45948. var j = 0;
  45949. var k = 0;
  45950. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45951. var h = 0;
  45952. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45953. var d2 = 0;
  45954. var subdivisionsX = this._subdivisionsX;
  45955. var subdivisionsY = this._subdivisionsY;
  45956. for (var row = 0; row < subdivisionsY; row++) {
  45957. for (var col = 0; col < subdivisionsX; col++) {
  45958. i = col * 3;
  45959. j = row * (subdivisionsX + 1) * 3;
  45960. k = (row + 1) * (subdivisionsX + 1) * 3;
  45961. v1.x = positions[j + i];
  45962. v1.y = positions[j + i + 1];
  45963. v1.z = positions[j + i + 2];
  45964. v2.x = positions[j + i + 3];
  45965. v2.y = positions[j + i + 4];
  45966. v2.z = positions[j + i + 5];
  45967. v3.x = positions[k + i];
  45968. v3.y = positions[k + i + 1];
  45969. v3.z = positions[k + i + 2];
  45970. v4.x = positions[k + i + 3];
  45971. v4.y = positions[k + i + 4];
  45972. v4.z = positions[k + i + 5];
  45973. // 2D slope V1V4
  45974. cd = (v4.z - v1.z) / (v4.x - v1.x);
  45975. h = v1.z - cd * v1.x; // v1 belongs to the slope
  45976. // facet equations :
  45977. // we compute each facet normal vector
  45978. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  45979. // we compute the value d by applying the equation to v1 which belongs to the plane
  45980. // then we store the facet equation in a Vector4
  45981. v2.subtractToRef(v1, v1v2);
  45982. v3.subtractToRef(v1, v1v3);
  45983. v4.subtractToRef(v1, v1v4);
  45984. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  45985. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  45986. norm1.normalize();
  45987. norm2.normalize();
  45988. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  45989. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  45990. var quad = this._heightQuads[row * subdivisionsX + col];
  45991. quad.slope.copyFromFloats(cd, h);
  45992. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  45993. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  45994. }
  45995. }
  45996. return this;
  45997. };
  45998. GroundMesh.prototype.serialize = function (serializationObject) {
  45999. _super.prototype.serialize.call(this, serializationObject);
  46000. serializationObject.subdivisionsX = this._subdivisionsX;
  46001. serializationObject.subdivisionsY = this._subdivisionsY;
  46002. serializationObject.minX = this._minX;
  46003. serializationObject.maxX = this._maxX;
  46004. serializationObject.minZ = this._minZ;
  46005. serializationObject.maxZ = this._maxZ;
  46006. serializationObject.width = this._width;
  46007. serializationObject.height = this._height;
  46008. };
  46009. GroundMesh.Parse = function (parsedMesh, scene) {
  46010. var result = new GroundMesh(parsedMesh.name, scene);
  46011. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  46012. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  46013. result._minX = parsedMesh.minX;
  46014. result._maxX = parsedMesh.maxX;
  46015. result._minZ = parsedMesh.minZ;
  46016. result._maxZ = parsedMesh.maxZ;
  46017. result._width = parsedMesh.width;
  46018. result._height = parsedMesh.height;
  46019. return result;
  46020. };
  46021. return GroundMesh;
  46022. }(BABYLON.Mesh));
  46023. BABYLON.GroundMesh = GroundMesh;
  46024. })(BABYLON || (BABYLON = {}));
  46025. //# sourceMappingURL=babylon.groundMesh.js.map
  46026. var BABYLON;
  46027. (function (BABYLON) {
  46028. /**
  46029. * Creates an instance based on a source mesh.
  46030. */
  46031. var InstancedMesh = /** @class */ (function (_super) {
  46032. __extends(InstancedMesh, _super);
  46033. function InstancedMesh(name, source) {
  46034. var _this = _super.call(this, name, source.getScene()) || this;
  46035. source.instances.push(_this);
  46036. _this._sourceMesh = source;
  46037. _this.position.copyFrom(source.position);
  46038. _this.rotation.copyFrom(source.rotation);
  46039. _this.scaling.copyFrom(source.scaling);
  46040. if (source.rotationQuaternion) {
  46041. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46042. }
  46043. _this.infiniteDistance = source.infiniteDistance;
  46044. _this.setPivotMatrix(source.getPivotMatrix());
  46045. _this.refreshBoundingInfo();
  46046. _this._syncSubMeshes();
  46047. return _this;
  46048. }
  46049. /**
  46050. * Returns the string "InstancedMesh".
  46051. */
  46052. InstancedMesh.prototype.getClassName = function () {
  46053. return "InstancedMesh";
  46054. };
  46055. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46056. // Methods
  46057. get: function () {
  46058. return this._sourceMesh.receiveShadows;
  46059. },
  46060. enumerable: true,
  46061. configurable: true
  46062. });
  46063. Object.defineProperty(InstancedMesh.prototype, "material", {
  46064. get: function () {
  46065. return this._sourceMesh.material;
  46066. },
  46067. enumerable: true,
  46068. configurable: true
  46069. });
  46070. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46071. get: function () {
  46072. return this._sourceMesh.visibility;
  46073. },
  46074. enumerable: true,
  46075. configurable: true
  46076. });
  46077. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46078. get: function () {
  46079. return this._sourceMesh.skeleton;
  46080. },
  46081. enumerable: true,
  46082. configurable: true
  46083. });
  46084. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46085. get: function () {
  46086. return this._sourceMesh.renderingGroupId;
  46087. },
  46088. enumerable: true,
  46089. configurable: true
  46090. });
  46091. /**
  46092. * Returns the total number of vertices (integer).
  46093. */
  46094. InstancedMesh.prototype.getTotalVertices = function () {
  46095. return this._sourceMesh.getTotalVertices();
  46096. };
  46097. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46098. get: function () {
  46099. return this._sourceMesh;
  46100. },
  46101. enumerable: true,
  46102. configurable: true
  46103. });
  46104. /**
  46105. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46106. */
  46107. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46108. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46109. };
  46110. /**
  46111. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46112. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46113. * The `data` are either a numeric array either a Float32Array.
  46114. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46115. * 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).
  46116. * Note that a new underlying VertexBuffer object is created each call.
  46117. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46118. *
  46119. * Possible `kind` values :
  46120. * - BABYLON.VertexBuffer.PositionKind
  46121. * - BABYLON.VertexBuffer.UVKind
  46122. * - BABYLON.VertexBuffer.UV2Kind
  46123. * - BABYLON.VertexBuffer.UV3Kind
  46124. * - BABYLON.VertexBuffer.UV4Kind
  46125. * - BABYLON.VertexBuffer.UV5Kind
  46126. * - BABYLON.VertexBuffer.UV6Kind
  46127. * - BABYLON.VertexBuffer.ColorKind
  46128. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46129. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46130. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46131. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46132. *
  46133. * Returns the Mesh.
  46134. */
  46135. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46136. if (this.sourceMesh) {
  46137. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46138. }
  46139. return this.sourceMesh;
  46140. };
  46141. /**
  46142. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46143. * If the mesh has no geometry, it is simply returned as it is.
  46144. * The `data` are either a numeric array either a Float32Array.
  46145. * No new underlying VertexBuffer object is created.
  46146. * 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.
  46147. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46148. *
  46149. * Possible `kind` values :
  46150. * - BABYLON.VertexBuffer.PositionKind
  46151. * - BABYLON.VertexBuffer.UVKind
  46152. * - BABYLON.VertexBuffer.UV2Kind
  46153. * - BABYLON.VertexBuffer.UV3Kind
  46154. * - BABYLON.VertexBuffer.UV4Kind
  46155. * - BABYLON.VertexBuffer.UV5Kind
  46156. * - BABYLON.VertexBuffer.UV6Kind
  46157. * - BABYLON.VertexBuffer.ColorKind
  46158. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46159. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46160. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46161. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46162. *
  46163. * Returns the Mesh.
  46164. */
  46165. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46166. if (this.sourceMesh) {
  46167. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46168. }
  46169. return this.sourceMesh;
  46170. };
  46171. /**
  46172. * Sets the mesh indices.
  46173. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46174. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46175. * This method creates a new index buffer each call.
  46176. * Returns the Mesh.
  46177. */
  46178. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46179. if (totalVertices === void 0) { totalVertices = null; }
  46180. if (this.sourceMesh) {
  46181. this.sourceMesh.setIndices(indices, totalVertices);
  46182. }
  46183. return this.sourceMesh;
  46184. };
  46185. /**
  46186. * Boolean : True if the mesh owns the requested kind of data.
  46187. */
  46188. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46189. return this._sourceMesh.isVerticesDataPresent(kind);
  46190. };
  46191. /**
  46192. * Returns an array of indices (IndicesArray).
  46193. */
  46194. InstancedMesh.prototype.getIndices = function () {
  46195. return this._sourceMesh.getIndices();
  46196. };
  46197. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46198. get: function () {
  46199. return this._sourceMesh._positions;
  46200. },
  46201. enumerable: true,
  46202. configurable: true
  46203. });
  46204. /**
  46205. * Sets a new updated BoundingInfo to the mesh.
  46206. * Returns the mesh.
  46207. */
  46208. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46209. var meshBB = this._sourceMesh.getBoundingInfo();
  46210. if (meshBB) {
  46211. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46212. }
  46213. this._updateBoundingInfo();
  46214. return this;
  46215. };
  46216. InstancedMesh.prototype._preActivate = function () {
  46217. if (this._currentLOD) {
  46218. this._currentLOD._preActivate();
  46219. }
  46220. return this;
  46221. };
  46222. InstancedMesh.prototype._activate = function (renderId) {
  46223. if (this._currentLOD) {
  46224. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46225. }
  46226. return this;
  46227. };
  46228. /**
  46229. * Returns the current associated LOD AbstractMesh.
  46230. */
  46231. InstancedMesh.prototype.getLOD = function (camera) {
  46232. if (!camera) {
  46233. return this;
  46234. }
  46235. var boundingInfo = this.getBoundingInfo();
  46236. if (!boundingInfo) {
  46237. return this;
  46238. }
  46239. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46240. if (this._currentLOD === this.sourceMesh) {
  46241. return this;
  46242. }
  46243. return this._currentLOD;
  46244. };
  46245. InstancedMesh.prototype._syncSubMeshes = function () {
  46246. this.releaseSubMeshes();
  46247. if (this._sourceMesh.subMeshes) {
  46248. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46249. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46250. }
  46251. }
  46252. return this;
  46253. };
  46254. InstancedMesh.prototype._generatePointsArray = function () {
  46255. return this._sourceMesh._generatePointsArray();
  46256. };
  46257. /**
  46258. * Creates a new InstancedMesh from the current mesh.
  46259. * - name (string) : the cloned mesh name
  46260. * - newParent (optional Node) : the optional Node to parent the clone to.
  46261. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46262. *
  46263. * Returns the clone.
  46264. */
  46265. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46266. var result = this._sourceMesh.createInstance(name);
  46267. // Deep copy
  46268. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46269. // Bounding info
  46270. this.refreshBoundingInfo();
  46271. // Parent
  46272. if (newParent) {
  46273. result.parent = newParent;
  46274. }
  46275. if (!doNotCloneChildren) {
  46276. // Children
  46277. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46278. var mesh = this.getScene().meshes[index];
  46279. if (mesh.parent === this) {
  46280. mesh.clone(mesh.name, result);
  46281. }
  46282. }
  46283. }
  46284. result.computeWorldMatrix(true);
  46285. return result;
  46286. };
  46287. /**
  46288. * Disposes the InstancedMesh.
  46289. * Returns nothing.
  46290. */
  46291. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46292. // Remove from mesh
  46293. var index = this._sourceMesh.instances.indexOf(this);
  46294. this._sourceMesh.instances.splice(index, 1);
  46295. _super.prototype.dispose.call(this, doNotRecurse);
  46296. };
  46297. return InstancedMesh;
  46298. }(BABYLON.AbstractMesh));
  46299. BABYLON.InstancedMesh = InstancedMesh;
  46300. })(BABYLON || (BABYLON = {}));
  46301. //# sourceMappingURL=babylon.instancedMesh.js.map
  46302. var BABYLON;
  46303. (function (BABYLON) {
  46304. var LinesMesh = /** @class */ (function (_super) {
  46305. __extends(LinesMesh, _super);
  46306. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46307. if (scene === void 0) { scene = null; }
  46308. if (parent === void 0) { parent = null; }
  46309. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46310. _this.useVertexColor = useVertexColor;
  46311. _this.color = new BABYLON.Color3(1, 1, 1);
  46312. _this.alpha = 1;
  46313. if (source) {
  46314. _this.color = source.color.clone();
  46315. _this.alpha = source.alpha;
  46316. _this.useVertexColor = source.useVertexColor;
  46317. }
  46318. _this._intersectionThreshold = 0.1;
  46319. var options = {
  46320. attributes: [BABYLON.VertexBuffer.PositionKind],
  46321. uniforms: ["world", "viewProjection"],
  46322. needAlphaBlending: false,
  46323. };
  46324. if (!useVertexColor) {
  46325. options.uniforms.push("color");
  46326. options.needAlphaBlending = true;
  46327. }
  46328. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46329. return _this;
  46330. }
  46331. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46332. /**
  46333. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46334. * This margin is expressed in world space coordinates, so its value may vary.
  46335. * Default value is 0.1
  46336. * @returns the intersection Threshold value.
  46337. */
  46338. get: function () {
  46339. return this._intersectionThreshold;
  46340. },
  46341. /**
  46342. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46343. * This margin is expressed in world space coordinates, so its value may vary.
  46344. * @param value the new threshold to apply
  46345. */
  46346. set: function (value) {
  46347. if (this._intersectionThreshold === value) {
  46348. return;
  46349. }
  46350. this._intersectionThreshold = value;
  46351. if (this.geometry) {
  46352. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46353. }
  46354. },
  46355. enumerable: true,
  46356. configurable: true
  46357. });
  46358. /**
  46359. * Returns the string "LineMesh"
  46360. */
  46361. LinesMesh.prototype.getClassName = function () {
  46362. return "LinesMesh";
  46363. };
  46364. Object.defineProperty(LinesMesh.prototype, "material", {
  46365. get: function () {
  46366. return this._colorShader;
  46367. },
  46368. set: function (value) {
  46369. // Do nothing
  46370. },
  46371. enumerable: true,
  46372. configurable: true
  46373. });
  46374. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46375. get: function () {
  46376. return false;
  46377. },
  46378. enumerable: true,
  46379. configurable: true
  46380. });
  46381. LinesMesh.prototype.createInstance = function (name) {
  46382. throw new Error("LinesMeshes do not support createInstance.");
  46383. };
  46384. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46385. if (!this._geometry) {
  46386. return this;
  46387. }
  46388. // VBOs
  46389. this._geometry._bind(this._colorShader.getEffect());
  46390. // Color
  46391. if (!this.useVertexColor) {
  46392. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46393. }
  46394. return this;
  46395. };
  46396. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46397. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46398. return this;
  46399. }
  46400. var engine = this.getScene().getEngine();
  46401. // Draw order
  46402. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46403. return this;
  46404. };
  46405. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46406. this._colorShader.dispose();
  46407. _super.prototype.dispose.call(this, doNotRecurse);
  46408. };
  46409. /**
  46410. * Returns a new LineMesh object cloned from the current one.
  46411. */
  46412. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46413. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46414. };
  46415. return LinesMesh;
  46416. }(BABYLON.Mesh));
  46417. BABYLON.LinesMesh = LinesMesh;
  46418. })(BABYLON || (BABYLON = {}));
  46419. //# sourceMappingURL=babylon.linesMesh.js.map
  46420. var BABYLON;
  46421. (function (BABYLON) {
  46422. var ShaderMaterial = /** @class */ (function (_super) {
  46423. __extends(ShaderMaterial, _super);
  46424. function ShaderMaterial(name, scene, shaderPath, options) {
  46425. var _this = _super.call(this, name, scene) || this;
  46426. _this._textures = {};
  46427. _this._textureArrays = {};
  46428. _this._floats = {};
  46429. _this._floatsArrays = {};
  46430. _this._colors3 = {};
  46431. _this._colors3Arrays = {};
  46432. _this._colors4 = {};
  46433. _this._vectors2 = {};
  46434. _this._vectors3 = {};
  46435. _this._vectors4 = {};
  46436. _this._matrices = {};
  46437. _this._matrices3x3 = {};
  46438. _this._matrices2x2 = {};
  46439. _this._vectors3Arrays = {};
  46440. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46441. _this._shaderPath = shaderPath;
  46442. options.needAlphaBlending = options.needAlphaBlending || false;
  46443. options.needAlphaTesting = options.needAlphaTesting || false;
  46444. options.attributes = options.attributes || ["position", "normal", "uv"];
  46445. options.uniforms = options.uniforms || ["worldViewProjection"];
  46446. options.uniformBuffers = options.uniformBuffers || [];
  46447. options.samplers = options.samplers || [];
  46448. options.defines = options.defines || [];
  46449. _this._options = options;
  46450. return _this;
  46451. }
  46452. ShaderMaterial.prototype.getClassName = function () {
  46453. return "ShaderMaterial";
  46454. };
  46455. ShaderMaterial.prototype.needAlphaBlending = function () {
  46456. return this._options.needAlphaBlending;
  46457. };
  46458. ShaderMaterial.prototype.needAlphaTesting = function () {
  46459. return this._options.needAlphaTesting;
  46460. };
  46461. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46462. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46463. this._options.uniforms.push(uniformName);
  46464. }
  46465. };
  46466. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46467. if (this._options.samplers.indexOf(name) === -1) {
  46468. this._options.samplers.push(name);
  46469. }
  46470. this._textures[name] = texture;
  46471. return this;
  46472. };
  46473. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46474. if (this._options.samplers.indexOf(name) === -1) {
  46475. this._options.samplers.push(name);
  46476. }
  46477. this._checkUniform(name);
  46478. this._textureArrays[name] = textures;
  46479. return this;
  46480. };
  46481. ShaderMaterial.prototype.setFloat = function (name, value) {
  46482. this._checkUniform(name);
  46483. this._floats[name] = value;
  46484. return this;
  46485. };
  46486. ShaderMaterial.prototype.setFloats = function (name, value) {
  46487. this._checkUniform(name);
  46488. this._floatsArrays[name] = value;
  46489. return this;
  46490. };
  46491. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46492. this._checkUniform(name);
  46493. this._colors3[name] = value;
  46494. return this;
  46495. };
  46496. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46497. this._checkUniform(name);
  46498. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46499. color.toArray(arr, arr.length);
  46500. return arr;
  46501. }, []);
  46502. return this;
  46503. };
  46504. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46505. this._checkUniform(name);
  46506. this._colors4[name] = value;
  46507. return this;
  46508. };
  46509. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46510. this._checkUniform(name);
  46511. this._vectors2[name] = value;
  46512. return this;
  46513. };
  46514. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46515. this._checkUniform(name);
  46516. this._vectors3[name] = value;
  46517. return this;
  46518. };
  46519. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46520. this._checkUniform(name);
  46521. this._vectors4[name] = value;
  46522. return this;
  46523. };
  46524. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46525. this._checkUniform(name);
  46526. this._matrices[name] = value;
  46527. return this;
  46528. };
  46529. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46530. this._checkUniform(name);
  46531. this._matrices3x3[name] = value;
  46532. return this;
  46533. };
  46534. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46535. this._checkUniform(name);
  46536. this._matrices2x2[name] = value;
  46537. return this;
  46538. };
  46539. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46540. this._checkUniform(name);
  46541. this._vectors3Arrays[name] = value;
  46542. return this;
  46543. };
  46544. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46545. if (!mesh) {
  46546. return true;
  46547. }
  46548. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46549. return false;
  46550. }
  46551. return false;
  46552. };
  46553. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46554. var scene = this.getScene();
  46555. var engine = scene.getEngine();
  46556. if (!this.checkReadyOnEveryCall) {
  46557. if (this._renderId === scene.getRenderId()) {
  46558. if (this._checkCache(scene, mesh, useInstances)) {
  46559. return true;
  46560. }
  46561. }
  46562. }
  46563. // Instances
  46564. var defines = [];
  46565. var attribs = [];
  46566. var fallbacks = new BABYLON.EffectFallbacks();
  46567. if (useInstances) {
  46568. defines.push("#define INSTANCES");
  46569. }
  46570. for (var index = 0; index < this._options.defines.length; index++) {
  46571. defines.push(this._options.defines[index]);
  46572. }
  46573. for (var index = 0; index < this._options.attributes.length; index++) {
  46574. attribs.push(this._options.attributes[index]);
  46575. }
  46576. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46577. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46578. defines.push("#define VERTEXCOLOR");
  46579. }
  46580. // Bones
  46581. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46582. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46583. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46584. if (mesh.numBoneInfluencers > 4) {
  46585. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46586. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46587. }
  46588. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46589. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46590. fallbacks.addCPUSkinningFallback(0, mesh);
  46591. if (this._options.uniforms.indexOf("mBones") === -1) {
  46592. this._options.uniforms.push("mBones");
  46593. }
  46594. }
  46595. else {
  46596. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46597. }
  46598. // Textures
  46599. for (var name in this._textures) {
  46600. if (!this._textures[name].isReady()) {
  46601. return false;
  46602. }
  46603. }
  46604. // Alpha test
  46605. if (engine.getAlphaTesting()) {
  46606. defines.push("#define ALPHATEST");
  46607. }
  46608. var previousEffect = this._effect;
  46609. var join = defines.join("\n");
  46610. this._effect = engine.createEffect(this._shaderPath, {
  46611. attributes: attribs,
  46612. uniformsNames: this._options.uniforms,
  46613. uniformBuffersNames: this._options.uniformBuffers,
  46614. samplers: this._options.samplers,
  46615. defines: join,
  46616. fallbacks: fallbacks,
  46617. onCompiled: this.onCompiled,
  46618. onError: this.onError
  46619. }, engine);
  46620. if (!this._effect.isReady()) {
  46621. return false;
  46622. }
  46623. if (previousEffect !== this._effect) {
  46624. scene.resetCachedMaterial();
  46625. }
  46626. this._renderId = scene.getRenderId();
  46627. return true;
  46628. };
  46629. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46630. var scene = this.getScene();
  46631. if (!this._effect) {
  46632. return;
  46633. }
  46634. if (this._options.uniforms.indexOf("world") !== -1) {
  46635. this._effect.setMatrix("world", world);
  46636. }
  46637. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46638. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46639. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46640. }
  46641. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46642. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46643. }
  46644. };
  46645. ShaderMaterial.prototype.bind = function (world, mesh) {
  46646. // Std values
  46647. this.bindOnlyWorldMatrix(world);
  46648. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46649. if (this._options.uniforms.indexOf("view") !== -1) {
  46650. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46651. }
  46652. if (this._options.uniforms.indexOf("projection") !== -1) {
  46653. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46654. }
  46655. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46656. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46657. }
  46658. // Bones
  46659. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46660. var name;
  46661. // Texture
  46662. for (name in this._textures) {
  46663. this._effect.setTexture(name, this._textures[name]);
  46664. }
  46665. // Texture arrays
  46666. for (name in this._textureArrays) {
  46667. this._effect.setTextureArray(name, this._textureArrays[name]);
  46668. }
  46669. // Float
  46670. for (name in this._floats) {
  46671. this._effect.setFloat(name, this._floats[name]);
  46672. }
  46673. // Float s
  46674. for (name in this._floatsArrays) {
  46675. this._effect.setArray(name, this._floatsArrays[name]);
  46676. }
  46677. // Color3
  46678. for (name in this._colors3) {
  46679. this._effect.setColor3(name, this._colors3[name]);
  46680. }
  46681. for (name in this._colors3Arrays) {
  46682. this._effect.setArray3(name, this._colors3Arrays[name]);
  46683. }
  46684. // Color4
  46685. for (name in this._colors4) {
  46686. var color = this._colors4[name];
  46687. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46688. }
  46689. // Vector2
  46690. for (name in this._vectors2) {
  46691. this._effect.setVector2(name, this._vectors2[name]);
  46692. }
  46693. // Vector3
  46694. for (name in this._vectors3) {
  46695. this._effect.setVector3(name, this._vectors3[name]);
  46696. }
  46697. // Vector4
  46698. for (name in this._vectors4) {
  46699. this._effect.setVector4(name, this._vectors4[name]);
  46700. }
  46701. // Matrix
  46702. for (name in this._matrices) {
  46703. this._effect.setMatrix(name, this._matrices[name]);
  46704. }
  46705. // Matrix 3x3
  46706. for (name in this._matrices3x3) {
  46707. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46708. }
  46709. // Matrix 2x2
  46710. for (name in this._matrices2x2) {
  46711. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46712. }
  46713. // Vector3Array
  46714. for (name in this._vectors3Arrays) {
  46715. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46716. }
  46717. }
  46718. this._afterBind(mesh);
  46719. };
  46720. ShaderMaterial.prototype.getActiveTextures = function () {
  46721. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46722. for (var name in this._textures) {
  46723. activeTextures.push(this._textures[name]);
  46724. }
  46725. for (var name in this._textureArrays) {
  46726. var array = this._textureArrays[name];
  46727. for (var index = 0; index < array.length; index++) {
  46728. activeTextures.push(array[index]);
  46729. }
  46730. }
  46731. return activeTextures;
  46732. };
  46733. ShaderMaterial.prototype.hasTexture = function (texture) {
  46734. if (_super.prototype.hasTexture.call(this, texture)) {
  46735. return true;
  46736. }
  46737. for (var name in this._textures) {
  46738. if (this._textures[name] === texture) {
  46739. return true;
  46740. }
  46741. }
  46742. for (var name in this._textureArrays) {
  46743. var array = this._textureArrays[name];
  46744. for (var index = 0; index < array.length; index++) {
  46745. if (array[index] === texture) {
  46746. return true;
  46747. }
  46748. }
  46749. }
  46750. return false;
  46751. };
  46752. ShaderMaterial.prototype.clone = function (name) {
  46753. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46754. return newShaderMaterial;
  46755. };
  46756. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46757. if (forceDisposeTextures) {
  46758. var name;
  46759. for (name in this._textures) {
  46760. this._textures[name].dispose();
  46761. }
  46762. for (name in this._textureArrays) {
  46763. var array = this._textureArrays[name];
  46764. for (var index = 0; index < array.length; index++) {
  46765. array[index].dispose();
  46766. }
  46767. }
  46768. }
  46769. this._textures = {};
  46770. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46771. };
  46772. ShaderMaterial.prototype.serialize = function () {
  46773. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46774. serializationObject.customType = "BABYLON.ShaderMaterial";
  46775. serializationObject.options = this._options;
  46776. serializationObject.shaderPath = this._shaderPath;
  46777. var name;
  46778. // Texture
  46779. serializationObject.textures = {};
  46780. for (name in this._textures) {
  46781. serializationObject.textures[name] = this._textures[name].serialize();
  46782. }
  46783. // Texture arrays
  46784. serializationObject.textureArrays = {};
  46785. for (name in this._textureArrays) {
  46786. serializationObject.textureArrays[name] = [];
  46787. var array = this._textureArrays[name];
  46788. for (var index = 0; index < array.length; index++) {
  46789. serializationObject.textureArrays[name].push(array[index].serialize());
  46790. }
  46791. }
  46792. // Float
  46793. serializationObject.floats = {};
  46794. for (name in this._floats) {
  46795. serializationObject.floats[name] = this._floats[name];
  46796. }
  46797. // Float s
  46798. serializationObject.FloatArrays = {};
  46799. for (name in this._floatsArrays) {
  46800. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46801. }
  46802. // Color3
  46803. serializationObject.colors3 = {};
  46804. for (name in this._colors3) {
  46805. serializationObject.colors3[name] = this._colors3[name].asArray();
  46806. }
  46807. // Color3 array
  46808. serializationObject.colors3Arrays = {};
  46809. for (name in this._colors3Arrays) {
  46810. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46811. }
  46812. // Color4
  46813. serializationObject.colors4 = {};
  46814. for (name in this._colors4) {
  46815. serializationObject.colors4[name] = this._colors4[name].asArray();
  46816. }
  46817. // Vector2
  46818. serializationObject.vectors2 = {};
  46819. for (name in this._vectors2) {
  46820. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46821. }
  46822. // Vector3
  46823. serializationObject.vectors3 = {};
  46824. for (name in this._vectors3) {
  46825. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46826. }
  46827. // Vector4
  46828. serializationObject.vectors4 = {};
  46829. for (name in this._vectors4) {
  46830. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46831. }
  46832. // Matrix
  46833. serializationObject.matrices = {};
  46834. for (name in this._matrices) {
  46835. serializationObject.matrices[name] = this._matrices[name].asArray();
  46836. }
  46837. // Matrix 3x3
  46838. serializationObject.matrices3x3 = {};
  46839. for (name in this._matrices3x3) {
  46840. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46841. }
  46842. // Matrix 2x2
  46843. serializationObject.matrices2x2 = {};
  46844. for (name in this._matrices2x2) {
  46845. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46846. }
  46847. // Vector3Array
  46848. serializationObject.vectors3Arrays = {};
  46849. for (name in this._vectors3Arrays) {
  46850. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46851. }
  46852. return serializationObject;
  46853. };
  46854. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46855. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46856. var name;
  46857. // Texture
  46858. for (name in source.textures) {
  46859. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46860. }
  46861. // Texture arrays
  46862. for (name in source.textureArrays) {
  46863. var array = source.textureArrays[name];
  46864. var textureArray = new Array();
  46865. for (var index = 0; index < array.length; index++) {
  46866. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46867. }
  46868. material.setTextureArray(name, textureArray);
  46869. }
  46870. // Float
  46871. for (name in source.floats) {
  46872. material.setFloat(name, source.floats[name]);
  46873. }
  46874. // Float s
  46875. for (name in source.floatsArrays) {
  46876. material.setFloats(name, source.floatsArrays[name]);
  46877. }
  46878. // Color3
  46879. for (name in source.colors3) {
  46880. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46881. }
  46882. // Color3 arrays
  46883. for (name in source.colors3Arrays) {
  46884. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46885. if (i % 3 === 0) {
  46886. arr.push([num]);
  46887. }
  46888. else {
  46889. arr[arr.length - 1].push(num);
  46890. }
  46891. return arr;
  46892. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46893. material.setColor3Array(name, colors);
  46894. }
  46895. // Color4
  46896. for (name in source.colors4) {
  46897. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46898. }
  46899. // Vector2
  46900. for (name in source.vectors2) {
  46901. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46902. }
  46903. // Vector3
  46904. for (name in source.vectors3) {
  46905. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46906. }
  46907. // Vector4
  46908. for (name in source.vectors4) {
  46909. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46910. }
  46911. // Matrix
  46912. for (name in source.matrices) {
  46913. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46914. }
  46915. // Matrix 3x3
  46916. for (name in source.matrices3x3) {
  46917. material.setMatrix3x3(name, source.matrices3x3[name]);
  46918. }
  46919. // Matrix 2x2
  46920. for (name in source.matrices2x2) {
  46921. material.setMatrix2x2(name, source.matrices2x2[name]);
  46922. }
  46923. // Vector3Array
  46924. for (name in source.vectors3Arrays) {
  46925. material.setArray3(name, source.vectors3Arrays[name]);
  46926. }
  46927. return material;
  46928. };
  46929. return ShaderMaterial;
  46930. }(BABYLON.Material));
  46931. BABYLON.ShaderMaterial = ShaderMaterial;
  46932. })(BABYLON || (BABYLON = {}));
  46933. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46934. var BABYLON;
  46935. (function (BABYLON) {
  46936. var MeshBuilder = /** @class */ (function () {
  46937. function MeshBuilder() {
  46938. }
  46939. MeshBuilder.updateSideOrientation = function (orientation) {
  46940. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46941. return BABYLON.Mesh.DOUBLESIDE;
  46942. }
  46943. if (orientation === undefined || orientation === null) {
  46944. return BABYLON.Mesh.FRONTSIDE;
  46945. }
  46946. return orientation;
  46947. };
  46948. /**
  46949. * Creates a box mesh.
  46950. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46951. * The parameter `size` sets the size (float) of each box side (default 1).
  46952. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46953. * 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).
  46954. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46955. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46956. * 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).
  46957. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46959. */
  46960. MeshBuilder.CreateBox = function (name, options, scene) {
  46961. if (scene === void 0) { scene = null; }
  46962. var box = new BABYLON.Mesh(name, scene);
  46963. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46964. box._originalBuilderSideOrientation = options.sideOrientation;
  46965. var vertexData = BABYLON.VertexData.CreateBox(options);
  46966. vertexData.applyToMesh(box, options.updatable);
  46967. return box;
  46968. };
  46969. /**
  46970. * Creates a sphere mesh.
  46971. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  46972. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  46973. * 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`).
  46974. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  46975. * 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
  46976. * 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).
  46977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46978. * 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).
  46979. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46981. */
  46982. MeshBuilder.CreateSphere = function (name, options, scene) {
  46983. var sphere = new BABYLON.Mesh(name, scene);
  46984. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46985. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46986. var vertexData = BABYLON.VertexData.CreateSphere(options);
  46987. vertexData.applyToMesh(sphere, options.updatable);
  46988. return sphere;
  46989. };
  46990. /**
  46991. * Creates a plane polygonal mesh. By default, this is a disc.
  46992. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  46993. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  46994. * 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.
  46995. * 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
  46996. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46997. * 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).
  46998. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47000. */
  47001. MeshBuilder.CreateDisc = function (name, options, scene) {
  47002. if (scene === void 0) { scene = null; }
  47003. var disc = new BABYLON.Mesh(name, scene);
  47004. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47005. disc._originalBuilderSideOrientation = options.sideOrientation;
  47006. var vertexData = BABYLON.VertexData.CreateDisc(options);
  47007. vertexData.applyToMesh(disc, options.updatable);
  47008. return disc;
  47009. };
  47010. /**
  47011. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  47012. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  47013. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  47014. * 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`).
  47015. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  47016. * 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.
  47017. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47018. * 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).
  47019. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47021. */
  47022. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  47023. var sphere = new BABYLON.Mesh(name, scene);
  47024. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47025. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47026. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  47027. vertexData.applyToMesh(sphere, options.updatable);
  47028. return sphere;
  47029. };
  47030. ;
  47031. /**
  47032. * Creates a ribbon mesh.
  47033. * 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.
  47034. *
  47035. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47036. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47037. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47038. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47039. * 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.
  47040. * 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.
  47041. * 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
  47042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47043. * 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).
  47044. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47045. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47046. * 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.
  47047. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47048. * 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
  47049. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47050. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47052. */
  47053. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47054. if (scene === void 0) { scene = null; }
  47055. var pathArray = options.pathArray;
  47056. var closeArray = options.closeArray;
  47057. var closePath = options.closePath;
  47058. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47059. var instance = options.instance;
  47060. var updatable = options.updatable;
  47061. if (instance) {
  47062. // positionFunction : ribbon case
  47063. // only pathArray and sideOrientation parameters are taken into account for positions update
  47064. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47065. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47066. var positionFunction = function (positions) {
  47067. var minlg = pathArray[0].length;
  47068. var i = 0;
  47069. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47070. for (var si = 1; si <= ns; si++) {
  47071. for (var p = 0; p < pathArray.length; p++) {
  47072. var path = pathArray[p];
  47073. var l = path.length;
  47074. minlg = (minlg < l) ? minlg : l;
  47075. var j = 0;
  47076. while (j < minlg) {
  47077. positions[i] = path[j].x;
  47078. positions[i + 1] = path[j].y;
  47079. positions[i + 2] = path[j].z;
  47080. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47081. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47082. }
  47083. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47084. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47085. }
  47086. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47087. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47088. }
  47089. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47090. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47091. }
  47092. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47093. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47094. }
  47095. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47096. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47097. }
  47098. j++;
  47099. i += 3;
  47100. }
  47101. if (instance._closePath) {
  47102. positions[i] = path[0].x;
  47103. positions[i + 1] = path[0].y;
  47104. positions[i + 2] = path[0].z;
  47105. i += 3;
  47106. }
  47107. }
  47108. }
  47109. };
  47110. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47111. positionFunction(positions);
  47112. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47113. instance._boundingInfo.update(instance._worldMatrix);
  47114. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47115. if (options.colors) {
  47116. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47117. for (var c = 0; c < options.colors.length; c++) {
  47118. colors[c * 4] = options.colors[c].r;
  47119. colors[c * 4 + 1] = options.colors[c].g;
  47120. colors[c * 4 + 2] = options.colors[c].b;
  47121. colors[c * 4 + 3] = options.colors[c].a;
  47122. }
  47123. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47124. }
  47125. if (options.uvs) {
  47126. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47127. for (var i = 0; i < options.uvs.length; i++) {
  47128. uvs[i * 2] = options.uvs[i].x;
  47129. uvs[i * 2 + 1] = options.uvs[i].y;
  47130. }
  47131. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47132. }
  47133. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47134. var indices = instance.getIndices();
  47135. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47136. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47137. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47138. if (instance._closePath) {
  47139. var indexFirst = 0;
  47140. var indexLast = 0;
  47141. for (var p = 0; p < pathArray.length; p++) {
  47142. indexFirst = instance._idx[p] * 3;
  47143. if (p + 1 < pathArray.length) {
  47144. indexLast = (instance._idx[p + 1] - 1) * 3;
  47145. }
  47146. else {
  47147. indexLast = normals.length - 3;
  47148. }
  47149. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47150. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47151. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47152. normals[indexLast] = normals[indexFirst];
  47153. normals[indexLast + 1] = normals[indexFirst + 1];
  47154. normals[indexLast + 2] = normals[indexFirst + 2];
  47155. }
  47156. }
  47157. if (!(instance.areNormalsFrozen)) {
  47158. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47159. }
  47160. }
  47161. return instance;
  47162. }
  47163. else {
  47164. var ribbon = new BABYLON.Mesh(name, scene);
  47165. ribbon._originalBuilderSideOrientation = sideOrientation;
  47166. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47167. if (closePath) {
  47168. ribbon._idx = vertexData._idx;
  47169. }
  47170. ribbon._closePath = closePath;
  47171. ribbon._closeArray = closeArray;
  47172. vertexData.applyToMesh(ribbon, updatable);
  47173. return ribbon;
  47174. }
  47175. };
  47176. /**
  47177. * Creates a cylinder or a cone mesh.
  47178. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47179. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47180. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47181. * 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.
  47182. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47183. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47184. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47185. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47186. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47187. * 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).
  47188. * 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
  47189. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47190. * 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
  47191. * 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.
  47192. * If `enclose` is false, a ring surface is one element.
  47193. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47194. * 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
  47195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47196. * 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).
  47197. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47198. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47199. */
  47200. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47201. var cylinder = new BABYLON.Mesh(name, scene);
  47202. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47203. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47204. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47205. vertexData.applyToMesh(cylinder, options.updatable);
  47206. return cylinder;
  47207. };
  47208. /**
  47209. * Creates a torus mesh.
  47210. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47211. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47212. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47213. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47214. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47215. * 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).
  47216. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47218. */
  47219. MeshBuilder.CreateTorus = function (name, options, scene) {
  47220. var torus = new BABYLON.Mesh(name, scene);
  47221. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47222. torus._originalBuilderSideOrientation = options.sideOrientation;
  47223. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47224. vertexData.applyToMesh(torus, options.updatable);
  47225. return torus;
  47226. };
  47227. /**
  47228. * Creates a torus knot mesh.
  47229. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47230. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47231. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47232. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47233. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47234. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47235. * 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).
  47236. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47238. */
  47239. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47240. var torusKnot = new BABYLON.Mesh(name, scene);
  47241. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47242. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47243. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47244. vertexData.applyToMesh(torusKnot, options.updatable);
  47245. return torusKnot;
  47246. };
  47247. /**
  47248. * Creates a line system mesh.
  47249. * A line system is a pool of many lines gathered in a single mesh.
  47250. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47251. * 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.
  47252. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47253. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47254. * 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
  47255. * 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
  47256. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47258. */
  47259. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47260. var instance = options.instance;
  47261. var lines = options.lines;
  47262. if (instance) {
  47263. var positionFunction = function (positions) {
  47264. var i = 0;
  47265. for (var l = 0; l < lines.length; l++) {
  47266. var points = lines[l];
  47267. for (var p = 0; p < points.length; p++) {
  47268. positions[i] = points[p].x;
  47269. positions[i + 1] = points[p].y;
  47270. positions[i + 2] = points[p].z;
  47271. i += 3;
  47272. }
  47273. }
  47274. };
  47275. instance.updateMeshPositions(positionFunction, false);
  47276. return instance;
  47277. }
  47278. // line system creation
  47279. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47280. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47281. vertexData.applyToMesh(lineSystem, options.updatable);
  47282. return lineSystem;
  47283. };
  47284. /**
  47285. * Creates a line mesh.
  47286. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47287. * 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.
  47288. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47289. * The parameter `points` is an array successive Vector3.
  47290. * 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
  47291. * When updating an instance, remember that only point positions can change, not the number of points.
  47292. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47293. */
  47294. MeshBuilder.CreateLines = function (name, options, scene) {
  47295. if (scene === void 0) { scene = null; }
  47296. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47297. return lines;
  47298. };
  47299. /**
  47300. * Creates a dashed line mesh.
  47301. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47302. * 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.
  47303. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47304. * The parameter `points` is an array successive Vector3.
  47305. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47306. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47307. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47308. * 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
  47309. * When updating an instance, remember that only point positions can change, not the number of points.
  47310. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47311. */
  47312. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47313. if (scene === void 0) { scene = null; }
  47314. var points = options.points;
  47315. var instance = options.instance;
  47316. var gapSize = options.gapSize || 1;
  47317. var dashSize = options.dashSize || 3;
  47318. if (instance) {
  47319. var positionFunction = function (positions) {
  47320. var curvect = BABYLON.Vector3.Zero();
  47321. var nbSeg = positions.length / 6;
  47322. var lg = 0;
  47323. var nb = 0;
  47324. var shft = 0;
  47325. var dashshft = 0;
  47326. var curshft = 0;
  47327. var p = 0;
  47328. var i = 0;
  47329. var j = 0;
  47330. for (i = 0; i < points.length - 1; i++) {
  47331. points[i + 1].subtractToRef(points[i], curvect);
  47332. lg += curvect.length();
  47333. }
  47334. shft = lg / nbSeg;
  47335. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47336. for (i = 0; i < points.length - 1; i++) {
  47337. points[i + 1].subtractToRef(points[i], curvect);
  47338. nb = Math.floor(curvect.length() / shft);
  47339. curvect.normalize();
  47340. j = 0;
  47341. while (j < nb && p < positions.length) {
  47342. curshft = shft * j;
  47343. positions[p] = points[i].x + curshft * curvect.x;
  47344. positions[p + 1] = points[i].y + curshft * curvect.y;
  47345. positions[p + 2] = points[i].z + curshft * curvect.z;
  47346. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47347. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47348. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47349. p += 6;
  47350. j++;
  47351. }
  47352. }
  47353. while (p < positions.length) {
  47354. positions[p] = points[i].x;
  47355. positions[p + 1] = points[i].y;
  47356. positions[p + 2] = points[i].z;
  47357. p += 3;
  47358. }
  47359. };
  47360. instance.updateMeshPositions(positionFunction, false);
  47361. return instance;
  47362. }
  47363. // dashed lines creation
  47364. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47365. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47366. vertexData.applyToMesh(dashedLines, options.updatable);
  47367. dashedLines.dashSize = dashSize;
  47368. dashedLines.gapSize = gapSize;
  47369. return dashedLines;
  47370. };
  47371. /**
  47372. * Creates an extruded shape mesh.
  47373. * 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.
  47374. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47375. *
  47376. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47377. * 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
  47378. * extruded along the Z axis.
  47379. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47380. * 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.
  47381. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47382. * 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
  47383. * 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
  47384. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47385. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47386. * 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).
  47387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47388. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47390. */
  47391. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47392. if (scene === void 0) { scene = null; }
  47393. var path = options.path;
  47394. var shape = options.shape;
  47395. var scale = options.scale || 1;
  47396. var rotation = options.rotation || 0;
  47397. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47398. var updatable = options.updatable;
  47399. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47400. var instance = options.instance || null;
  47401. var invertUV = options.invertUV || false;
  47402. 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);
  47403. };
  47404. /**
  47405. * Creates an custom extruded shape mesh.
  47406. * 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.
  47407. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47408. *
  47409. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47410. * 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
  47411. * extruded along the Z axis.
  47412. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47413. * 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
  47414. * and the distance of this point from the begining of the path :
  47415. * ```javascript
  47416. * var rotationFunction = function(i, distance) {
  47417. * // do things
  47418. * return rotationValue; }
  47419. * ```
  47420. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47421. * 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
  47422. * and the distance of this point from the begining of the path :
  47423. * ```javascript
  47424. * var scaleFunction = function(i, distance) {
  47425. * // do things
  47426. * return scaleValue;}
  47427. * ```
  47428. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47429. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47430. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47431. * 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
  47432. * 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
  47433. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47434. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47435. * 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).
  47436. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47437. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47439. */
  47440. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47441. var path = options.path;
  47442. var shape = options.shape;
  47443. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47444. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47445. var ribbonCloseArray = options.ribbonCloseArray || false;
  47446. var ribbonClosePath = options.ribbonClosePath || false;
  47447. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47448. var updatable = options.updatable;
  47449. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47450. var instance = options.instance;
  47451. var invertUV = options.invertUV || false;
  47452. 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);
  47453. };
  47454. /**
  47455. * Creates lathe mesh.
  47456. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47457. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47458. *
  47459. * 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
  47460. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47461. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47462. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47463. * 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.
  47464. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47465. * 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
  47466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47467. * 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).
  47468. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47469. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47470. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47471. */
  47472. MeshBuilder.CreateLathe = function (name, options, scene) {
  47473. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47474. var closed = (options.closed === undefined) ? true : options.closed;
  47475. var shape = options.shape;
  47476. var radius = options.radius || 1;
  47477. var tessellation = options.tessellation || 64;
  47478. var updatable = options.updatable;
  47479. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47480. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47481. var pi2 = Math.PI * 2;
  47482. var paths = new Array();
  47483. var invertUV = options.invertUV || false;
  47484. var i = 0;
  47485. var p = 0;
  47486. var step = pi2 / tessellation * arc;
  47487. var rotated;
  47488. var path = new Array();
  47489. ;
  47490. for (i = 0; i <= tessellation; i++) {
  47491. var path = [];
  47492. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47493. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47494. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47495. }
  47496. for (p = 0; p < shape.length; p++) {
  47497. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47498. path.push(rotated);
  47499. }
  47500. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47501. 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));
  47502. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47503. }
  47504. paths.push(path);
  47505. }
  47506. // lathe ribbon
  47507. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47508. return lathe;
  47509. };
  47510. /**
  47511. * Creates a plane mesh.
  47512. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47513. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47514. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47515. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47516. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47517. * 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).
  47518. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47520. */
  47521. MeshBuilder.CreatePlane = function (name, options, scene) {
  47522. var plane = new BABYLON.Mesh(name, scene);
  47523. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47524. plane._originalBuilderSideOrientation = options.sideOrientation;
  47525. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47526. vertexData.applyToMesh(plane, options.updatable);
  47527. if (options.sourcePlane) {
  47528. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47529. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47530. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47531. plane.rotate(vectorProduct, product);
  47532. }
  47533. return plane;
  47534. };
  47535. /**
  47536. * Creates a ground mesh.
  47537. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47538. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47539. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47541. */
  47542. MeshBuilder.CreateGround = function (name, options, scene) {
  47543. var ground = new BABYLON.GroundMesh(name, scene);
  47544. ground._setReady(false);
  47545. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47546. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47547. ground._width = options.width || 1;
  47548. ground._height = options.height || 1;
  47549. ground._maxX = ground._width / 2;
  47550. ground._maxZ = ground._height / 2;
  47551. ground._minX = -ground._maxX;
  47552. ground._minZ = -ground._maxZ;
  47553. var vertexData = BABYLON.VertexData.CreateGround(options);
  47554. vertexData.applyToMesh(ground, options.updatable);
  47555. ground._setReady(true);
  47556. return ground;
  47557. };
  47558. /**
  47559. * Creates a tiled ground mesh.
  47560. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47561. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47562. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47563. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47564. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47565. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47566. * numbers of subdivisions on the ground width and height of each tile.
  47567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47568. */
  47569. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47570. var tiledGround = new BABYLON.Mesh(name, scene);
  47571. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47572. vertexData.applyToMesh(tiledGround, options.updatable);
  47573. return tiledGround;
  47574. };
  47575. /**
  47576. * Creates a ground mesh from a height map.
  47577. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47578. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47579. * The parameter `url` sets the URL of the height map image resource.
  47580. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47581. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47582. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47583. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47584. * 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.
  47585. * 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).
  47586. * This function is passed the newly built mesh :
  47587. * ```javascript
  47588. * function(mesh) { // do things
  47589. * return; }
  47590. * ```
  47591. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47592. */
  47593. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47594. var width = options.width || 10.0;
  47595. var height = options.height || 10.0;
  47596. var subdivisions = options.subdivisions || 1 | 0;
  47597. var minHeight = options.minHeight || 0.0;
  47598. var maxHeight = options.maxHeight || 1.0;
  47599. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47600. var updatable = options.updatable;
  47601. var onReady = options.onReady;
  47602. var ground = new BABYLON.GroundMesh(name, scene);
  47603. ground._subdivisionsX = subdivisions;
  47604. ground._subdivisionsY = subdivisions;
  47605. ground._width = width;
  47606. ground._height = height;
  47607. ground._maxX = ground._width / 2.0;
  47608. ground._maxZ = ground._height / 2.0;
  47609. ground._minX = -ground._maxX;
  47610. ground._minZ = -ground._maxZ;
  47611. ground._setReady(false);
  47612. var onload = function (img) {
  47613. // Getting height map data
  47614. var canvas = document.createElement("canvas");
  47615. var context = canvas.getContext("2d");
  47616. if (!context) {
  47617. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47618. }
  47619. var bufferWidth = img.width;
  47620. var bufferHeight = img.height;
  47621. canvas.width = bufferWidth;
  47622. canvas.height = bufferHeight;
  47623. context.drawImage(img, 0, 0);
  47624. // Create VertexData from map data
  47625. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47626. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47627. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47628. width: width, height: height,
  47629. subdivisions: subdivisions,
  47630. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47631. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47632. });
  47633. vertexData.applyToMesh(ground, updatable);
  47634. ground._setReady(true);
  47635. //execute ready callback, if set
  47636. if (onReady) {
  47637. onReady(ground);
  47638. }
  47639. };
  47640. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47641. return ground;
  47642. };
  47643. /**
  47644. * Creates a polygon mesh.
  47645. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47646. * 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.
  47647. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47649. * 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).
  47650. * Remember you can only change the shape positions, not their number when updating a polygon.
  47651. */
  47652. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47653. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47654. var shape = options.shape;
  47655. var holes = options.holes || [];
  47656. var depth = options.depth || 0;
  47657. var contours = [];
  47658. var hole = [];
  47659. for (var i = 0; i < shape.length; i++) {
  47660. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47661. }
  47662. var epsilon = 0.00000001;
  47663. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47664. contours.pop();
  47665. }
  47666. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47667. for (var hNb = 0; hNb < holes.length; hNb++) {
  47668. hole = [];
  47669. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47670. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47671. }
  47672. polygonTriangulation.addHole(hole);
  47673. }
  47674. var polygon = polygonTriangulation.build(options.updatable, depth);
  47675. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47676. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47677. vertexData.applyToMesh(polygon, options.updatable);
  47678. return polygon;
  47679. };
  47680. ;
  47681. /**
  47682. * Creates an extruded polygon mesh, with depth in the Y direction.
  47683. * 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).
  47684. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47685. */
  47686. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47687. return MeshBuilder.CreatePolygon(name, options, scene);
  47688. };
  47689. ;
  47690. /**
  47691. * Creates a tube mesh.
  47692. * 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.
  47693. *
  47694. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47695. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47696. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47697. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47698. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47699. * 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.
  47700. * It must return a radius value (positive float) :
  47701. * ```javascript
  47702. * var radiusFunction = function(i, distance) {
  47703. * // do things
  47704. * return radius; }
  47705. * ```
  47706. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47707. * 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
  47708. * 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
  47709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47710. * 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).
  47711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47712. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47713. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47714. */
  47715. MeshBuilder.CreateTube = function (name, options, scene) {
  47716. var path = options.path;
  47717. var instance = options.instance;
  47718. var radius = 1.0;
  47719. if (instance) {
  47720. radius = instance.radius;
  47721. }
  47722. if (options.radius !== undefined) {
  47723. radius = options.radius;
  47724. }
  47725. ;
  47726. var tessellation = options.tessellation || 64 | 0;
  47727. var radiusFunction = options.radiusFunction || null;
  47728. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47729. var invertUV = options.invertUV || false;
  47730. var updatable = options.updatable;
  47731. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47732. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47733. // tube geometry
  47734. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47735. var tangents = path3D.getTangents();
  47736. var normals = path3D.getNormals();
  47737. var distances = path3D.getDistances();
  47738. var pi2 = Math.PI * 2;
  47739. var step = pi2 / tessellation * arc;
  47740. var returnRadius = function () { return radius; };
  47741. var radiusFunctionFinal = radiusFunction || returnRadius;
  47742. var circlePath;
  47743. var rad;
  47744. var normal;
  47745. var rotated;
  47746. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47747. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47748. for (var i = 0; i < path.length; i++) {
  47749. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47750. circlePath = Array(); // current circle array
  47751. normal = normals[i]; // current normal
  47752. for (var t = 0; t < tessellation; t++) {
  47753. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47754. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47755. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47756. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47757. circlePath[t] = rotated;
  47758. }
  47759. circlePaths[index] = circlePath;
  47760. index++;
  47761. }
  47762. // cap
  47763. var capPath = function (nbPoints, pathIndex) {
  47764. var pointCap = Array();
  47765. for (var i = 0; i < nbPoints; i++) {
  47766. pointCap.push(path[pathIndex]);
  47767. }
  47768. return pointCap;
  47769. };
  47770. switch (cap) {
  47771. case BABYLON.Mesh.NO_CAP:
  47772. break;
  47773. case BABYLON.Mesh.CAP_START:
  47774. circlePaths[0] = capPath(tessellation, 0);
  47775. circlePaths[1] = circlePaths[2].slice(0);
  47776. break;
  47777. case BABYLON.Mesh.CAP_END:
  47778. circlePaths[index] = circlePaths[index - 1].slice(0);
  47779. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47780. break;
  47781. case BABYLON.Mesh.CAP_ALL:
  47782. circlePaths[0] = capPath(tessellation, 0);
  47783. circlePaths[1] = circlePaths[2].slice(0);
  47784. circlePaths[index] = circlePaths[index - 1].slice(0);
  47785. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47786. break;
  47787. default:
  47788. break;
  47789. }
  47790. return circlePaths;
  47791. };
  47792. var path3D;
  47793. var pathArray;
  47794. if (instance) {
  47795. var arc = options.arc || instance.arc;
  47796. path3D = (instance.path3D).update(path);
  47797. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47798. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47799. instance.path3D = path3D;
  47800. instance.pathArray = pathArray;
  47801. instance.arc = arc;
  47802. instance.radius = radius;
  47803. return instance;
  47804. }
  47805. // tube creation
  47806. path3D = new BABYLON.Path3D(path);
  47807. var newPathArray = new Array();
  47808. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47809. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47810. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47811. tube.pathArray = pathArray;
  47812. tube.path3D = path3D;
  47813. tube.tessellation = tessellation;
  47814. tube.cap = cap;
  47815. tube.arc = options.arc;
  47816. tube.radius = radius;
  47817. return tube;
  47818. };
  47819. /**
  47820. * Creates a polyhedron mesh.
  47821. *
  47822. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47823. * 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
  47824. * to choose the wanted type.
  47825. * The parameter `size` (positive float, default 1) sets the polygon size.
  47826. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47827. * 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`.
  47828. * 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
  47829. * 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)`).
  47830. * 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
  47831. * 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.
  47832. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47833. * 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).
  47834. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47835. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47836. */
  47837. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47838. var polyhedron = new BABYLON.Mesh(name, scene);
  47839. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47840. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47841. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47842. vertexData.applyToMesh(polyhedron, options.updatable);
  47843. return polyhedron;
  47844. };
  47845. /**
  47846. * Creates a decal mesh.
  47847. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47848. * 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.
  47849. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47850. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47851. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47852. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47853. */
  47854. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47855. var indices = sourceMesh.getIndices();
  47856. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47857. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47858. var position = options.position || BABYLON.Vector3.Zero();
  47859. var normal = options.normal || BABYLON.Vector3.Up();
  47860. var size = options.size || BABYLON.Vector3.One();
  47861. var angle = options.angle || 0;
  47862. // Getting correct rotation
  47863. if (!normal) {
  47864. var target = new BABYLON.Vector3(0, 0, 1);
  47865. var camera = sourceMesh.getScene().activeCamera;
  47866. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47867. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47868. }
  47869. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47870. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47871. var pitch = Math.atan2(normal.y, len);
  47872. // Matrix
  47873. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47874. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47875. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47876. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47877. var vertexData = new BABYLON.VertexData();
  47878. vertexData.indices = [];
  47879. vertexData.positions = [];
  47880. vertexData.normals = [];
  47881. vertexData.uvs = [];
  47882. var currentVertexDataIndex = 0;
  47883. var extractDecalVector3 = function (indexId) {
  47884. var result = new BABYLON.PositionNormalVertex();
  47885. if (!indices || !positions || !normals) {
  47886. return result;
  47887. }
  47888. var vertexId = indices[indexId];
  47889. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47890. // Send vector to decal local world
  47891. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47892. // Get normal
  47893. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47894. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47895. return result;
  47896. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47897. var clip = function (vertices, axis) {
  47898. if (vertices.length === 0) {
  47899. return vertices;
  47900. }
  47901. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47902. var clipVertices = function (v0, v1) {
  47903. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47904. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47905. };
  47906. var result = new Array();
  47907. for (var index = 0; index < vertices.length; index += 3) {
  47908. var v1Out;
  47909. var v2Out;
  47910. var v3Out;
  47911. var total = 0;
  47912. var nV1 = null;
  47913. var nV2 = null;
  47914. var nV3 = null;
  47915. var nV4 = null;
  47916. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47917. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47918. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47919. v1Out = d1 > 0;
  47920. v2Out = d2 > 0;
  47921. v3Out = d3 > 0;
  47922. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47923. switch (total) {
  47924. case 0:
  47925. result.push(vertices[index]);
  47926. result.push(vertices[index + 1]);
  47927. result.push(vertices[index + 2]);
  47928. break;
  47929. case 1:
  47930. if (v1Out) {
  47931. nV1 = vertices[index + 1];
  47932. nV2 = vertices[index + 2];
  47933. nV3 = clipVertices(vertices[index], nV1);
  47934. nV4 = clipVertices(vertices[index], nV2);
  47935. }
  47936. if (v2Out) {
  47937. nV1 = vertices[index];
  47938. nV2 = vertices[index + 2];
  47939. nV3 = clipVertices(vertices[index + 1], nV1);
  47940. nV4 = clipVertices(vertices[index + 1], nV2);
  47941. result.push(nV3);
  47942. result.push(nV2.clone());
  47943. result.push(nV1.clone());
  47944. result.push(nV2.clone());
  47945. result.push(nV3.clone());
  47946. result.push(nV4);
  47947. break;
  47948. }
  47949. if (v3Out) {
  47950. nV1 = vertices[index];
  47951. nV2 = vertices[index + 1];
  47952. nV3 = clipVertices(vertices[index + 2], nV1);
  47953. nV4 = clipVertices(vertices[index + 2], nV2);
  47954. }
  47955. if (nV1 && nV2 && nV3 && nV4) {
  47956. result.push(nV1.clone());
  47957. result.push(nV2.clone());
  47958. result.push(nV3);
  47959. result.push(nV4);
  47960. result.push(nV3.clone());
  47961. result.push(nV2.clone());
  47962. }
  47963. break;
  47964. case 2:
  47965. if (!v1Out) {
  47966. nV1 = vertices[index].clone();
  47967. nV2 = clipVertices(nV1, vertices[index + 1]);
  47968. nV3 = clipVertices(nV1, vertices[index + 2]);
  47969. result.push(nV1);
  47970. result.push(nV2);
  47971. result.push(nV3);
  47972. }
  47973. if (!v2Out) {
  47974. nV1 = vertices[index + 1].clone();
  47975. nV2 = clipVertices(nV1, vertices[index + 2]);
  47976. nV3 = clipVertices(nV1, vertices[index]);
  47977. result.push(nV1);
  47978. result.push(nV2);
  47979. result.push(nV3);
  47980. }
  47981. if (!v3Out) {
  47982. nV1 = vertices[index + 2].clone();
  47983. nV2 = clipVertices(nV1, vertices[index]);
  47984. nV3 = clipVertices(nV1, vertices[index + 1]);
  47985. result.push(nV1);
  47986. result.push(nV2);
  47987. result.push(nV3);
  47988. }
  47989. break;
  47990. case 3:
  47991. break;
  47992. }
  47993. }
  47994. return result;
  47995. };
  47996. for (var index = 0; index < indices.length; index += 3) {
  47997. var faceVertices = new Array();
  47998. faceVertices.push(extractDecalVector3(index));
  47999. faceVertices.push(extractDecalVector3(index + 1));
  48000. faceVertices.push(extractDecalVector3(index + 2));
  48001. // Clip
  48002. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  48003. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  48004. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  48005. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  48006. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  48007. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  48008. if (faceVertices.length === 0) {
  48009. continue;
  48010. }
  48011. // Add UVs and get back to world
  48012. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  48013. var vertex = faceVertices[vIndex];
  48014. //TODO check for Int32Array | Uint32Array | Uint16Array
  48015. vertexData.indices.push(currentVertexDataIndex);
  48016. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  48017. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  48018. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  48019. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  48020. currentVertexDataIndex++;
  48021. }
  48022. }
  48023. // Return mesh
  48024. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  48025. vertexData.applyToMesh(decal);
  48026. decal.position = position.clone();
  48027. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48028. return decal;
  48029. };
  48030. // Privates
  48031. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48032. // extrusion geometry
  48033. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48034. var tangents = path3D.getTangents();
  48035. var normals = path3D.getNormals();
  48036. var binormals = path3D.getBinormals();
  48037. var distances = path3D.getDistances();
  48038. var angle = 0;
  48039. var returnScale = function () { return scale !== null ? scale : 1; };
  48040. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48041. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48042. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48043. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48044. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48045. for (var i = 0; i < curve.length; i++) {
  48046. var shapePath = new Array();
  48047. var angleStep = rotate(i, distances[i]);
  48048. var scaleRatio = scl(i, distances[i]);
  48049. for (var p = 0; p < shape.length; p++) {
  48050. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48051. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48052. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48053. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48054. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48055. shapePath[p] = rotated;
  48056. }
  48057. shapePaths[index] = shapePath;
  48058. angle += angleStep;
  48059. index++;
  48060. }
  48061. // cap
  48062. var capPath = function (shapePath) {
  48063. var pointCap = Array();
  48064. var barycenter = BABYLON.Vector3.Zero();
  48065. var i;
  48066. for (i = 0; i < shapePath.length; i++) {
  48067. barycenter.addInPlace(shapePath[i]);
  48068. }
  48069. barycenter.scaleInPlace(1.0 / shapePath.length);
  48070. for (i = 0; i < shapePath.length; i++) {
  48071. pointCap.push(barycenter);
  48072. }
  48073. return pointCap;
  48074. };
  48075. switch (cap) {
  48076. case BABYLON.Mesh.NO_CAP:
  48077. break;
  48078. case BABYLON.Mesh.CAP_START:
  48079. shapePaths[0] = capPath(shapePaths[2]);
  48080. shapePaths[1] = shapePaths[2];
  48081. break;
  48082. case BABYLON.Mesh.CAP_END:
  48083. shapePaths[index] = shapePaths[index - 1];
  48084. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48085. break;
  48086. case BABYLON.Mesh.CAP_ALL:
  48087. shapePaths[0] = capPath(shapePaths[2]);
  48088. shapePaths[1] = shapePaths[2];
  48089. shapePaths[index] = shapePaths[index - 1];
  48090. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48091. break;
  48092. default:
  48093. break;
  48094. }
  48095. return shapePaths;
  48096. };
  48097. var path3D;
  48098. var pathArray;
  48099. if (instance) {
  48100. path3D = (instance.path3D).update(curve);
  48101. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48102. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48103. return instance;
  48104. }
  48105. // extruded shape creation
  48106. path3D = new BABYLON.Path3D(curve);
  48107. var newShapePaths = new Array();
  48108. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48109. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48110. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48111. extrudedGeneric.pathArray = pathArray;
  48112. extrudedGeneric.path3D = path3D;
  48113. extrudedGeneric.cap = cap;
  48114. return extrudedGeneric;
  48115. };
  48116. return MeshBuilder;
  48117. }());
  48118. BABYLON.MeshBuilder = MeshBuilder;
  48119. })(BABYLON || (BABYLON = {}));
  48120. //# sourceMappingURL=babylon.meshBuilder.js.map
  48121. var BABYLON;
  48122. (function (BABYLON) {
  48123. var AudioEngine = /** @class */ (function () {
  48124. function AudioEngine() {
  48125. this._audioContext = null;
  48126. this._audioContextInitialized = false;
  48127. this.canUseWebAudio = false;
  48128. this.WarnedWebAudioUnsupported = false;
  48129. this.unlocked = false;
  48130. this.isMP3supported = false;
  48131. this.isOGGsupported = false;
  48132. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48133. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48134. this.canUseWebAudio = true;
  48135. }
  48136. var audioElem = document.createElement('audio');
  48137. try {
  48138. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48139. this.isMP3supported = true;
  48140. }
  48141. }
  48142. catch (e) {
  48143. // protect error during capability check.
  48144. }
  48145. try {
  48146. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48147. this.isOGGsupported = true;
  48148. }
  48149. }
  48150. catch (e) {
  48151. // protect error during capability check.
  48152. }
  48153. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48154. this._unlockiOSaudio();
  48155. }
  48156. else {
  48157. this.unlocked = true;
  48158. }
  48159. }
  48160. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48161. get: function () {
  48162. if (!this._audioContextInitialized) {
  48163. this._initializeAudioContext();
  48164. }
  48165. return this._audioContext;
  48166. },
  48167. enumerable: true,
  48168. configurable: true
  48169. });
  48170. AudioEngine.prototype._unlockiOSaudio = function () {
  48171. var _this = this;
  48172. var unlockaudio = function () {
  48173. if (!_this.audioContext) {
  48174. return;
  48175. }
  48176. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48177. var source = _this.audioContext.createBufferSource();
  48178. source.buffer = buffer;
  48179. source.connect(_this.audioContext.destination);
  48180. source.start(0);
  48181. setTimeout(function () {
  48182. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48183. _this.unlocked = true;
  48184. window.removeEventListener('touchend', unlockaudio, false);
  48185. if (_this.onAudioUnlocked) {
  48186. _this.onAudioUnlocked();
  48187. }
  48188. }
  48189. }, 0);
  48190. };
  48191. window.addEventListener('touchend', unlockaudio, false);
  48192. };
  48193. AudioEngine.prototype._initializeAudioContext = function () {
  48194. try {
  48195. if (this.canUseWebAudio) {
  48196. this._audioContext = new AudioContext();
  48197. // create a global volume gain node
  48198. this.masterGain = this._audioContext.createGain();
  48199. this.masterGain.gain.value = 1;
  48200. this.masterGain.connect(this._audioContext.destination);
  48201. this._audioContextInitialized = true;
  48202. }
  48203. }
  48204. catch (e) {
  48205. this.canUseWebAudio = false;
  48206. BABYLON.Tools.Error("Web Audio: " + e.message);
  48207. }
  48208. };
  48209. AudioEngine.prototype.dispose = function () {
  48210. if (this.canUseWebAudio && this._audioContextInitialized) {
  48211. if (this._connectedAnalyser && this._audioContext) {
  48212. this._connectedAnalyser.stopDebugCanvas();
  48213. this._connectedAnalyser.dispose();
  48214. this.masterGain.disconnect();
  48215. this.masterGain.connect(this._audioContext.destination);
  48216. this._connectedAnalyser = null;
  48217. }
  48218. this.masterGain.gain.value = 1;
  48219. }
  48220. this.WarnedWebAudioUnsupported = false;
  48221. };
  48222. AudioEngine.prototype.getGlobalVolume = function () {
  48223. if (this.canUseWebAudio && this._audioContextInitialized) {
  48224. return this.masterGain.gain.value;
  48225. }
  48226. else {
  48227. return -1;
  48228. }
  48229. };
  48230. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48231. if (this.canUseWebAudio && this._audioContextInitialized) {
  48232. this.masterGain.gain.value = newVolume;
  48233. }
  48234. };
  48235. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48236. if (this._connectedAnalyser) {
  48237. this._connectedAnalyser.stopDebugCanvas();
  48238. }
  48239. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48240. this._connectedAnalyser = analyser;
  48241. this.masterGain.disconnect();
  48242. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48243. }
  48244. };
  48245. return AudioEngine;
  48246. }());
  48247. BABYLON.AudioEngine = AudioEngine;
  48248. })(BABYLON || (BABYLON = {}));
  48249. //# sourceMappingURL=babylon.audioEngine.js.map
  48250. var BABYLON;
  48251. (function (BABYLON) {
  48252. var Sound = /** @class */ (function () {
  48253. /**
  48254. * Create a sound and attach it to a scene
  48255. * @param name Name of your sound
  48256. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48257. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48258. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48259. */
  48260. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48261. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48262. var _this = this;
  48263. this.autoplay = false;
  48264. this.loop = false;
  48265. this.useCustomAttenuation = false;
  48266. this.spatialSound = false;
  48267. this.refDistance = 1;
  48268. this.rolloffFactor = 1;
  48269. this.maxDistance = 100;
  48270. this.distanceModel = "linear";
  48271. this._panningModel = "equalpower";
  48272. this._playbackRate = 1;
  48273. this._streaming = false;
  48274. this._startTime = 0;
  48275. this._startOffset = 0;
  48276. this._position = BABYLON.Vector3.Zero();
  48277. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48278. this._volume = 1;
  48279. this._isLoaded = false;
  48280. this._isReadyToPlay = false;
  48281. this.isPlaying = false;
  48282. this.isPaused = false;
  48283. this._isDirectional = false;
  48284. // Used if you'd like to create a directional sound.
  48285. // If not set, the sound will be omnidirectional
  48286. this._coneInnerAngle = 360;
  48287. this._coneOuterAngle = 360;
  48288. this._coneOuterGain = 0;
  48289. this._isOutputConnected = false;
  48290. this._urlType = "Unknown";
  48291. this.name = name;
  48292. this._scene = scene;
  48293. this._readyToPlayCallback = readyToPlayCallback;
  48294. // Default custom attenuation function is a linear attenuation
  48295. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48296. if (currentDistance < maxDistance) {
  48297. return currentVolume * (1 - currentDistance / maxDistance);
  48298. }
  48299. else {
  48300. return 0;
  48301. }
  48302. };
  48303. if (options) {
  48304. this.autoplay = options.autoplay || false;
  48305. this.loop = options.loop || false;
  48306. // if volume === 0, we need another way to check this option
  48307. if (options.volume !== undefined) {
  48308. this._volume = options.volume;
  48309. }
  48310. this.spatialSound = options.spatialSound || false;
  48311. this.maxDistance = options.maxDistance || 100;
  48312. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48313. this.rolloffFactor = options.rolloffFactor || 1;
  48314. this.refDistance = options.refDistance || 1;
  48315. this.distanceModel = options.distanceModel || "linear";
  48316. this._playbackRate = options.playbackRate || 1;
  48317. this._streaming = options.streaming || false;
  48318. }
  48319. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48320. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48321. this._soundGain.gain.value = this._volume;
  48322. this._inputAudioNode = this._soundGain;
  48323. this._ouputAudioNode = this._soundGain;
  48324. if (this.spatialSound) {
  48325. this._createSpatialParameters();
  48326. }
  48327. this._scene.mainSoundTrack.AddSound(this);
  48328. var validParameter = true;
  48329. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48330. if (urlOrArrayBuffer) {
  48331. if (typeof (urlOrArrayBuffer) === "string")
  48332. this._urlType = "String";
  48333. if (Array.isArray(urlOrArrayBuffer))
  48334. this._urlType = "Array";
  48335. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48336. this._urlType = "ArrayBuffer";
  48337. var urls = [];
  48338. var codecSupportedFound = false;
  48339. switch (this._urlType) {
  48340. case "ArrayBuffer":
  48341. if (urlOrArrayBuffer.byteLength > 0) {
  48342. codecSupportedFound = true;
  48343. this._soundLoaded(urlOrArrayBuffer);
  48344. }
  48345. break;
  48346. case "String":
  48347. urls.push(urlOrArrayBuffer);
  48348. case "Array":
  48349. if (urls.length === 0)
  48350. urls = urlOrArrayBuffer;
  48351. // If we found a supported format, we load it immediately and stop the loop
  48352. for (var i = 0; i < urls.length; i++) {
  48353. var url = urls[i];
  48354. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48355. codecSupportedFound = true;
  48356. }
  48357. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48358. codecSupportedFound = true;
  48359. }
  48360. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48361. codecSupportedFound = true;
  48362. }
  48363. if (url.indexOf("blob:") !== -1) {
  48364. codecSupportedFound = true;
  48365. }
  48366. if (codecSupportedFound) {
  48367. // Loading sound using XHR2
  48368. if (!this._streaming) {
  48369. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48370. }
  48371. else {
  48372. this._htmlAudioElement = new Audio(url);
  48373. this._htmlAudioElement.controls = false;
  48374. this._htmlAudioElement.loop = this.loop;
  48375. this._htmlAudioElement.crossOrigin = "anonymous";
  48376. this._htmlAudioElement.preload = "auto";
  48377. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48378. _this._isReadyToPlay = true;
  48379. if (_this.autoplay) {
  48380. _this.play();
  48381. }
  48382. if (_this._readyToPlayCallback) {
  48383. _this._readyToPlayCallback();
  48384. }
  48385. });
  48386. document.body.appendChild(this._htmlAudioElement);
  48387. }
  48388. break;
  48389. }
  48390. }
  48391. break;
  48392. default:
  48393. validParameter = false;
  48394. break;
  48395. }
  48396. if (!validParameter) {
  48397. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48398. }
  48399. else {
  48400. if (!codecSupportedFound) {
  48401. this._isReadyToPlay = true;
  48402. // Simulating a ready to play event to avoid breaking code path
  48403. if (this._readyToPlayCallback) {
  48404. window.setTimeout(function () {
  48405. if (_this._readyToPlayCallback) {
  48406. _this._readyToPlayCallback();
  48407. }
  48408. }, 1000);
  48409. }
  48410. }
  48411. }
  48412. }
  48413. }
  48414. else {
  48415. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48416. this._scene.mainSoundTrack.AddSound(this);
  48417. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48418. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48419. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48420. }
  48421. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48422. if (this._readyToPlayCallback) {
  48423. window.setTimeout(function () {
  48424. if (_this._readyToPlayCallback) {
  48425. _this._readyToPlayCallback();
  48426. }
  48427. }, 1000);
  48428. }
  48429. }
  48430. }
  48431. Sound.prototype.dispose = function () {
  48432. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48433. if (this.isPlaying) {
  48434. this.stop();
  48435. }
  48436. this._isReadyToPlay = false;
  48437. if (this.soundTrackId === -1) {
  48438. this._scene.mainSoundTrack.RemoveSound(this);
  48439. }
  48440. else {
  48441. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48442. }
  48443. if (this._soundGain) {
  48444. this._soundGain.disconnect();
  48445. this._soundGain = null;
  48446. }
  48447. if (this._soundPanner) {
  48448. this._soundPanner.disconnect();
  48449. this._soundPanner = null;
  48450. }
  48451. if (this._soundSource) {
  48452. this._soundSource.disconnect();
  48453. this._soundSource = null;
  48454. }
  48455. this._audioBuffer = null;
  48456. if (this._htmlAudioElement) {
  48457. this._htmlAudioElement.pause();
  48458. this._htmlAudioElement.src = "";
  48459. document.body.removeChild(this._htmlAudioElement);
  48460. }
  48461. if (this._connectedMesh && this._registerFunc) {
  48462. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48463. this._connectedMesh = null;
  48464. }
  48465. }
  48466. };
  48467. Sound.prototype.isReady = function () {
  48468. return this._isReadyToPlay;
  48469. };
  48470. Sound.prototype._soundLoaded = function (audioData) {
  48471. var _this = this;
  48472. this._isLoaded = true;
  48473. if (!BABYLON.Engine.audioEngine.audioContext) {
  48474. return;
  48475. }
  48476. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48477. _this._audioBuffer = buffer;
  48478. _this._isReadyToPlay = true;
  48479. if (_this.autoplay) {
  48480. _this.play();
  48481. }
  48482. if (_this._readyToPlayCallback) {
  48483. _this._readyToPlayCallback();
  48484. }
  48485. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48486. };
  48487. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48488. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48489. this._audioBuffer = audioBuffer;
  48490. this._isReadyToPlay = true;
  48491. }
  48492. };
  48493. Sound.prototype.updateOptions = function (options) {
  48494. if (options) {
  48495. this.loop = options.loop || this.loop;
  48496. this.maxDistance = options.maxDistance || this.maxDistance;
  48497. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48498. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48499. this.refDistance = options.refDistance || this.refDistance;
  48500. this.distanceModel = options.distanceModel || this.distanceModel;
  48501. this._playbackRate = options.playbackRate || this._playbackRate;
  48502. this._updateSpatialParameters();
  48503. if (this.isPlaying) {
  48504. if (this._streaming) {
  48505. this._htmlAudioElement.playbackRate = this._playbackRate;
  48506. }
  48507. else {
  48508. if (this._soundSource) {
  48509. this._soundSource.playbackRate.value = this._playbackRate;
  48510. }
  48511. }
  48512. }
  48513. }
  48514. };
  48515. Sound.prototype._createSpatialParameters = function () {
  48516. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48517. if (this._scene.headphone) {
  48518. this._panningModel = "HRTF";
  48519. }
  48520. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48521. this._updateSpatialParameters();
  48522. this._soundPanner.connect(this._ouputAudioNode);
  48523. this._inputAudioNode = this._soundPanner;
  48524. }
  48525. };
  48526. Sound.prototype._updateSpatialParameters = function () {
  48527. if (this.spatialSound && this._soundPanner) {
  48528. if (this.useCustomAttenuation) {
  48529. // Tricks to disable in a way embedded Web Audio attenuation
  48530. this._soundPanner.distanceModel = "linear";
  48531. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48532. this._soundPanner.refDistance = 1;
  48533. this._soundPanner.rolloffFactor = 1;
  48534. this._soundPanner.panningModel = this._panningModel;
  48535. }
  48536. else {
  48537. this._soundPanner.distanceModel = this.distanceModel;
  48538. this._soundPanner.maxDistance = this.maxDistance;
  48539. this._soundPanner.refDistance = this.refDistance;
  48540. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48541. this._soundPanner.panningModel = this._panningModel;
  48542. }
  48543. }
  48544. };
  48545. Sound.prototype.switchPanningModelToHRTF = function () {
  48546. this._panningModel = "HRTF";
  48547. this._switchPanningModel();
  48548. };
  48549. Sound.prototype.switchPanningModelToEqualPower = function () {
  48550. this._panningModel = "equalpower";
  48551. this._switchPanningModel();
  48552. };
  48553. Sound.prototype._switchPanningModel = function () {
  48554. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48555. this._soundPanner.panningModel = this._panningModel;
  48556. }
  48557. };
  48558. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48559. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48560. if (this._isOutputConnected) {
  48561. this._ouputAudioNode.disconnect();
  48562. }
  48563. this._ouputAudioNode.connect(soundTrackAudioNode);
  48564. this._isOutputConnected = true;
  48565. }
  48566. };
  48567. /**
  48568. * Transform this sound into a directional source
  48569. * @param coneInnerAngle Size of the inner cone in degree
  48570. * @param coneOuterAngle Size of the outer cone in degree
  48571. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48572. */
  48573. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48574. if (coneOuterAngle < coneInnerAngle) {
  48575. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48576. return;
  48577. }
  48578. this._coneInnerAngle = coneInnerAngle;
  48579. this._coneOuterAngle = coneOuterAngle;
  48580. this._coneOuterGain = coneOuterGain;
  48581. this._isDirectional = true;
  48582. if (this.isPlaying && this.loop) {
  48583. this.stop();
  48584. this.play();
  48585. }
  48586. };
  48587. Sound.prototype.setPosition = function (newPosition) {
  48588. this._position = newPosition;
  48589. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48590. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48591. }
  48592. };
  48593. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48594. this._localDirection = newLocalDirection;
  48595. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48596. this._updateDirection();
  48597. }
  48598. };
  48599. Sound.prototype._updateDirection = function () {
  48600. if (!this._connectedMesh || !this._soundPanner) {
  48601. return;
  48602. }
  48603. var mat = this._connectedMesh.getWorldMatrix();
  48604. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48605. direction.normalize();
  48606. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48607. };
  48608. Sound.prototype.updateDistanceFromListener = function () {
  48609. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48610. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48611. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48612. }
  48613. };
  48614. Sound.prototype.setAttenuationFunction = function (callback) {
  48615. this._customAttenuationFunction = callback;
  48616. };
  48617. /**
  48618. * Play the sound
  48619. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48620. * @param offset (optional) Start the sound setting it at a specific time
  48621. */
  48622. Sound.prototype.play = function (time, offset) {
  48623. var _this = this;
  48624. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48625. try {
  48626. if (this._startOffset < 0) {
  48627. time = -this._startOffset;
  48628. this._startOffset = 0;
  48629. }
  48630. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48631. if (!this._soundSource || !this._streamingSource) {
  48632. if (this.spatialSound && this._soundPanner) {
  48633. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48634. if (this._isDirectional) {
  48635. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48636. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48637. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48638. if (this._connectedMesh) {
  48639. this._updateDirection();
  48640. }
  48641. else {
  48642. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48643. }
  48644. }
  48645. }
  48646. }
  48647. if (this._streaming) {
  48648. if (!this._streamingSource) {
  48649. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48650. this._htmlAudioElement.onended = function () { _this._onended(); };
  48651. this._htmlAudioElement.playbackRate = this._playbackRate;
  48652. }
  48653. this._streamingSource.disconnect();
  48654. this._streamingSource.connect(this._inputAudioNode);
  48655. this._htmlAudioElement.play();
  48656. }
  48657. else {
  48658. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48659. this._soundSource.buffer = this._audioBuffer;
  48660. this._soundSource.connect(this._inputAudioNode);
  48661. this._soundSource.loop = this.loop;
  48662. this._soundSource.playbackRate.value = this._playbackRate;
  48663. this._soundSource.onended = function () { _this._onended(); };
  48664. if (this._soundSource.buffer) {
  48665. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48666. }
  48667. }
  48668. this._startTime = startTime;
  48669. this.isPlaying = true;
  48670. this.isPaused = false;
  48671. }
  48672. catch (ex) {
  48673. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48674. }
  48675. }
  48676. };
  48677. Sound.prototype._onended = function () {
  48678. this.isPlaying = false;
  48679. if (this.onended) {
  48680. this.onended();
  48681. }
  48682. };
  48683. /**
  48684. * Stop the sound
  48685. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48686. */
  48687. Sound.prototype.stop = function (time) {
  48688. if (this.isPlaying) {
  48689. if (this._streaming) {
  48690. this._htmlAudioElement.pause();
  48691. // Test needed for Firefox or it will generate an Invalid State Error
  48692. if (this._htmlAudioElement.currentTime > 0) {
  48693. this._htmlAudioElement.currentTime = 0;
  48694. }
  48695. }
  48696. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48697. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48698. this._soundSource.stop(stopTime);
  48699. this._soundSource.onended = function () { };
  48700. if (!this.isPaused) {
  48701. this._startOffset = 0;
  48702. }
  48703. }
  48704. this.isPlaying = false;
  48705. }
  48706. };
  48707. Sound.prototype.pause = function () {
  48708. if (this.isPlaying) {
  48709. this.isPaused = true;
  48710. if (this._streaming) {
  48711. this._htmlAudioElement.pause();
  48712. }
  48713. else if (BABYLON.Engine.audioEngine.audioContext) {
  48714. this.stop(0);
  48715. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48716. }
  48717. }
  48718. };
  48719. Sound.prototype.setVolume = function (newVolume, time) {
  48720. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48721. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48722. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48723. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48724. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48725. }
  48726. else {
  48727. this._soundGain.gain.value = newVolume;
  48728. }
  48729. }
  48730. this._volume = newVolume;
  48731. };
  48732. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48733. this._playbackRate = newPlaybackRate;
  48734. if (this.isPlaying) {
  48735. if (this._streaming) {
  48736. this._htmlAudioElement.playbackRate = this._playbackRate;
  48737. }
  48738. else if (this._soundSource) {
  48739. this._soundSource.playbackRate.value = this._playbackRate;
  48740. }
  48741. }
  48742. };
  48743. Sound.prototype.getVolume = function () {
  48744. return this._volume;
  48745. };
  48746. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48747. var _this = this;
  48748. if (this._connectedMesh && this._registerFunc) {
  48749. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48750. this._registerFunc = null;
  48751. }
  48752. this._connectedMesh = meshToConnectTo;
  48753. if (!this.spatialSound) {
  48754. this.spatialSound = true;
  48755. this._createSpatialParameters();
  48756. if (this.isPlaying && this.loop) {
  48757. this.stop();
  48758. this.play();
  48759. }
  48760. }
  48761. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48762. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48763. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48764. };
  48765. Sound.prototype.detachFromMesh = function () {
  48766. if (this._connectedMesh && this._registerFunc) {
  48767. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48768. this._registerFunc = null;
  48769. this._connectedMesh = null;
  48770. }
  48771. };
  48772. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48773. var boundingInfo = connectedMesh.getBoundingInfo();
  48774. if (!boundingInfo) {
  48775. return;
  48776. }
  48777. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48778. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48779. this._updateDirection();
  48780. }
  48781. };
  48782. Sound.prototype.clone = function () {
  48783. var _this = this;
  48784. if (!this._streaming) {
  48785. var setBufferAndRun = function () {
  48786. if (_this._isReadyToPlay) {
  48787. clonedSound._audioBuffer = _this.getAudioBuffer();
  48788. clonedSound._isReadyToPlay = true;
  48789. if (clonedSound.autoplay) {
  48790. clonedSound.play();
  48791. }
  48792. }
  48793. else {
  48794. window.setTimeout(setBufferAndRun, 300);
  48795. }
  48796. };
  48797. var currentOptions = {
  48798. autoplay: this.autoplay, loop: this.loop,
  48799. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48800. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48801. refDistance: this.refDistance, distanceModel: this.distanceModel
  48802. };
  48803. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48804. if (this.useCustomAttenuation) {
  48805. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48806. }
  48807. clonedSound.setPosition(this._position);
  48808. clonedSound.setPlaybackRate(this._playbackRate);
  48809. setBufferAndRun();
  48810. return clonedSound;
  48811. }
  48812. else {
  48813. return null;
  48814. }
  48815. };
  48816. Sound.prototype.getAudioBuffer = function () {
  48817. return this._audioBuffer;
  48818. };
  48819. Sound.prototype.serialize = function () {
  48820. var serializationObject = {
  48821. name: this.name,
  48822. url: this.name,
  48823. autoplay: this.autoplay,
  48824. loop: this.loop,
  48825. volume: this._volume,
  48826. spatialSound: this.spatialSound,
  48827. maxDistance: this.maxDistance,
  48828. rolloffFactor: this.rolloffFactor,
  48829. refDistance: this.refDistance,
  48830. distanceModel: this.distanceModel,
  48831. playbackRate: this._playbackRate,
  48832. panningModel: this._panningModel,
  48833. soundTrackId: this.soundTrackId
  48834. };
  48835. if (this.spatialSound) {
  48836. if (this._connectedMesh)
  48837. serializationObject.connectedMeshId = this._connectedMesh.id;
  48838. serializationObject.position = this._position.asArray();
  48839. serializationObject.refDistance = this.refDistance;
  48840. serializationObject.distanceModel = this.distanceModel;
  48841. serializationObject.isDirectional = this._isDirectional;
  48842. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48843. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48844. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48845. serializationObject.coneOuterGain = this._coneOuterGain;
  48846. }
  48847. return serializationObject;
  48848. };
  48849. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48850. var soundName = parsedSound.name;
  48851. var soundUrl;
  48852. if (parsedSound.url) {
  48853. soundUrl = rootUrl + parsedSound.url;
  48854. }
  48855. else {
  48856. soundUrl = rootUrl + soundName;
  48857. }
  48858. var options = {
  48859. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48860. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48861. rolloffFactor: parsedSound.rolloffFactor,
  48862. refDistance: parsedSound.refDistance,
  48863. distanceModel: parsedSound.distanceModel,
  48864. playbackRate: parsedSound.playbackRate
  48865. };
  48866. var newSound;
  48867. if (!sourceSound) {
  48868. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48869. scene._addPendingData(newSound);
  48870. }
  48871. else {
  48872. var setBufferAndRun = function () {
  48873. if (sourceSound._isReadyToPlay) {
  48874. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48875. newSound._isReadyToPlay = true;
  48876. if (newSound.autoplay) {
  48877. newSound.play();
  48878. }
  48879. }
  48880. else {
  48881. window.setTimeout(setBufferAndRun, 300);
  48882. }
  48883. };
  48884. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48885. setBufferAndRun();
  48886. }
  48887. if (parsedSound.position) {
  48888. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48889. newSound.setPosition(soundPosition);
  48890. }
  48891. if (parsedSound.isDirectional) {
  48892. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48893. if (parsedSound.localDirectionToMesh) {
  48894. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48895. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48896. }
  48897. }
  48898. if (parsedSound.connectedMeshId) {
  48899. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48900. if (connectedMesh) {
  48901. newSound.attachToMesh(connectedMesh);
  48902. }
  48903. }
  48904. return newSound;
  48905. };
  48906. return Sound;
  48907. }());
  48908. BABYLON.Sound = Sound;
  48909. })(BABYLON || (BABYLON = {}));
  48910. //# sourceMappingURL=babylon.sound.js.map
  48911. var BABYLON;
  48912. (function (BABYLON) {
  48913. var SoundTrack = /** @class */ (function () {
  48914. function SoundTrack(scene, options) {
  48915. this.id = -1;
  48916. this._isMainTrack = false;
  48917. this._isInitialized = false;
  48918. this._scene = scene;
  48919. this.soundCollection = new Array();
  48920. this._options = options;
  48921. if (!this._isMainTrack) {
  48922. this._scene.soundTracks.push(this);
  48923. this.id = this._scene.soundTracks.length - 1;
  48924. }
  48925. }
  48926. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48927. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48928. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48929. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48930. if (this._options) {
  48931. if (this._options.volume) {
  48932. this._outputAudioNode.gain.value = this._options.volume;
  48933. }
  48934. if (this._options.mainTrack) {
  48935. this._isMainTrack = this._options.mainTrack;
  48936. }
  48937. }
  48938. this._isInitialized = true;
  48939. }
  48940. };
  48941. SoundTrack.prototype.dispose = function () {
  48942. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48943. if (this._connectedAnalyser) {
  48944. this._connectedAnalyser.stopDebugCanvas();
  48945. }
  48946. while (this.soundCollection.length) {
  48947. this.soundCollection[0].dispose();
  48948. }
  48949. if (this._outputAudioNode) {
  48950. this._outputAudioNode.disconnect();
  48951. }
  48952. this._outputAudioNode = null;
  48953. }
  48954. };
  48955. SoundTrack.prototype.AddSound = function (sound) {
  48956. if (!this._isInitialized) {
  48957. this._initializeSoundTrackAudioGraph();
  48958. }
  48959. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48960. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48961. }
  48962. if (sound.soundTrackId) {
  48963. if (sound.soundTrackId === -1) {
  48964. this._scene.mainSoundTrack.RemoveSound(sound);
  48965. }
  48966. else {
  48967. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  48968. }
  48969. }
  48970. this.soundCollection.push(sound);
  48971. sound.soundTrackId = this.id;
  48972. };
  48973. SoundTrack.prototype.RemoveSound = function (sound) {
  48974. var index = this.soundCollection.indexOf(sound);
  48975. if (index !== -1) {
  48976. this.soundCollection.splice(index, 1);
  48977. }
  48978. };
  48979. SoundTrack.prototype.setVolume = function (newVolume) {
  48980. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48981. this._outputAudioNode.gain.value = newVolume;
  48982. }
  48983. };
  48984. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  48985. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48986. for (var i = 0; i < this.soundCollection.length; i++) {
  48987. this.soundCollection[i].switchPanningModelToHRTF();
  48988. }
  48989. }
  48990. };
  48991. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  48992. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48993. for (var i = 0; i < this.soundCollection.length; i++) {
  48994. this.soundCollection[i].switchPanningModelToEqualPower();
  48995. }
  48996. }
  48997. };
  48998. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  48999. if (this._connectedAnalyser) {
  49000. this._connectedAnalyser.stopDebugCanvas();
  49001. }
  49002. this._connectedAnalyser = analyser;
  49003. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49004. this._outputAudioNode.disconnect();
  49005. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  49006. }
  49007. };
  49008. return SoundTrack;
  49009. }());
  49010. BABYLON.SoundTrack = SoundTrack;
  49011. })(BABYLON || (BABYLON = {}));
  49012. //# sourceMappingURL=babylon.soundtrack.js.map
  49013. var BABYLON;
  49014. (function (BABYLON) {
  49015. var Analyser = /** @class */ (function () {
  49016. function Analyser(scene) {
  49017. this.SMOOTHING = 0.75;
  49018. this.FFT_SIZE = 512;
  49019. this.BARGRAPHAMPLITUDE = 256;
  49020. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49021. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49022. this._scene = scene;
  49023. this._audioEngine = BABYLON.Engine.audioEngine;
  49024. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  49025. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49026. this._webAudioAnalyser.minDecibels = -140;
  49027. this._webAudioAnalyser.maxDecibels = 0;
  49028. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49029. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49030. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49031. }
  49032. }
  49033. Analyser.prototype.getFrequencyBinCount = function () {
  49034. if (this._audioEngine.canUseWebAudio) {
  49035. return this._webAudioAnalyser.frequencyBinCount;
  49036. }
  49037. else {
  49038. return 0;
  49039. }
  49040. };
  49041. Analyser.prototype.getByteFrequencyData = function () {
  49042. if (this._audioEngine.canUseWebAudio) {
  49043. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49044. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49045. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49046. }
  49047. return this._byteFreqs;
  49048. };
  49049. Analyser.prototype.getByteTimeDomainData = function () {
  49050. if (this._audioEngine.canUseWebAudio) {
  49051. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49052. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49053. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49054. }
  49055. return this._byteTime;
  49056. };
  49057. Analyser.prototype.getFloatFrequencyData = function () {
  49058. if (this._audioEngine.canUseWebAudio) {
  49059. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49060. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49061. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49062. }
  49063. return this._floatFreqs;
  49064. };
  49065. Analyser.prototype.drawDebugCanvas = function () {
  49066. var _this = this;
  49067. if (this._audioEngine.canUseWebAudio) {
  49068. if (!this._debugCanvas) {
  49069. this._debugCanvas = document.createElement("canvas");
  49070. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49071. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49072. this._debugCanvas.style.position = "absolute";
  49073. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49074. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49075. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49076. document.body.appendChild(this._debugCanvas);
  49077. this._registerFunc = function () {
  49078. _this.drawDebugCanvas();
  49079. };
  49080. this._scene.registerBeforeRender(this._registerFunc);
  49081. }
  49082. if (this._registerFunc && this._debugCanvasContext) {
  49083. var workingArray = this.getByteFrequencyData();
  49084. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49085. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49086. // Draw the frequency domain chart.
  49087. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49088. var value = workingArray[i];
  49089. var percent = value / this.BARGRAPHAMPLITUDE;
  49090. var height = this.DEBUGCANVASSIZE.height * percent;
  49091. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49092. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49093. var hue = i / this.getFrequencyBinCount() * 360;
  49094. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49095. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49096. }
  49097. }
  49098. }
  49099. };
  49100. Analyser.prototype.stopDebugCanvas = function () {
  49101. if (this._debugCanvas) {
  49102. if (this._registerFunc) {
  49103. this._scene.unregisterBeforeRender(this._registerFunc);
  49104. this._registerFunc = null;
  49105. }
  49106. document.body.removeChild(this._debugCanvas);
  49107. this._debugCanvas = null;
  49108. this._debugCanvasContext = null;
  49109. }
  49110. };
  49111. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49112. if (this._audioEngine.canUseWebAudio) {
  49113. inputAudioNode.connect(this._webAudioAnalyser);
  49114. this._webAudioAnalyser.connect(outputAudioNode);
  49115. }
  49116. };
  49117. Analyser.prototype.dispose = function () {
  49118. if (this._audioEngine.canUseWebAudio) {
  49119. this._webAudioAnalyser.disconnect();
  49120. }
  49121. };
  49122. return Analyser;
  49123. }());
  49124. BABYLON.Analyser = Analyser;
  49125. })(BABYLON || (BABYLON = {}));
  49126. //# sourceMappingURL=babylon.analyser.js.map
  49127. var BABYLON;
  49128. (function (BABYLON) {
  49129. var CubeTexture = /** @class */ (function (_super) {
  49130. __extends(CubeTexture, _super);
  49131. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49132. if (extensions === void 0) { extensions = null; }
  49133. if (noMipmap === void 0) { noMipmap = false; }
  49134. if (files === void 0) { files = null; }
  49135. if (onLoad === void 0) { onLoad = null; }
  49136. if (onError === void 0) { onError = null; }
  49137. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49138. if (prefiltered === void 0) { prefiltered = false; }
  49139. if (forcedExtension === void 0) { forcedExtension = null; }
  49140. var _this = _super.call(this, scene) || this;
  49141. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49142. _this.name = rootUrl;
  49143. _this.url = rootUrl;
  49144. _this._noMipmap = noMipmap;
  49145. _this.hasAlpha = false;
  49146. _this._format = format;
  49147. _this._prefiltered = prefiltered;
  49148. _this.isCube = true;
  49149. _this._textureMatrix = BABYLON.Matrix.Identity();
  49150. if (prefiltered) {
  49151. _this.gammaSpace = false;
  49152. }
  49153. if (!rootUrl && !files) {
  49154. return _this;
  49155. }
  49156. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49157. if (!files) {
  49158. if (!extensions) {
  49159. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49160. }
  49161. files = [];
  49162. for (var index = 0; index < extensions.length; index++) {
  49163. files.push(rootUrl + extensions[index]);
  49164. }
  49165. _this._extensions = extensions;
  49166. }
  49167. _this._files = files;
  49168. if (!_this._texture) {
  49169. if (!scene.useDelayedTextureLoading) {
  49170. if (prefiltered) {
  49171. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49172. }
  49173. else {
  49174. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49175. }
  49176. }
  49177. else {
  49178. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49179. }
  49180. }
  49181. else if (onLoad) {
  49182. if (_this._texture.isReady) {
  49183. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49184. }
  49185. else {
  49186. _this._texture.onLoadedObservable.add(onLoad);
  49187. }
  49188. }
  49189. return _this;
  49190. }
  49191. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49192. return new CubeTexture("", scene, null, noMipmap, files);
  49193. };
  49194. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49195. if (forcedExtension === void 0) { forcedExtension = null; }
  49196. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49197. };
  49198. // Methods
  49199. CubeTexture.prototype.delayLoad = function () {
  49200. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49201. return;
  49202. }
  49203. var scene = this.getScene();
  49204. if (!scene) {
  49205. return;
  49206. }
  49207. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49208. this._texture = this._getFromCache(this.url, this._noMipmap);
  49209. if (!this._texture) {
  49210. if (this._prefiltered) {
  49211. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49212. }
  49213. else {
  49214. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49215. }
  49216. }
  49217. };
  49218. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49219. return this._textureMatrix;
  49220. };
  49221. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49222. this._textureMatrix = value;
  49223. };
  49224. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49225. var texture = BABYLON.SerializationHelper.Parse(function () {
  49226. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49227. }, parsedTexture, scene);
  49228. // Animations
  49229. if (parsedTexture.animations) {
  49230. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49231. var parsedAnimation = parsedTexture.animations[animationIndex];
  49232. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49233. }
  49234. }
  49235. return texture;
  49236. };
  49237. CubeTexture.prototype.clone = function () {
  49238. var _this = this;
  49239. return BABYLON.SerializationHelper.Clone(function () {
  49240. var scene = _this.getScene();
  49241. if (!scene) {
  49242. return _this;
  49243. }
  49244. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49245. }, this);
  49246. };
  49247. return CubeTexture;
  49248. }(BABYLON.BaseTexture));
  49249. BABYLON.CubeTexture = CubeTexture;
  49250. })(BABYLON || (BABYLON = {}));
  49251. //# sourceMappingURL=babylon.cubeTexture.js.map
  49252. var BABYLON;
  49253. (function (BABYLON) {
  49254. var RenderTargetTexture = /** @class */ (function (_super) {
  49255. __extends(RenderTargetTexture, _super);
  49256. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49257. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49258. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49259. if (isCube === void 0) { isCube = false; }
  49260. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49261. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49262. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49263. if (isMulti === void 0) { isMulti = false; }
  49264. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49265. _this.isCube = isCube;
  49266. /**
  49267. * Use this list to define the list of mesh you want to render.
  49268. */
  49269. _this.renderList = new Array();
  49270. _this.renderParticles = true;
  49271. _this.renderSprites = false;
  49272. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49273. _this.ignoreCameraViewport = false;
  49274. // Events
  49275. /**
  49276. * An event triggered when the texture is unbind.
  49277. * @type {BABYLON.Observable}
  49278. */
  49279. _this.onBeforeBindObservable = new BABYLON.Observable();
  49280. /**
  49281. * An event triggered when the texture is unbind.
  49282. * @type {BABYLON.Observable}
  49283. */
  49284. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49285. /**
  49286. * An event triggered before rendering the texture
  49287. * @type {BABYLON.Observable}
  49288. */
  49289. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49290. /**
  49291. * An event triggered after rendering the texture
  49292. * @type {BABYLON.Observable}
  49293. */
  49294. _this.onAfterRenderObservable = new BABYLON.Observable();
  49295. /**
  49296. * An event triggered after the texture clear
  49297. * @type {BABYLON.Observable}
  49298. */
  49299. _this.onClearObservable = new BABYLON.Observable();
  49300. _this._currentRefreshId = -1;
  49301. _this._refreshRate = 1;
  49302. _this._samples = 1;
  49303. scene = _this.getScene();
  49304. if (!scene) {
  49305. return _this;
  49306. }
  49307. _this._engine = scene.getEngine();
  49308. _this.name = name;
  49309. _this.isRenderTarget = true;
  49310. _this._initialSizeParameter = size;
  49311. _this._processSizeParameter(size);
  49312. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  49313. });
  49314. _this._generateMipMaps = generateMipMaps ? true : false;
  49315. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49316. // Rendering groups
  49317. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49318. if (isMulti) {
  49319. return _this;
  49320. }
  49321. _this._renderTargetOptions = {
  49322. generateMipMaps: generateMipMaps,
  49323. type: type,
  49324. samplingMode: samplingMode,
  49325. generateDepthBuffer: generateDepthBuffer,
  49326. generateStencilBuffer: generateStencilBuffer
  49327. };
  49328. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49329. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49330. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49331. }
  49332. if (isCube) {
  49333. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  49334. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49335. _this._textureMatrix = BABYLON.Matrix.Identity();
  49336. }
  49337. else {
  49338. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  49339. }
  49340. return _this;
  49341. }
  49342. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49343. get: function () {
  49344. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49345. },
  49346. enumerable: true,
  49347. configurable: true
  49348. });
  49349. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49350. get: function () {
  49351. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49352. },
  49353. enumerable: true,
  49354. configurable: true
  49355. });
  49356. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49357. get: function () {
  49358. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49359. },
  49360. enumerable: true,
  49361. configurable: true
  49362. });
  49363. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49364. set: function (callback) {
  49365. if (this._onAfterUnbindObserver) {
  49366. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49367. }
  49368. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49369. },
  49370. enumerable: true,
  49371. configurable: true
  49372. });
  49373. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49374. set: function (callback) {
  49375. if (this._onBeforeRenderObserver) {
  49376. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49377. }
  49378. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49379. },
  49380. enumerable: true,
  49381. configurable: true
  49382. });
  49383. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49384. set: function (callback) {
  49385. if (this._onAfterRenderObserver) {
  49386. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49387. }
  49388. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49389. },
  49390. enumerable: true,
  49391. configurable: true
  49392. });
  49393. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49394. set: function (callback) {
  49395. if (this._onClearObserver) {
  49396. this.onClearObservable.remove(this._onClearObserver);
  49397. }
  49398. this._onClearObserver = this.onClearObservable.add(callback);
  49399. },
  49400. enumerable: true,
  49401. configurable: true
  49402. });
  49403. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49404. get: function () {
  49405. return this._renderTargetOptions;
  49406. },
  49407. enumerable: true,
  49408. configurable: true
  49409. });
  49410. RenderTargetTexture.prototype._onRatioRescale = function () {
  49411. if (this._sizeRatio) {
  49412. this.resize(this._initialSizeParameter);
  49413. }
  49414. };
  49415. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  49416. if (size.ratio) {
  49417. this._sizeRatio = size.ratio;
  49418. this._size = {
  49419. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  49420. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  49421. };
  49422. }
  49423. else {
  49424. this._size = size;
  49425. }
  49426. };
  49427. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49428. get: function () {
  49429. return this._samples;
  49430. },
  49431. set: function (value) {
  49432. if (this._samples === value) {
  49433. return;
  49434. }
  49435. var scene = this.getScene();
  49436. if (!scene) {
  49437. return;
  49438. }
  49439. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49440. },
  49441. enumerable: true,
  49442. configurable: true
  49443. });
  49444. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49445. this._currentRefreshId = -1;
  49446. };
  49447. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49448. get: function () {
  49449. return this._refreshRate;
  49450. },
  49451. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49452. set: function (value) {
  49453. this._refreshRate = value;
  49454. this.resetRefreshCounter();
  49455. },
  49456. enumerable: true,
  49457. configurable: true
  49458. });
  49459. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49460. if (!this._postProcessManager) {
  49461. var scene = this.getScene();
  49462. if (!scene) {
  49463. return;
  49464. }
  49465. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49466. this._postProcesses = new Array();
  49467. }
  49468. this._postProcesses.push(postProcess);
  49469. this._postProcesses[0].autoClear = false;
  49470. };
  49471. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49472. if (!this._postProcesses) {
  49473. return;
  49474. }
  49475. if (dispose) {
  49476. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49477. var postProcess = _a[_i];
  49478. postProcess.dispose();
  49479. }
  49480. }
  49481. this._postProcesses = [];
  49482. };
  49483. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49484. if (!this._postProcesses) {
  49485. return;
  49486. }
  49487. var index = this._postProcesses.indexOf(postProcess);
  49488. if (index === -1) {
  49489. return;
  49490. }
  49491. this._postProcesses.splice(index, 1);
  49492. if (this._postProcesses.length > 0) {
  49493. this._postProcesses[0].autoClear = false;
  49494. }
  49495. };
  49496. RenderTargetTexture.prototype._shouldRender = function () {
  49497. if (this._currentRefreshId === -1) {
  49498. this._currentRefreshId = 1;
  49499. return true;
  49500. }
  49501. if (this.refreshRate === this._currentRefreshId) {
  49502. this._currentRefreshId = 1;
  49503. return true;
  49504. }
  49505. this._currentRefreshId++;
  49506. return false;
  49507. };
  49508. RenderTargetTexture.prototype.getRenderSize = function () {
  49509. if (this._size.width) {
  49510. return this._size.width;
  49511. }
  49512. return this._size;
  49513. };
  49514. RenderTargetTexture.prototype.getRenderWidth = function () {
  49515. if (this._size.width) {
  49516. return this._size.width;
  49517. }
  49518. return this._size;
  49519. };
  49520. RenderTargetTexture.prototype.getRenderHeight = function () {
  49521. if (this._size.width) {
  49522. return this._size.height;
  49523. }
  49524. return this._size;
  49525. };
  49526. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49527. get: function () {
  49528. return true;
  49529. },
  49530. enumerable: true,
  49531. configurable: true
  49532. });
  49533. RenderTargetTexture.prototype.scale = function (ratio) {
  49534. var newSize = this.getRenderSize() * ratio;
  49535. this.resize(newSize);
  49536. };
  49537. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49538. if (this.isCube) {
  49539. return this._textureMatrix;
  49540. }
  49541. return _super.prototype.getReflectionTextureMatrix.call(this);
  49542. };
  49543. RenderTargetTexture.prototype.resize = function (size) {
  49544. this.releaseInternalTexture();
  49545. var scene = this.getScene();
  49546. if (!scene) {
  49547. return;
  49548. }
  49549. this._processSizeParameter(size);
  49550. if (this.isCube) {
  49551. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  49552. }
  49553. else {
  49554. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  49555. }
  49556. };
  49557. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49558. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49559. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49560. var scene = this.getScene();
  49561. if (!scene) {
  49562. return;
  49563. }
  49564. var engine = scene.getEngine();
  49565. if (this.useCameraPostProcesses !== undefined) {
  49566. useCameraPostProcess = this.useCameraPostProcesses;
  49567. }
  49568. if (this._waitingRenderList) {
  49569. this.renderList = [];
  49570. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49571. var id = this._waitingRenderList[index];
  49572. var mesh_1 = scene.getMeshByID(id);
  49573. if (mesh_1) {
  49574. this.renderList.push(mesh_1);
  49575. }
  49576. }
  49577. delete this._waitingRenderList;
  49578. }
  49579. // Is predicate defined?
  49580. if (this.renderListPredicate) {
  49581. if (this.renderList) {
  49582. this.renderList.splice(0); // Clear previous renderList
  49583. }
  49584. else {
  49585. this.renderList = [];
  49586. }
  49587. var scene = this.getScene();
  49588. if (!scene) {
  49589. return;
  49590. }
  49591. var sceneMeshes = scene.meshes;
  49592. for (var index = 0; index < sceneMeshes.length; index++) {
  49593. var mesh = sceneMeshes[index];
  49594. if (this.renderListPredicate(mesh)) {
  49595. this.renderList.push(mesh);
  49596. }
  49597. }
  49598. }
  49599. this.onBeforeBindObservable.notifyObservers(this);
  49600. // Set custom projection.
  49601. // Needs to be before binding to prevent changing the aspect ratio.
  49602. var camera;
  49603. if (this.activeCamera) {
  49604. camera = this.activeCamera;
  49605. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  49606. if (this.activeCamera !== scene.activeCamera) {
  49607. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49608. }
  49609. }
  49610. else {
  49611. camera = scene.activeCamera;
  49612. if (camera) {
  49613. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  49614. }
  49615. }
  49616. // Prepare renderingManager
  49617. this._renderingManager.reset();
  49618. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49619. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49620. var sceneRenderId = scene.getRenderId();
  49621. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49622. var mesh = currentRenderList[meshIndex];
  49623. if (mesh) {
  49624. if (!mesh.isReady()) {
  49625. // Reset _currentRefreshId
  49626. this.resetRefreshCounter();
  49627. continue;
  49628. }
  49629. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49630. var isMasked = void 0;
  49631. if (!this.renderList && camera) {
  49632. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49633. }
  49634. else {
  49635. isMasked = false;
  49636. }
  49637. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49638. mesh._activate(sceneRenderId);
  49639. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49640. var subMesh = mesh.subMeshes[subIndex];
  49641. scene._activeIndices.addCount(subMesh.indexCount, false);
  49642. this._renderingManager.dispatch(subMesh);
  49643. }
  49644. }
  49645. }
  49646. }
  49647. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49648. var particleSystem = scene.particleSystems[particleIndex];
  49649. var emitter = particleSystem.emitter;
  49650. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49651. continue;
  49652. }
  49653. if (currentRenderList.indexOf(emitter) >= 0) {
  49654. this._renderingManager.dispatchParticles(particleSystem);
  49655. }
  49656. }
  49657. if (this.isCube) {
  49658. for (var face = 0; face < 6; face++) {
  49659. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49660. scene.incrementRenderId();
  49661. scene.resetCachedMaterial();
  49662. }
  49663. }
  49664. else {
  49665. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49666. }
  49667. this.onAfterUnbindObservable.notifyObservers(this);
  49668. if (scene.activeCamera) {
  49669. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49670. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49671. }
  49672. engine.setViewport(scene.activeCamera.viewport);
  49673. }
  49674. scene.resetCachedMaterial();
  49675. };
  49676. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  49677. var minimum = 128;
  49678. var x = renderDimension * scale;
  49679. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  49680. // Ensure we don't exceed the render dimension (while staying POT)
  49681. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  49682. };
  49683. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49684. var _this = this;
  49685. var scene = this.getScene();
  49686. if (!scene) {
  49687. return;
  49688. }
  49689. var engine = scene.getEngine();
  49690. if (!this._texture) {
  49691. return;
  49692. }
  49693. // Bind
  49694. if (this._postProcessManager) {
  49695. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49696. }
  49697. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49698. if (this._texture) {
  49699. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49700. }
  49701. }
  49702. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49703. // Clear
  49704. if (this.onClearObservable.hasObservers()) {
  49705. this.onClearObservable.notifyObservers(engine);
  49706. }
  49707. else {
  49708. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49709. }
  49710. if (!this._doNotChangeAspectRatio) {
  49711. scene.updateTransformMatrix(true);
  49712. }
  49713. // Render
  49714. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49715. if (this._postProcessManager) {
  49716. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49717. }
  49718. else if (useCameraPostProcess) {
  49719. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49720. }
  49721. if (!this._doNotChangeAspectRatio) {
  49722. scene.updateTransformMatrix(true);
  49723. }
  49724. // Dump ?
  49725. if (dumpForDebug) {
  49726. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  49727. }
  49728. // Unbind
  49729. if (!this.isCube || faceIndex === 5) {
  49730. if (this.isCube) {
  49731. if (faceIndex === 5) {
  49732. engine.generateMipMapsForCubemap(this._texture);
  49733. }
  49734. }
  49735. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49736. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49737. });
  49738. }
  49739. else {
  49740. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49741. }
  49742. };
  49743. /**
  49744. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49745. * This allowed control for front to back rendering or reversly depending of the special needs.
  49746. *
  49747. * @param renderingGroupId The rendering group id corresponding to its index
  49748. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49749. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49750. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49751. */
  49752. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49753. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49754. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49755. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49756. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49757. };
  49758. /**
  49759. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49760. *
  49761. * @param renderingGroupId The rendering group id corresponding to its index
  49762. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49763. */
  49764. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49765. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49766. };
  49767. RenderTargetTexture.prototype.clone = function () {
  49768. var textureSize = this.getSize();
  49769. 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);
  49770. // Base texture
  49771. newTexture.hasAlpha = this.hasAlpha;
  49772. newTexture.level = this.level;
  49773. // RenderTarget Texture
  49774. newTexture.coordinatesMode = this.coordinatesMode;
  49775. if (this.renderList) {
  49776. newTexture.renderList = this.renderList.slice(0);
  49777. }
  49778. return newTexture;
  49779. };
  49780. RenderTargetTexture.prototype.serialize = function () {
  49781. if (!this.name) {
  49782. return null;
  49783. }
  49784. var serializationObject = _super.prototype.serialize.call(this);
  49785. serializationObject.renderTargetSize = this.getRenderSize();
  49786. serializationObject.renderList = [];
  49787. if (this.renderList) {
  49788. for (var index = 0; index < this.renderList.length; index++) {
  49789. serializationObject.renderList.push(this.renderList[index].id);
  49790. }
  49791. }
  49792. return serializationObject;
  49793. };
  49794. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49795. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49796. var objBuffer = this.getInternalTexture();
  49797. var scene = this.getScene();
  49798. if (objBuffer && scene) {
  49799. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49800. }
  49801. };
  49802. RenderTargetTexture.prototype.dispose = function () {
  49803. if (this._postProcessManager) {
  49804. this._postProcessManager.dispose();
  49805. this._postProcessManager = null;
  49806. }
  49807. this.clearPostProcesses(true);
  49808. if (this._resizeObserver) {
  49809. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  49810. this._resizeObserver = null;
  49811. }
  49812. this.renderList = null;
  49813. // Remove from custom render targets
  49814. var scene = this.getScene();
  49815. if (!scene) {
  49816. return;
  49817. }
  49818. var index = scene.customRenderTargets.indexOf(this);
  49819. if (index >= 0) {
  49820. scene.customRenderTargets.splice(index, 1);
  49821. }
  49822. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49823. var camera = _a[_i];
  49824. index = camera.customRenderTargets.indexOf(this);
  49825. if (index >= 0) {
  49826. camera.customRenderTargets.splice(index, 1);
  49827. }
  49828. }
  49829. _super.prototype.dispose.call(this);
  49830. };
  49831. RenderTargetTexture.prototype._rebuild = function () {
  49832. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49833. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49834. }
  49835. if (this._postProcessManager) {
  49836. this._postProcessManager._rebuild();
  49837. }
  49838. };
  49839. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49840. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49841. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49842. return RenderTargetTexture;
  49843. }(BABYLON.Texture));
  49844. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49845. })(BABYLON || (BABYLON = {}));
  49846. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49847. var BABYLON;
  49848. (function (BABYLON) {
  49849. ;
  49850. var MultiRenderTarget = /** @class */ (function (_super) {
  49851. __extends(MultiRenderTarget, _super);
  49852. function MultiRenderTarget(name, size, count, scene, options) {
  49853. var _this = this;
  49854. options = options || {};
  49855. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  49856. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  49857. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  49858. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  49859. _this._engine = scene.getEngine();
  49860. if (!_this.isSupported) {
  49861. _this.dispose();
  49862. return;
  49863. }
  49864. var types = [];
  49865. var samplingModes = [];
  49866. for (var i = 0; i < count; i++) {
  49867. if (options.types && options.types[i]) {
  49868. types.push(options.types[i]);
  49869. }
  49870. else {
  49871. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49872. }
  49873. if (options.samplingModes && options.samplingModes[i]) {
  49874. samplingModes.push(options.samplingModes[i]);
  49875. }
  49876. else {
  49877. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49878. }
  49879. }
  49880. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49881. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49882. _this._count = count;
  49883. _this._size = size;
  49884. _this._multiRenderTargetOptions = {
  49885. samplingModes: samplingModes,
  49886. generateMipMaps: generateMipMaps,
  49887. generateDepthBuffer: generateDepthBuffer,
  49888. generateStencilBuffer: generateStencilBuffer,
  49889. generateDepthTexture: generateDepthTexture,
  49890. types: types,
  49891. textureCount: count
  49892. };
  49893. _this._createInternalTextures();
  49894. _this._createTextures();
  49895. return _this;
  49896. }
  49897. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49898. get: function () {
  49899. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  49900. },
  49901. enumerable: true,
  49902. configurable: true
  49903. });
  49904. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49905. get: function () {
  49906. return this._textures;
  49907. },
  49908. enumerable: true,
  49909. configurable: true
  49910. });
  49911. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49912. get: function () {
  49913. return this._textures[this._textures.length - 1];
  49914. },
  49915. enumerable: true,
  49916. configurable: true
  49917. });
  49918. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49919. set: function (wrap) {
  49920. if (this._textures) {
  49921. for (var i = 0; i < this._textures.length; i++) {
  49922. this._textures[i].wrapU = wrap;
  49923. }
  49924. }
  49925. },
  49926. enumerable: true,
  49927. configurable: true
  49928. });
  49929. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49930. set: function (wrap) {
  49931. if (this._textures) {
  49932. for (var i = 0; i < this._textures.length; i++) {
  49933. this._textures[i].wrapV = wrap;
  49934. }
  49935. }
  49936. },
  49937. enumerable: true,
  49938. configurable: true
  49939. });
  49940. MultiRenderTarget.prototype._rebuild = function () {
  49941. this.releaseInternalTextures();
  49942. this._createInternalTextures();
  49943. for (var i = 0; i < this._internalTextures.length; i++) {
  49944. var texture = this._textures[i];
  49945. texture._texture = this._internalTextures[i];
  49946. }
  49947. // Keeps references to frame buffer and stencil/depth buffer
  49948. this._texture = this._internalTextures[0];
  49949. };
  49950. MultiRenderTarget.prototype._createInternalTextures = function () {
  49951. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49952. };
  49953. MultiRenderTarget.prototype._createTextures = function () {
  49954. this._textures = [];
  49955. for (var i = 0; i < this._internalTextures.length; i++) {
  49956. var texture = new BABYLON.Texture(null, this.getScene());
  49957. texture._texture = this._internalTextures[i];
  49958. this._textures.push(texture);
  49959. }
  49960. // Keeps references to frame buffer and stencil/depth buffer
  49961. this._texture = this._internalTextures[0];
  49962. };
  49963. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  49964. get: function () {
  49965. return this._samples;
  49966. },
  49967. set: function (value) {
  49968. if (this._samples === value) {
  49969. return;
  49970. }
  49971. for (var i = 0; i < this._internalTextures.length; i++) {
  49972. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  49973. }
  49974. },
  49975. enumerable: true,
  49976. configurable: true
  49977. });
  49978. MultiRenderTarget.prototype.resize = function (size) {
  49979. this.releaseInternalTextures();
  49980. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  49981. this._createInternalTextures();
  49982. };
  49983. MultiRenderTarget.prototype.dispose = function () {
  49984. this.releaseInternalTextures();
  49985. _super.prototype.dispose.call(this);
  49986. };
  49987. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  49988. if (!this._internalTextures) {
  49989. return;
  49990. }
  49991. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  49992. if (this._internalTextures[i] !== undefined) {
  49993. this._internalTextures[i].dispose();
  49994. this._internalTextures.splice(i, 1);
  49995. }
  49996. }
  49997. };
  49998. return MultiRenderTarget;
  49999. }(BABYLON.RenderTargetTexture));
  50000. BABYLON.MultiRenderTarget = MultiRenderTarget;
  50001. })(BABYLON || (BABYLON = {}));
  50002. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  50003. var BABYLON;
  50004. (function (BABYLON) {
  50005. var MirrorTexture = /** @class */ (function (_super) {
  50006. __extends(MirrorTexture, _super);
  50007. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  50008. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50009. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50010. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50011. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  50012. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  50013. _this._transformMatrix = BABYLON.Matrix.Zero();
  50014. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  50015. _this._adaptiveBlurKernel = 0;
  50016. _this._blurKernelX = 0;
  50017. _this._blurKernelY = 0;
  50018. _this._blurRatio = 1.0;
  50019. _this.ignoreCameraViewport = true;
  50020. _this.onBeforeRenderObservable.add(function () {
  50021. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  50022. _this._savedViewMatrix = scene.getViewMatrix();
  50023. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  50024. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  50025. scene.clipPlane = _this.mirrorPlane;
  50026. scene.getEngine().cullBackFaces = false;
  50027. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  50028. });
  50029. _this.onAfterRenderObservable.add(function () {
  50030. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  50031. scene.getEngine().cullBackFaces = true;
  50032. scene._mirroredCameraPosition = null;
  50033. delete scene.clipPlane;
  50034. });
  50035. return _this;
  50036. }
  50037. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  50038. get: function () {
  50039. return this._blurRatio;
  50040. },
  50041. set: function (value) {
  50042. if (this._blurRatio === value) {
  50043. return;
  50044. }
  50045. this._blurRatio = value;
  50046. this._preparePostProcesses();
  50047. },
  50048. enumerable: true,
  50049. configurable: true
  50050. });
  50051. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  50052. set: function (value) {
  50053. this._adaptiveBlurKernel = value;
  50054. this._autoComputeBlurKernel();
  50055. },
  50056. enumerable: true,
  50057. configurable: true
  50058. });
  50059. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  50060. set: function (value) {
  50061. this.blurKernelX = value;
  50062. this.blurKernelY = value;
  50063. },
  50064. enumerable: true,
  50065. configurable: true
  50066. });
  50067. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  50068. get: function () {
  50069. return this._blurKernelX;
  50070. },
  50071. set: function (value) {
  50072. if (this._blurKernelX === value) {
  50073. return;
  50074. }
  50075. this._blurKernelX = value;
  50076. this._preparePostProcesses();
  50077. },
  50078. enumerable: true,
  50079. configurable: true
  50080. });
  50081. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  50082. get: function () {
  50083. return this._blurKernelY;
  50084. },
  50085. set: function (value) {
  50086. if (this._blurKernelY === value) {
  50087. return;
  50088. }
  50089. this._blurKernelY = value;
  50090. this._preparePostProcesses();
  50091. },
  50092. enumerable: true,
  50093. configurable: true
  50094. });
  50095. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  50096. var engine = this.getScene().getEngine();
  50097. var dw = this.getRenderWidth() / engine.getRenderWidth();
  50098. var dh = this.getRenderHeight() / engine.getRenderHeight();
  50099. this.blurKernelX = this._adaptiveBlurKernel * dw;
  50100. this.blurKernelY = this._adaptiveBlurKernel * dh;
  50101. };
  50102. MirrorTexture.prototype._onRatioRescale = function () {
  50103. if (this._sizeRatio) {
  50104. this.resize(this._initialSizeParameter);
  50105. if (!this._adaptiveBlurKernel) {
  50106. this._preparePostProcesses();
  50107. }
  50108. }
  50109. if (this._adaptiveBlurKernel) {
  50110. this._autoComputeBlurKernel();
  50111. }
  50112. };
  50113. MirrorTexture.prototype._preparePostProcesses = function () {
  50114. this.clearPostProcesses(true);
  50115. if (this._blurKernelX && this._blurKernelY) {
  50116. var engine = this.getScene().getEngine();
  50117. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50118. 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);
  50119. this._blurX.autoClear = false;
  50120. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50121. this._blurX.outputTexture = this._texture;
  50122. }
  50123. else {
  50124. this._blurX.alwaysForcePOT = true;
  50125. }
  50126. 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);
  50127. this._blurY.autoClear = false;
  50128. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50129. this.addPostProcess(this._blurX);
  50130. this.addPostProcess(this._blurY);
  50131. }
  50132. };
  50133. MirrorTexture.prototype.clone = function () {
  50134. var scene = this.getScene();
  50135. if (!scene) {
  50136. return this;
  50137. }
  50138. var textureSize = this.getSize();
  50139. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50140. // Base texture
  50141. newTexture.hasAlpha = this.hasAlpha;
  50142. newTexture.level = this.level;
  50143. // Mirror Texture
  50144. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50145. if (this.renderList) {
  50146. newTexture.renderList = this.renderList.slice(0);
  50147. }
  50148. return newTexture;
  50149. };
  50150. MirrorTexture.prototype.serialize = function () {
  50151. if (!this.name) {
  50152. return null;
  50153. }
  50154. var serializationObject = _super.prototype.serialize.call(this);
  50155. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50156. return serializationObject;
  50157. };
  50158. return MirrorTexture;
  50159. }(BABYLON.RenderTargetTexture));
  50160. BABYLON.MirrorTexture = MirrorTexture;
  50161. })(BABYLON || (BABYLON = {}));
  50162. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50163. var BABYLON;
  50164. (function (BABYLON) {
  50165. /**
  50166. * Creates a refraction texture used by refraction channel of the standard material.
  50167. * @param name the texture name
  50168. * @param size size of the underlying texture
  50169. * @param scene root scene
  50170. */
  50171. var RefractionTexture = /** @class */ (function (_super) {
  50172. __extends(RefractionTexture, _super);
  50173. function RefractionTexture(name, size, scene, generateMipMaps) {
  50174. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  50175. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  50176. _this.depth = 2.0;
  50177. _this.onBeforeRenderObservable.add(function () {
  50178. scene.clipPlane = _this.refractionPlane;
  50179. });
  50180. _this.onAfterRenderObservable.add(function () {
  50181. delete scene.clipPlane;
  50182. });
  50183. return _this;
  50184. }
  50185. RefractionTexture.prototype.clone = function () {
  50186. var scene = this.getScene();
  50187. if (!scene) {
  50188. return this;
  50189. }
  50190. var textureSize = this.getSize();
  50191. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  50192. // Base texture
  50193. newTexture.hasAlpha = this.hasAlpha;
  50194. newTexture.level = this.level;
  50195. // Refraction Texture
  50196. newTexture.refractionPlane = this.refractionPlane.clone();
  50197. if (this.renderList) {
  50198. newTexture.renderList = this.renderList.slice(0);
  50199. }
  50200. newTexture.depth = this.depth;
  50201. return newTexture;
  50202. };
  50203. RefractionTexture.prototype.serialize = function () {
  50204. if (!this.name) {
  50205. return null;
  50206. }
  50207. var serializationObject = _super.prototype.serialize.call(this);
  50208. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  50209. serializationObject.depth = this.depth;
  50210. return serializationObject;
  50211. };
  50212. return RefractionTexture;
  50213. }(BABYLON.RenderTargetTexture));
  50214. BABYLON.RefractionTexture = RefractionTexture;
  50215. })(BABYLON || (BABYLON = {}));
  50216. //# sourceMappingURL=babylon.refractionTexture.js.map
  50217. var BABYLON;
  50218. (function (BABYLON) {
  50219. var DynamicTexture = /** @class */ (function (_super) {
  50220. __extends(DynamicTexture, _super);
  50221. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50222. if (scene === void 0) { scene = null; }
  50223. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50224. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50225. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50226. _this.name = name;
  50227. _this._engine = _this.getScene().getEngine();
  50228. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50229. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50230. _this._generateMipMaps = generateMipMaps;
  50231. if (options.getContext) {
  50232. _this._canvas = options;
  50233. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50234. }
  50235. else {
  50236. _this._canvas = document.createElement("canvas");
  50237. if (options.width) {
  50238. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50239. }
  50240. else {
  50241. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50242. }
  50243. }
  50244. var textureSize = _this.getSize();
  50245. _this._canvas.width = textureSize.width;
  50246. _this._canvas.height = textureSize.height;
  50247. _this._context = _this._canvas.getContext("2d");
  50248. return _this;
  50249. }
  50250. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50251. get: function () {
  50252. return true;
  50253. },
  50254. enumerable: true,
  50255. configurable: true
  50256. });
  50257. DynamicTexture.prototype._recreate = function (textureSize) {
  50258. this._canvas.width = textureSize.width;
  50259. this._canvas.height = textureSize.height;
  50260. this.releaseInternalTexture();
  50261. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50262. };
  50263. DynamicTexture.prototype.scale = function (ratio) {
  50264. var textureSize = this.getSize();
  50265. textureSize.width *= ratio;
  50266. textureSize.height *= ratio;
  50267. this._recreate(textureSize);
  50268. };
  50269. DynamicTexture.prototype.scaleTo = function (width, height) {
  50270. var textureSize = this.getSize();
  50271. textureSize.width = width;
  50272. textureSize.height = height;
  50273. this._recreate(textureSize);
  50274. };
  50275. DynamicTexture.prototype.getContext = function () {
  50276. return this._context;
  50277. };
  50278. DynamicTexture.prototype.clear = function () {
  50279. var size = this.getSize();
  50280. this._context.fillRect(0, 0, size.width, size.height);
  50281. };
  50282. DynamicTexture.prototype.update = function (invertY) {
  50283. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50284. };
  50285. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50286. if (update === void 0) { update = true; }
  50287. var size = this.getSize();
  50288. if (clearColor) {
  50289. this._context.fillStyle = clearColor;
  50290. this._context.fillRect(0, 0, size.width, size.height);
  50291. }
  50292. this._context.font = font;
  50293. if (x === null || x === undefined) {
  50294. var textSize = this._context.measureText(text);
  50295. x = (size.width - textSize.width) / 2;
  50296. }
  50297. if (y === null || y === undefined) {
  50298. var fontSize = parseInt((font.replace(/\D/g, '')));
  50299. ;
  50300. y = (size.height / 2) + (fontSize / 3.65);
  50301. }
  50302. this._context.fillStyle = color;
  50303. this._context.fillText(text, x, y);
  50304. if (update) {
  50305. this.update(invertY);
  50306. }
  50307. };
  50308. DynamicTexture.prototype.clone = function () {
  50309. var scene = this.getScene();
  50310. if (!scene) {
  50311. return this;
  50312. }
  50313. var textureSize = this.getSize();
  50314. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50315. // Base texture
  50316. newTexture.hasAlpha = this.hasAlpha;
  50317. newTexture.level = this.level;
  50318. // Dynamic Texture
  50319. newTexture.wrapU = this.wrapU;
  50320. newTexture.wrapV = this.wrapV;
  50321. return newTexture;
  50322. };
  50323. DynamicTexture.prototype._rebuild = function () {
  50324. this.update();
  50325. };
  50326. return DynamicTexture;
  50327. }(BABYLON.Texture));
  50328. BABYLON.DynamicTexture = DynamicTexture;
  50329. })(BABYLON || (BABYLON = {}));
  50330. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50331. var BABYLON;
  50332. (function (BABYLON) {
  50333. var VideoTexture = /** @class */ (function (_super) {
  50334. __extends(VideoTexture, _super);
  50335. /**
  50336. * Creates a video texture.
  50337. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50338. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50339. * @param {BABYLON.Scene} scene is obviously the current scene.
  50340. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50341. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50342. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50343. */
  50344. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50345. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50346. if (invertY === void 0) { invertY = false; }
  50347. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50348. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50349. _this._autoLaunch = true;
  50350. var urls = null;
  50351. _this.name = name;
  50352. if (urlsOrVideo instanceof HTMLVideoElement) {
  50353. _this.video = urlsOrVideo;
  50354. }
  50355. else {
  50356. urls = urlsOrVideo;
  50357. _this.video = document.createElement("video");
  50358. _this.video.autoplay = false;
  50359. _this.video.loop = true;
  50360. }
  50361. _this._engine = _this.getScene().getEngine();
  50362. _this._generateMipMaps = generateMipMaps;
  50363. _this._samplingMode = samplingMode;
  50364. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50365. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50366. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50367. }
  50368. else {
  50369. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50370. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50371. _this._generateMipMaps = false;
  50372. }
  50373. if (urls) {
  50374. _this.video.addEventListener("canplay", function () {
  50375. _this._createTexture();
  50376. });
  50377. urls.forEach(function (url) {
  50378. var source = document.createElement("source");
  50379. source.src = url;
  50380. _this.video.appendChild(source);
  50381. });
  50382. }
  50383. else {
  50384. _this._createTexture();
  50385. }
  50386. _this._lastUpdate = BABYLON.Tools.Now;
  50387. return _this;
  50388. }
  50389. VideoTexture.prototype.__setTextureReady = function () {
  50390. if (this._texture) {
  50391. this._texture.isReady = true;
  50392. }
  50393. };
  50394. VideoTexture.prototype._createTexture = function () {
  50395. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50396. if (this._autoLaunch) {
  50397. this._autoLaunch = false;
  50398. this.video.play();
  50399. }
  50400. this._setTextureReady = this.__setTextureReady.bind(this);
  50401. this.video.addEventListener("playing", this._setTextureReady);
  50402. };
  50403. VideoTexture.prototype._rebuild = function () {
  50404. this.update();
  50405. };
  50406. VideoTexture.prototype.update = function () {
  50407. var now = BABYLON.Tools.Now;
  50408. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50409. return false;
  50410. }
  50411. this._lastUpdate = now;
  50412. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50413. return true;
  50414. };
  50415. VideoTexture.prototype.dispose = function () {
  50416. _super.prototype.dispose.call(this);
  50417. this.video.removeEventListener("playing", this._setTextureReady);
  50418. };
  50419. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50420. var video = document.createElement("video");
  50421. var constraintsDeviceId;
  50422. if (constraints && constraints.deviceId) {
  50423. constraintsDeviceId = {
  50424. exact: constraints.deviceId
  50425. };
  50426. }
  50427. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50428. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50429. if (navigator.getUserMedia) {
  50430. navigator.getUserMedia({
  50431. video: {
  50432. deviceId: constraintsDeviceId,
  50433. width: {
  50434. min: (constraints && constraints.minWidth) || 256,
  50435. max: (constraints && constraints.maxWidth) || 640
  50436. },
  50437. height: {
  50438. min: (constraints && constraints.minHeight) || 256,
  50439. max: (constraints && constraints.maxHeight) || 480
  50440. }
  50441. }
  50442. }, function (stream) {
  50443. if (video.mozSrcObject !== undefined) {
  50444. video.mozSrcObject = stream;
  50445. }
  50446. else {
  50447. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50448. }
  50449. video.play();
  50450. if (onReady) {
  50451. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50452. }
  50453. }, function (e) {
  50454. BABYLON.Tools.Error(e.name);
  50455. });
  50456. }
  50457. };
  50458. return VideoTexture;
  50459. }(BABYLON.Texture));
  50460. BABYLON.VideoTexture = VideoTexture;
  50461. })(BABYLON || (BABYLON = {}));
  50462. //# sourceMappingURL=babylon.videoTexture.js.map
  50463. var BABYLON;
  50464. (function (BABYLON) {
  50465. var RawTexture = /** @class */ (function (_super) {
  50466. __extends(RawTexture, _super);
  50467. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50468. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50469. if (invertY === void 0) { invertY = false; }
  50470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50471. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50472. _this.format = format;
  50473. _this._engine = scene.getEngine();
  50474. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50475. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50476. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50477. return _this;
  50478. }
  50479. RawTexture.prototype.update = function (data) {
  50480. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50481. };
  50482. // Statics
  50483. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50484. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50485. if (invertY === void 0) { invertY = false; }
  50486. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50487. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50488. };
  50489. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50490. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50491. if (invertY === void 0) { invertY = false; }
  50492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50493. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50494. };
  50495. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50496. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50497. if (invertY === void 0) { invertY = false; }
  50498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50499. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50500. };
  50501. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50502. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50503. if (invertY === void 0) { invertY = false; }
  50504. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50505. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50506. };
  50507. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50508. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50509. if (invertY === void 0) { invertY = false; }
  50510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50511. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50512. };
  50513. return RawTexture;
  50514. }(BABYLON.Texture));
  50515. BABYLON.RawTexture = RawTexture;
  50516. })(BABYLON || (BABYLON = {}));
  50517. //# sourceMappingURL=babylon.rawTexture.js.map
  50518. var BABYLON;
  50519. (function (BABYLON) {
  50520. var PostProcess = /** @class */ (function () {
  50521. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50523. if (defines === void 0) { defines = null; }
  50524. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50525. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50526. if (blockCompilation === void 0) { blockCompilation = false; }
  50527. this.name = name;
  50528. this.width = -1;
  50529. this.height = -1;
  50530. this.autoClear = true;
  50531. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50532. /*
  50533. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50534. Can only be used on a single postprocess or on the last one of a chain.
  50535. */
  50536. this.enablePixelPerfectMode = false;
  50537. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50538. this.alwaysForcePOT = false;
  50539. this.samples = 1;
  50540. this.adaptScaleToCurrentViewport = false;
  50541. this._reusable = false;
  50542. this._textures = new BABYLON.SmartArray(2);
  50543. this._currentRenderTextureInd = 0;
  50544. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50545. this._texelSize = BABYLON.Vector2.Zero();
  50546. // Events
  50547. /**
  50548. * An event triggered when the postprocess is activated.
  50549. * @type {BABYLON.Observable}
  50550. */
  50551. this.onActivateObservable = new BABYLON.Observable();
  50552. /**
  50553. * An event triggered when the postprocess changes its size.
  50554. * @type {BABYLON.Observable}
  50555. */
  50556. this.onSizeChangedObservable = new BABYLON.Observable();
  50557. /**
  50558. * An event triggered when the postprocess applies its effect.
  50559. * @type {BABYLON.Observable}
  50560. */
  50561. this.onApplyObservable = new BABYLON.Observable();
  50562. /**
  50563. * An event triggered before rendering the postprocess
  50564. * @type {BABYLON.Observable}
  50565. */
  50566. this.onBeforeRenderObservable = new BABYLON.Observable();
  50567. /**
  50568. * An event triggered after rendering the postprocess
  50569. * @type {BABYLON.Observable}
  50570. */
  50571. this.onAfterRenderObservable = new BABYLON.Observable();
  50572. if (camera != null) {
  50573. this._camera = camera;
  50574. this._scene = camera.getScene();
  50575. camera.attachPostProcess(this);
  50576. this._engine = this._scene.getEngine();
  50577. this._scene.postProcesses.push(this);
  50578. }
  50579. else if (engine) {
  50580. this._engine = engine;
  50581. this._engine.postProcesses.push(this);
  50582. }
  50583. this._options = options;
  50584. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50585. this._reusable = reusable || false;
  50586. this._textureType = textureType;
  50587. this._samplers = samplers || [];
  50588. this._samplers.push("textureSampler");
  50589. this._fragmentUrl = fragmentUrl;
  50590. this._vertexUrl = vertexUrl;
  50591. this._parameters = parameters || [];
  50592. this._parameters.push("scale");
  50593. this._indexParameters = indexParameters;
  50594. if (!blockCompilation) {
  50595. this.updateEffect(defines);
  50596. }
  50597. }
  50598. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50599. set: function (callback) {
  50600. if (this._onActivateObserver) {
  50601. this.onActivateObservable.remove(this._onActivateObserver);
  50602. }
  50603. if (callback) {
  50604. this._onActivateObserver = this.onActivateObservable.add(callback);
  50605. }
  50606. },
  50607. enumerable: true,
  50608. configurable: true
  50609. });
  50610. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50611. set: function (callback) {
  50612. if (this._onSizeChangedObserver) {
  50613. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50614. }
  50615. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50616. },
  50617. enumerable: true,
  50618. configurable: true
  50619. });
  50620. Object.defineProperty(PostProcess.prototype, "onApply", {
  50621. set: function (callback) {
  50622. if (this._onApplyObserver) {
  50623. this.onApplyObservable.remove(this._onApplyObserver);
  50624. }
  50625. this._onApplyObserver = this.onApplyObservable.add(callback);
  50626. },
  50627. enumerable: true,
  50628. configurable: true
  50629. });
  50630. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50631. set: function (callback) {
  50632. if (this._onBeforeRenderObserver) {
  50633. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50634. }
  50635. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50636. },
  50637. enumerable: true,
  50638. configurable: true
  50639. });
  50640. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50641. set: function (callback) {
  50642. if (this._onAfterRenderObserver) {
  50643. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50644. }
  50645. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50646. },
  50647. enumerable: true,
  50648. configurable: true
  50649. });
  50650. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50651. get: function () {
  50652. return this._textures.data[this._currentRenderTextureInd];
  50653. },
  50654. set: function (value) {
  50655. this._forcedOutputTexture = value;
  50656. },
  50657. enumerable: true,
  50658. configurable: true
  50659. });
  50660. PostProcess.prototype.getCamera = function () {
  50661. return this._camera;
  50662. };
  50663. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50664. get: function () {
  50665. if (this._shareOutputWithPostProcess) {
  50666. return this._shareOutputWithPostProcess.texelSize;
  50667. }
  50668. if (this._forcedOutputTexture) {
  50669. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50670. }
  50671. return this._texelSize;
  50672. },
  50673. enumerable: true,
  50674. configurable: true
  50675. });
  50676. PostProcess.prototype.getEngine = function () {
  50677. return this._engine;
  50678. };
  50679. PostProcess.prototype.getEffect = function () {
  50680. return this._effect;
  50681. };
  50682. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50683. this._disposeTextures();
  50684. this._shareOutputWithPostProcess = postProcess;
  50685. return this;
  50686. };
  50687. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50688. if (defines === void 0) { defines = null; }
  50689. if (uniforms === void 0) { uniforms = null; }
  50690. if (samplers === void 0) { samplers = null; }
  50691. 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);
  50692. };
  50693. PostProcess.prototype.isReusable = function () {
  50694. return this._reusable;
  50695. };
  50696. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50697. PostProcess.prototype.markTextureDirty = function () {
  50698. this.width = -1;
  50699. };
  50700. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50701. var _this = this;
  50702. if (sourceTexture === void 0) { sourceTexture = null; }
  50703. camera = camera || this._camera;
  50704. var scene = camera.getScene();
  50705. var engine = scene.getEngine();
  50706. var maxSize = engine.getCaps().maxTextureSize;
  50707. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50708. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50709. var desiredWidth = (this._options.width || requiredWidth);
  50710. var desiredHeight = this._options.height || requiredHeight;
  50711. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50712. if (this.adaptScaleToCurrentViewport) {
  50713. var currentViewport = engine.currentViewport;
  50714. if (currentViewport) {
  50715. desiredWidth *= currentViewport.width;
  50716. desiredHeight *= currentViewport.height;
  50717. }
  50718. }
  50719. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50720. if (!this._options.width) {
  50721. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50722. }
  50723. if (!this._options.height) {
  50724. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50725. }
  50726. }
  50727. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50728. if (this._textures.length > 0) {
  50729. for (var i = 0; i < this._textures.length; i++) {
  50730. this._engine._releaseTexture(this._textures.data[i]);
  50731. }
  50732. this._textures.reset();
  50733. }
  50734. this.width = desiredWidth;
  50735. this.height = desiredHeight;
  50736. var textureSize = { width: this.width, height: this.height };
  50737. var textureOptions = {
  50738. generateMipMaps: false,
  50739. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50740. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50741. samplingMode: this.renderTargetSamplingMode,
  50742. type: this._textureType
  50743. };
  50744. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50745. if (this._reusable) {
  50746. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50747. }
  50748. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50749. this.onSizeChangedObservable.notifyObservers(this);
  50750. }
  50751. this._textures.forEach(function (texture) {
  50752. if (texture.samples !== _this.samples) {
  50753. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50754. }
  50755. });
  50756. }
  50757. var target;
  50758. if (this._shareOutputWithPostProcess) {
  50759. target = this._shareOutputWithPostProcess.outputTexture;
  50760. }
  50761. else if (this._forcedOutputTexture) {
  50762. target = this._forcedOutputTexture;
  50763. this.width = this._forcedOutputTexture.width;
  50764. this.height = this._forcedOutputTexture.height;
  50765. }
  50766. else {
  50767. target = this.outputTexture;
  50768. }
  50769. if (this.enablePixelPerfectMode) {
  50770. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50771. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50772. }
  50773. else {
  50774. this._scaleRatio.copyFromFloats(1, 1);
  50775. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50776. }
  50777. this.onActivateObservable.notifyObservers(camera);
  50778. // Clear
  50779. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50780. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50781. }
  50782. if (this._reusable) {
  50783. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50784. }
  50785. };
  50786. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50787. get: function () {
  50788. return this._effect.isSupported;
  50789. },
  50790. enumerable: true,
  50791. configurable: true
  50792. });
  50793. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50794. get: function () {
  50795. if (this._shareOutputWithPostProcess) {
  50796. return this._shareOutputWithPostProcess.aspectRatio;
  50797. }
  50798. if (this._forcedOutputTexture) {
  50799. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50800. }
  50801. return this.width / this.height;
  50802. },
  50803. enumerable: true,
  50804. configurable: true
  50805. });
  50806. PostProcess.prototype.apply = function () {
  50807. // Check
  50808. if (!this._effect || !this._effect.isReady())
  50809. return null;
  50810. // States
  50811. this._engine.enableEffect(this._effect);
  50812. this._engine.setState(false);
  50813. this._engine.setDepthBuffer(false);
  50814. this._engine.setDepthWrite(false);
  50815. // Alpha
  50816. this._engine.setAlphaMode(this.alphaMode);
  50817. if (this.alphaConstants) {
  50818. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50819. }
  50820. // Texture
  50821. var source;
  50822. if (this._shareOutputWithPostProcess) {
  50823. source = this._shareOutputWithPostProcess.outputTexture;
  50824. }
  50825. else if (this._forcedOutputTexture) {
  50826. source = this._forcedOutputTexture;
  50827. }
  50828. else {
  50829. source = this.outputTexture;
  50830. }
  50831. this._effect._bindTexture("textureSampler", source);
  50832. // Parameters
  50833. this._effect.setVector2("scale", this._scaleRatio);
  50834. this.onApplyObservable.notifyObservers(this._effect);
  50835. return this._effect;
  50836. };
  50837. PostProcess.prototype._disposeTextures = function () {
  50838. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50839. return;
  50840. }
  50841. if (this._textures.length > 0) {
  50842. for (var i = 0; i < this._textures.length; i++) {
  50843. this._engine._releaseTexture(this._textures.data[i]);
  50844. }
  50845. }
  50846. this._textures.dispose();
  50847. };
  50848. PostProcess.prototype.dispose = function (camera) {
  50849. camera = camera || this._camera;
  50850. this._disposeTextures();
  50851. if (this._scene) {
  50852. var index_1 = this._scene.postProcesses.indexOf(this);
  50853. if (index_1 !== -1) {
  50854. this._scene.postProcesses.splice(index_1, 1);
  50855. }
  50856. }
  50857. else {
  50858. var index_2 = this._engine.postProcesses.indexOf(this);
  50859. if (index_2 !== -1) {
  50860. this._engine.postProcesses.splice(index_2, 1);
  50861. }
  50862. }
  50863. if (!camera) {
  50864. return;
  50865. }
  50866. camera.detachPostProcess(this);
  50867. var index = camera._postProcesses.indexOf(this);
  50868. if (index === 0 && camera._postProcesses.length > 0) {
  50869. this._camera._postProcesses[0].markTextureDirty();
  50870. }
  50871. this.onActivateObservable.clear();
  50872. this.onAfterRenderObservable.clear();
  50873. this.onApplyObservable.clear();
  50874. this.onBeforeRenderObservable.clear();
  50875. this.onSizeChangedObservable.clear();
  50876. };
  50877. return PostProcess;
  50878. }());
  50879. BABYLON.PostProcess = PostProcess;
  50880. })(BABYLON || (BABYLON = {}));
  50881. //# sourceMappingURL=babylon.postProcess.js.map
  50882. var BABYLON;
  50883. (function (BABYLON) {
  50884. var PassPostProcess = /** @class */ (function (_super) {
  50885. __extends(PassPostProcess, _super);
  50886. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50887. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50888. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  50889. }
  50890. return PassPostProcess;
  50891. }(BABYLON.PostProcess));
  50892. BABYLON.PassPostProcess = PassPostProcess;
  50893. })(BABYLON || (BABYLON = {}));
  50894. //# sourceMappingURL=babylon.passPostProcess.js.map
  50895. var BABYLON;
  50896. (function (BABYLON) {
  50897. var ShadowGenerator = /** @class */ (function () {
  50898. /**
  50899. * Creates a ShadowGenerator object.
  50900. * A ShadowGenerator is the required tool to use the shadows.
  50901. * Each light casting shadows needs to use its own ShadowGenerator.
  50902. * Required parameters :
  50903. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  50904. * - `light`: the light object generating the shadows.
  50905. * - `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.
  50906. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  50907. */
  50908. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  50909. // Members
  50910. this._bias = 0.00005;
  50911. this._blurBoxOffset = 1;
  50912. this._blurScale = 2;
  50913. this._blurKernel = 1;
  50914. this._useKernelBlur = false;
  50915. this._filter = ShadowGenerator.FILTER_NONE;
  50916. this._darkness = 0;
  50917. this._transparencyShadow = false;
  50918. /**
  50919. * Controls the extent to which the shadows fade out at the edge of the frustum
  50920. * Used only by directionals and spots
  50921. */
  50922. this.frustumEdgeFalloff = 0;
  50923. this.forceBackFacesOnly = false;
  50924. this._lightDirection = BABYLON.Vector3.Zero();
  50925. this._viewMatrix = BABYLON.Matrix.Zero();
  50926. this._projectionMatrix = BABYLON.Matrix.Zero();
  50927. this._transformMatrix = BABYLON.Matrix.Zero();
  50928. this._currentFaceIndex = 0;
  50929. this._currentFaceIndexCache = 0;
  50930. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50931. this._mapSize = mapSize;
  50932. this._light = light;
  50933. this._scene = light.getScene();
  50934. light._shadowGenerator = this;
  50935. // Texture type fallback from float to int if not supported.
  50936. var caps = this._scene.getEngine().getCaps();
  50937. if (!useFullFloatFirst) {
  50938. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50939. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50940. }
  50941. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50942. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50943. }
  50944. else {
  50945. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50946. }
  50947. }
  50948. else {
  50949. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50950. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50951. }
  50952. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50953. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50954. }
  50955. else {
  50956. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50957. }
  50958. }
  50959. this._initializeGenerator();
  50960. }
  50961. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  50962. // Static
  50963. get: function () {
  50964. return ShadowGenerator._FILTER_NONE;
  50965. },
  50966. enumerable: true,
  50967. configurable: true
  50968. });
  50969. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  50970. get: function () {
  50971. return ShadowGenerator._FILTER_POISSONSAMPLING;
  50972. },
  50973. enumerable: true,
  50974. configurable: true
  50975. });
  50976. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  50977. get: function () {
  50978. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  50979. },
  50980. enumerable: true,
  50981. configurable: true
  50982. });
  50983. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  50984. get: function () {
  50985. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  50986. },
  50987. enumerable: true,
  50988. configurable: true
  50989. });
  50990. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  50991. get: function () {
  50992. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50993. },
  50994. enumerable: true,
  50995. configurable: true
  50996. });
  50997. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  50998. get: function () {
  50999. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51000. },
  51001. enumerable: true,
  51002. configurable: true
  51003. });
  51004. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  51005. get: function () {
  51006. return this._bias;
  51007. },
  51008. set: function (bias) {
  51009. this._bias = bias;
  51010. },
  51011. enumerable: true,
  51012. configurable: true
  51013. });
  51014. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  51015. get: function () {
  51016. return this._blurBoxOffset;
  51017. },
  51018. set: function (value) {
  51019. if (this._blurBoxOffset === value) {
  51020. return;
  51021. }
  51022. this._blurBoxOffset = value;
  51023. this._disposeBlurPostProcesses();
  51024. },
  51025. enumerable: true,
  51026. configurable: true
  51027. });
  51028. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  51029. get: function () {
  51030. return this._blurScale;
  51031. },
  51032. set: function (value) {
  51033. if (this._blurScale === value) {
  51034. return;
  51035. }
  51036. this._blurScale = value;
  51037. this._disposeBlurPostProcesses();
  51038. },
  51039. enumerable: true,
  51040. configurable: true
  51041. });
  51042. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  51043. get: function () {
  51044. return this._blurKernel;
  51045. },
  51046. set: function (value) {
  51047. if (this._blurKernel === value) {
  51048. return;
  51049. }
  51050. this._blurKernel = value;
  51051. this._disposeBlurPostProcesses();
  51052. },
  51053. enumerable: true,
  51054. configurable: true
  51055. });
  51056. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  51057. get: function () {
  51058. return this._useKernelBlur;
  51059. },
  51060. set: function (value) {
  51061. if (this._useKernelBlur === value) {
  51062. return;
  51063. }
  51064. this._useKernelBlur = value;
  51065. this._disposeBlurPostProcesses();
  51066. },
  51067. enumerable: true,
  51068. configurable: true
  51069. });
  51070. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  51071. get: function () {
  51072. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  51073. },
  51074. set: function (value) {
  51075. this._depthScale = value;
  51076. },
  51077. enumerable: true,
  51078. configurable: true
  51079. });
  51080. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  51081. get: function () {
  51082. return this._filter;
  51083. },
  51084. set: function (value) {
  51085. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  51086. if (this._light.needCube()) {
  51087. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51088. this.useExponentialShadowMap = true;
  51089. return;
  51090. }
  51091. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51092. this.useCloseExponentialShadowMap = true;
  51093. return;
  51094. }
  51095. }
  51096. if (this._filter === value) {
  51097. return;
  51098. }
  51099. this._filter = value;
  51100. this._disposeBlurPostProcesses();
  51101. this._applyFilterValues();
  51102. this._light._markMeshesAsLightDirty();
  51103. },
  51104. enumerable: true,
  51105. configurable: true
  51106. });
  51107. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  51108. get: function () {
  51109. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  51110. },
  51111. set: function (value) {
  51112. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  51113. return;
  51114. }
  51115. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  51116. },
  51117. enumerable: true,
  51118. configurable: true
  51119. });
  51120. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  51121. get: function () {
  51122. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51123. return this.useExponentialShadowMap;
  51124. },
  51125. set: function (value) {
  51126. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51127. this.useExponentialShadowMap = value;
  51128. },
  51129. enumerable: true,
  51130. configurable: true
  51131. });
  51132. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51133. get: function () {
  51134. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51135. return this.useBlurExponentialShadowMap;
  51136. },
  51137. set: function (value) {
  51138. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51139. this.useBlurExponentialShadowMap = value;
  51140. },
  51141. enumerable: true,
  51142. configurable: true
  51143. });
  51144. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51145. get: function () {
  51146. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51147. },
  51148. set: function (value) {
  51149. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51150. return;
  51151. }
  51152. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51153. },
  51154. enumerable: true,
  51155. configurable: true
  51156. });
  51157. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51158. get: function () {
  51159. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51160. },
  51161. set: function (value) {
  51162. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51163. return;
  51164. }
  51165. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51166. },
  51167. enumerable: true,
  51168. configurable: true
  51169. });
  51170. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  51171. get: function () {
  51172. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51173. },
  51174. set: function (value) {
  51175. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  51176. return;
  51177. }
  51178. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51179. },
  51180. enumerable: true,
  51181. configurable: true
  51182. });
  51183. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  51184. get: function () {
  51185. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51186. },
  51187. set: function (value) {
  51188. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51189. return;
  51190. }
  51191. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51192. },
  51193. enumerable: true,
  51194. configurable: true
  51195. });
  51196. /**
  51197. * Returns the darkness value (float).
  51198. */
  51199. ShadowGenerator.prototype.getDarkness = function () {
  51200. return this._darkness;
  51201. };
  51202. /**
  51203. * Sets the ShadowGenerator darkness value (float <= 1.0).
  51204. * Returns the ShadowGenerator.
  51205. */
  51206. ShadowGenerator.prototype.setDarkness = function (darkness) {
  51207. if (darkness >= 1.0)
  51208. this._darkness = 1.0;
  51209. else if (darkness <= 0.0)
  51210. this._darkness = 0.0;
  51211. else
  51212. this._darkness = darkness;
  51213. return this;
  51214. };
  51215. /**
  51216. * Sets the ability to have transparent shadow (boolean).
  51217. * Returns the ShadowGenerator.
  51218. */
  51219. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51220. this._transparencyShadow = hasShadow;
  51221. return this;
  51222. };
  51223. /**
  51224. * Returns a RenderTargetTexture object : the shadow map texture.
  51225. */
  51226. ShadowGenerator.prototype.getShadowMap = function () {
  51227. return this._shadowMap;
  51228. };
  51229. /**
  51230. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51231. */
  51232. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51233. if (this._shadowMap2) {
  51234. return this._shadowMap2;
  51235. }
  51236. return this._shadowMap;
  51237. };
  51238. /**
  51239. * Helper function to add a mesh and its descendants to the list of shadow casters
  51240. * @param mesh Mesh to add
  51241. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51242. */
  51243. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51244. if (includeDescendants === void 0) { includeDescendants = true; }
  51245. if (!this._shadowMap) {
  51246. return this;
  51247. }
  51248. if (!this._shadowMap.renderList) {
  51249. this._shadowMap.renderList = [];
  51250. }
  51251. this._shadowMap.renderList.push(mesh);
  51252. if (includeDescendants) {
  51253. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51254. }
  51255. return this;
  51256. var _a;
  51257. };
  51258. /**
  51259. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51260. * @param mesh Mesh to remove
  51261. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51262. */
  51263. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51264. if (includeDescendants === void 0) { includeDescendants = true; }
  51265. if (!this._shadowMap || !this._shadowMap.renderList) {
  51266. return this;
  51267. }
  51268. var index = this._shadowMap.renderList.indexOf(mesh);
  51269. if (index !== -1) {
  51270. this._shadowMap.renderList.splice(index, 1);
  51271. }
  51272. if (includeDescendants) {
  51273. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51274. var child = _a[_i];
  51275. this.removeShadowCaster(child);
  51276. }
  51277. }
  51278. return this;
  51279. };
  51280. /**
  51281. * Returns the associated light object.
  51282. */
  51283. ShadowGenerator.prototype.getLight = function () {
  51284. return this._light;
  51285. };
  51286. ShadowGenerator.prototype._initializeGenerator = function () {
  51287. this._light._markMeshesAsLightDirty();
  51288. this._initializeShadowMap();
  51289. };
  51290. ShadowGenerator.prototype._initializeShadowMap = function () {
  51291. var _this = this;
  51292. // Render target
  51293. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51294. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51295. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51296. this._shadowMap.anisotropicFilteringLevel = 1;
  51297. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51298. this._shadowMap.renderParticles = false;
  51299. this._shadowMap.ignoreCameraViewport = true;
  51300. // Record Face Index before render.
  51301. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51302. _this._currentFaceIndex = faceIndex;
  51303. });
  51304. // Custom render function.
  51305. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51306. // Blur if required afer render.
  51307. this._shadowMap.onAfterUnbindObservable.add(function () {
  51308. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51309. return;
  51310. }
  51311. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51312. _this._initializeBlurRTTAndPostProcesses();
  51313. }
  51314. var shadowMap = _this.getShadowMapForRendering();
  51315. if (shadowMap) {
  51316. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51317. }
  51318. });
  51319. // Clear according to the chosen filter.
  51320. this._shadowMap.onClearObservable.add(function (engine) {
  51321. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51322. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51323. }
  51324. else {
  51325. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51326. }
  51327. });
  51328. };
  51329. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51330. var _this = this;
  51331. var engine = this._scene.getEngine();
  51332. var targetSize = this._mapSize / this.blurScale;
  51333. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51334. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51335. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51336. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51337. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51338. }
  51339. if (this.useKernelBlur) {
  51340. 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);
  51341. this._kernelBlurXPostprocess.width = targetSize;
  51342. this._kernelBlurXPostprocess.height = targetSize;
  51343. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51344. effect.setTexture("textureSampler", _this._shadowMap);
  51345. });
  51346. 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);
  51347. this._kernelBlurXPostprocess.autoClear = false;
  51348. this._kernelBlurYPostprocess.autoClear = false;
  51349. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51350. this._kernelBlurXPostprocess.packedFloat = true;
  51351. this._kernelBlurYPostprocess.packedFloat = true;
  51352. }
  51353. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51354. }
  51355. else {
  51356. 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);
  51357. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51358. effect.setFloat2("screenSize", targetSize, targetSize);
  51359. effect.setTexture("textureSampler", _this._shadowMap);
  51360. });
  51361. this._boxBlurPostprocess.autoClear = false;
  51362. this._blurPostProcesses = [this._boxBlurPostprocess];
  51363. }
  51364. };
  51365. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51366. var index;
  51367. var engine = this._scene.getEngine();
  51368. if (depthOnlySubMeshes.length) {
  51369. engine.setColorWrite(false);
  51370. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51371. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51372. }
  51373. engine.setColorWrite(true);
  51374. }
  51375. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51376. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51377. }
  51378. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51379. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51380. }
  51381. if (this._transparencyShadow) {
  51382. for (index = 0; index < transparentSubMeshes.length; index++) {
  51383. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51384. }
  51385. }
  51386. };
  51387. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51388. var _this = this;
  51389. var mesh = subMesh.getRenderingMesh();
  51390. var scene = this._scene;
  51391. var engine = scene.getEngine();
  51392. var material = subMesh.getMaterial();
  51393. if (!material) {
  51394. return;
  51395. }
  51396. // Culling
  51397. engine.setState(material.backFaceCulling);
  51398. // Managing instances
  51399. var batch = mesh._getInstancesRenderList(subMesh._id);
  51400. if (batch.mustReturn) {
  51401. return;
  51402. }
  51403. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51404. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51405. engine.enableEffect(this._effect);
  51406. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51407. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51408. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51409. this._effect.setVector3("lightPosition", this.getLight().position);
  51410. if (scene.activeCamera) {
  51411. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51412. }
  51413. // Alpha test
  51414. if (material && material.needAlphaTesting()) {
  51415. var alphaTexture = material.getAlphaTestTexture();
  51416. if (alphaTexture) {
  51417. this._effect.setTexture("diffuseSampler", alphaTexture);
  51418. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51419. }
  51420. }
  51421. // Bones
  51422. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51423. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51424. }
  51425. if (this.forceBackFacesOnly) {
  51426. engine.setState(true, 0, false, true);
  51427. }
  51428. // Draw
  51429. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51430. if (this.forceBackFacesOnly) {
  51431. engine.setState(true, 0, false, false);
  51432. }
  51433. }
  51434. else {
  51435. // Need to reset refresh rate of the shadowMap
  51436. if (this._shadowMap) {
  51437. this._shadowMap.resetRefreshCounter();
  51438. }
  51439. }
  51440. };
  51441. ShadowGenerator.prototype._applyFilterValues = function () {
  51442. if (!this._shadowMap) {
  51443. return;
  51444. }
  51445. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51446. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51447. }
  51448. else {
  51449. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51450. }
  51451. };
  51452. /**
  51453. * Force shader compilation including textures ready check
  51454. */
  51455. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51456. var _this = this;
  51457. var shadowMap = this.getShadowMap();
  51458. if (!shadowMap) {
  51459. return;
  51460. }
  51461. var subMeshes = new Array();
  51462. var currentIndex = 0;
  51463. var renderList = shadowMap.renderList;
  51464. if (!renderList) {
  51465. return;
  51466. }
  51467. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51468. var mesh = renderList_1[_i];
  51469. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51470. }
  51471. var checkReady = function () {
  51472. if (!_this._scene || !_this._scene.getEngine()) {
  51473. return;
  51474. }
  51475. while (_this.isReady(subMeshes[currentIndex], options ? options.useInstances : false)) {
  51476. currentIndex++;
  51477. if (currentIndex >= subMeshes.length) {
  51478. if (onCompiled) {
  51479. onCompiled(_this);
  51480. }
  51481. return;
  51482. }
  51483. }
  51484. setTimeout(checkReady, 16);
  51485. };
  51486. if (subMeshes.length > 0) {
  51487. checkReady();
  51488. }
  51489. };
  51490. /**
  51491. * Boolean : true when the ShadowGenerator is finally computed.
  51492. */
  51493. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51494. var defines = [];
  51495. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51496. defines.push("#define FLOAT");
  51497. }
  51498. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51499. defines.push("#define ESM");
  51500. }
  51501. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51502. var mesh = subMesh.getMesh();
  51503. var material = subMesh.getMaterial();
  51504. // Alpha test
  51505. if (material && material.needAlphaTesting()) {
  51506. var alphaTexture = material.getAlphaTestTexture();
  51507. if (alphaTexture) {
  51508. defines.push("#define ALPHATEST");
  51509. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51510. attribs.push(BABYLON.VertexBuffer.UVKind);
  51511. defines.push("#define UV1");
  51512. }
  51513. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51514. if (alphaTexture.coordinatesIndex === 1) {
  51515. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51516. defines.push("#define UV2");
  51517. }
  51518. }
  51519. }
  51520. }
  51521. // Bones
  51522. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51523. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51524. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51525. if (mesh.numBoneInfluencers > 4) {
  51526. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51527. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51528. }
  51529. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51530. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51531. }
  51532. else {
  51533. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51534. }
  51535. // Instances
  51536. if (useInstances) {
  51537. defines.push("#define INSTANCES");
  51538. attribs.push("world0");
  51539. attribs.push("world1");
  51540. attribs.push("world2");
  51541. attribs.push("world3");
  51542. }
  51543. // Get correct effect
  51544. var join = defines.join("\n");
  51545. if (this._cachedDefines !== join) {
  51546. this._cachedDefines = join;
  51547. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51548. }
  51549. return this._effect.isReady();
  51550. };
  51551. /**
  51552. * This creates the defines related to the standard BJS materials.
  51553. */
  51554. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51555. var scene = this._scene;
  51556. var light = this._light;
  51557. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51558. return;
  51559. }
  51560. defines["SHADOW" + lightIndex] = true;
  51561. if (this.usePoissonSampling) {
  51562. defines["SHADOWPCF" + lightIndex] = true;
  51563. }
  51564. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51565. defines["SHADOWESM" + lightIndex] = true;
  51566. }
  51567. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51568. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51569. }
  51570. if (light.needCube()) {
  51571. defines["SHADOWCUBE" + lightIndex] = true;
  51572. }
  51573. };
  51574. /**
  51575. * This binds shadow lights related to the standard BJS materials.
  51576. * It implies the unifroms available on the materials are the standard BJS ones.
  51577. */
  51578. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51579. var light = this._light;
  51580. var scene = this._scene;
  51581. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51582. return;
  51583. }
  51584. var camera = scene.activeCamera;
  51585. if (!camera) {
  51586. return;
  51587. }
  51588. var shadowMap = this.getShadowMap();
  51589. if (!shadowMap) {
  51590. return;
  51591. }
  51592. if (!light.needCube()) {
  51593. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51594. }
  51595. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51596. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51597. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51598. };
  51599. // Methods
  51600. /**
  51601. * Returns a Matrix object : the updated transformation matrix.
  51602. */
  51603. ShadowGenerator.prototype.getTransformMatrix = function () {
  51604. var scene = this._scene;
  51605. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51606. return this._transformMatrix;
  51607. }
  51608. this._currentRenderID = scene.getRenderId();
  51609. this._currentFaceIndexCache = this._currentFaceIndex;
  51610. var lightPosition = this._light.position;
  51611. if (this._light.computeTransformedInformation()) {
  51612. lightPosition = this._light.transformedPosition;
  51613. }
  51614. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51615. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51616. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51617. }
  51618. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51619. this._cachedPosition = lightPosition.clone();
  51620. this._cachedDirection = this._lightDirection.clone();
  51621. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51622. var shadowMap = this.getShadowMap();
  51623. if (shadowMap) {
  51624. var renderList = shadowMap.renderList;
  51625. if (renderList) {
  51626. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51627. }
  51628. }
  51629. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51630. }
  51631. return this._transformMatrix;
  51632. };
  51633. ShadowGenerator.prototype.recreateShadowMap = function () {
  51634. var shadowMap = this._shadowMap;
  51635. if (!shadowMap) {
  51636. return;
  51637. }
  51638. // Track render list.
  51639. var renderList = shadowMap.renderList;
  51640. // Clean up existing data.
  51641. this._disposeRTTandPostProcesses();
  51642. // Reinitializes.
  51643. this._initializeGenerator();
  51644. // Reaffect the filter to ensure a correct fallback if necessary.
  51645. this.filter = this.filter;
  51646. // Reaffect the filter.
  51647. this._applyFilterValues();
  51648. // Reaffect Render List.
  51649. this._shadowMap.renderList = renderList;
  51650. };
  51651. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51652. if (this._shadowMap2) {
  51653. this._shadowMap2.dispose();
  51654. this._shadowMap2 = null;
  51655. }
  51656. if (this._downSamplePostprocess) {
  51657. this._downSamplePostprocess.dispose();
  51658. this._downSamplePostprocess = null;
  51659. }
  51660. if (this._boxBlurPostprocess) {
  51661. this._boxBlurPostprocess.dispose();
  51662. this._boxBlurPostprocess = null;
  51663. }
  51664. if (this._kernelBlurXPostprocess) {
  51665. this._kernelBlurXPostprocess.dispose();
  51666. this._kernelBlurXPostprocess = null;
  51667. }
  51668. if (this._kernelBlurYPostprocess) {
  51669. this._kernelBlurYPostprocess.dispose();
  51670. this._kernelBlurYPostprocess = null;
  51671. }
  51672. this._blurPostProcesses = [];
  51673. };
  51674. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51675. if (this._shadowMap) {
  51676. this._shadowMap.dispose();
  51677. this._shadowMap = null;
  51678. }
  51679. this._disposeBlurPostProcesses();
  51680. };
  51681. /**
  51682. * Disposes the ShadowGenerator.
  51683. * Returns nothing.
  51684. */
  51685. ShadowGenerator.prototype.dispose = function () {
  51686. this._disposeRTTandPostProcesses();
  51687. if (this._light) {
  51688. this._light._shadowGenerator = null;
  51689. this._light._markMeshesAsLightDirty();
  51690. }
  51691. };
  51692. /**
  51693. * Serializes the ShadowGenerator and returns a serializationObject.
  51694. */
  51695. ShadowGenerator.prototype.serialize = function () {
  51696. var serializationObject = {};
  51697. var shadowMap = this.getShadowMap();
  51698. if (!shadowMap) {
  51699. return serializationObject;
  51700. }
  51701. serializationObject.lightId = this._light.id;
  51702. serializationObject.mapSize = shadowMap.getRenderSize();
  51703. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51704. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51705. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51706. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51707. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51708. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51709. serializationObject.depthScale = this.depthScale;
  51710. serializationObject.darkness = this.getDarkness();
  51711. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51712. serializationObject.blurKernel = this.blurKernel;
  51713. serializationObject.blurScale = this.blurScale;
  51714. serializationObject.useKernelBlur = this.useKernelBlur;
  51715. serializationObject.transparencyShadow = this._transparencyShadow;
  51716. serializationObject.renderList = [];
  51717. if (shadowMap.renderList) {
  51718. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51719. var mesh = shadowMap.renderList[meshIndex];
  51720. serializationObject.renderList.push(mesh.id);
  51721. }
  51722. }
  51723. return serializationObject;
  51724. };
  51725. /**
  51726. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51727. */
  51728. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51729. //casting to point light, as light is missing the position attr and typescript complains.
  51730. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51731. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51732. var shadowMap = shadowGenerator.getShadowMap();
  51733. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51734. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51735. meshes.forEach(function (mesh) {
  51736. if (!shadowMap) {
  51737. return;
  51738. }
  51739. if (!shadowMap.renderList) {
  51740. shadowMap.renderList = [];
  51741. }
  51742. shadowMap.renderList.push(mesh);
  51743. });
  51744. }
  51745. if (parsedShadowGenerator.usePoissonSampling) {
  51746. shadowGenerator.usePoissonSampling = true;
  51747. }
  51748. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51749. shadowGenerator.useExponentialShadowMap = true;
  51750. }
  51751. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51752. shadowGenerator.useBlurExponentialShadowMap = true;
  51753. }
  51754. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51755. shadowGenerator.useCloseExponentialShadowMap = true;
  51756. }
  51757. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51758. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51759. }
  51760. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51761. shadowGenerator.useExponentialShadowMap = true;
  51762. }
  51763. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51764. shadowGenerator.useBlurExponentialShadowMap = true;
  51765. }
  51766. if (parsedShadowGenerator.depthScale) {
  51767. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51768. }
  51769. if (parsedShadowGenerator.blurScale) {
  51770. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51771. }
  51772. if (parsedShadowGenerator.blurBoxOffset) {
  51773. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51774. }
  51775. if (parsedShadowGenerator.useKernelBlur) {
  51776. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51777. }
  51778. if (parsedShadowGenerator.blurKernel) {
  51779. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51780. }
  51781. if (parsedShadowGenerator.bias !== undefined) {
  51782. shadowGenerator.bias = parsedShadowGenerator.bias;
  51783. }
  51784. if (parsedShadowGenerator.darkness) {
  51785. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51786. }
  51787. if (parsedShadowGenerator.transparencyShadow) {
  51788. shadowGenerator.setTransparencyShadow(true);
  51789. }
  51790. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51791. return shadowGenerator;
  51792. };
  51793. ShadowGenerator._FILTER_NONE = 0;
  51794. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51795. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51796. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51797. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51798. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51799. return ShadowGenerator;
  51800. }());
  51801. BABYLON.ShadowGenerator = ShadowGenerator;
  51802. })(BABYLON || (BABYLON = {}));
  51803. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51804. var BABYLON;
  51805. (function (BABYLON) {
  51806. var DefaultLoadingScreen = /** @class */ (function () {
  51807. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51808. if (_loadingText === void 0) { _loadingText = ""; }
  51809. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51810. var _this = this;
  51811. this._renderingCanvas = _renderingCanvas;
  51812. this._loadingText = _loadingText;
  51813. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51814. // Resize
  51815. this._resizeLoadingUI = function () {
  51816. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51817. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51818. if (!_this._loadingDiv) {
  51819. return;
  51820. }
  51821. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51822. _this._loadingDiv.style.left = canvasRect.left + "px";
  51823. _this._loadingDiv.style.top = canvasRect.top + "px";
  51824. _this._loadingDiv.style.width = canvasRect.width + "px";
  51825. _this._loadingDiv.style.height = canvasRect.height + "px";
  51826. };
  51827. }
  51828. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51829. if (this._loadingDiv) {
  51830. // Do not add a loading screen if there is already one
  51831. return;
  51832. }
  51833. this._loadingDiv = document.createElement("div");
  51834. this._loadingDiv.id = "babylonjsLoadingDiv";
  51835. this._loadingDiv.style.opacity = "0";
  51836. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51837. this._loadingDiv.style.pointerEvents = "none";
  51838. // Loading text
  51839. this._loadingTextDiv = document.createElement("div");
  51840. this._loadingTextDiv.style.position = "absolute";
  51841. this._loadingTextDiv.style.left = "0";
  51842. this._loadingTextDiv.style.top = "50%";
  51843. this._loadingTextDiv.style.marginTop = "80px";
  51844. this._loadingTextDiv.style.width = "100%";
  51845. this._loadingTextDiv.style.height = "20px";
  51846. this._loadingTextDiv.style.fontFamily = "Arial";
  51847. this._loadingTextDiv.style.fontSize = "14px";
  51848. this._loadingTextDiv.style.color = "white";
  51849. this._loadingTextDiv.style.textAlign = "center";
  51850. this._loadingTextDiv.innerHTML = "Loading";
  51851. this._loadingDiv.appendChild(this._loadingTextDiv);
  51852. //set the predefined text
  51853. this._loadingTextDiv.innerHTML = this._loadingText;
  51854. // Generating keyframes
  51855. var style = document.createElement('style');
  51856. style.type = 'text/css';
  51857. 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 }";
  51858. style.innerHTML = keyFrames;
  51859. document.getElementsByTagName('head')[0].appendChild(style);
  51860. // Loading img
  51861. var imgBack = new Image();
  51862. 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";
  51863. imgBack.style.position = "absolute";
  51864. imgBack.style.left = "50%";
  51865. imgBack.style.top = "50%";
  51866. imgBack.style.marginLeft = "-60px";
  51867. imgBack.style.marginTop = "-60px";
  51868. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  51869. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  51870. imgBack.style.transformOrigin = "50% 50%";
  51871. imgBack.style.webkitTransformOrigin = "50% 50%";
  51872. this._loadingDiv.appendChild(imgBack);
  51873. this._resizeLoadingUI();
  51874. window.addEventListener("resize", this._resizeLoadingUI);
  51875. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51876. document.body.appendChild(this._loadingDiv);
  51877. this._loadingDiv.style.opacity = "1";
  51878. };
  51879. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  51880. var _this = this;
  51881. if (!this._loadingDiv) {
  51882. return;
  51883. }
  51884. var onTransitionEnd = function () {
  51885. if (!_this._loadingDiv) {
  51886. return;
  51887. }
  51888. document.body.removeChild(_this._loadingDiv);
  51889. window.removeEventListener("resize", _this._resizeLoadingUI);
  51890. _this._loadingDiv = null;
  51891. };
  51892. this._loadingDiv.style.opacity = "0";
  51893. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  51894. };
  51895. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  51896. set: function (text) {
  51897. this._loadingText = text;
  51898. if (this._loadingTextDiv) {
  51899. this._loadingTextDiv.innerHTML = this._loadingText;
  51900. }
  51901. },
  51902. enumerable: true,
  51903. configurable: true
  51904. });
  51905. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  51906. get: function () {
  51907. return this._loadingDivBackgroundColor;
  51908. },
  51909. set: function (color) {
  51910. this._loadingDivBackgroundColor = color;
  51911. if (!this._loadingDiv) {
  51912. return;
  51913. }
  51914. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51915. },
  51916. enumerable: true,
  51917. configurable: true
  51918. });
  51919. return DefaultLoadingScreen;
  51920. }());
  51921. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51922. })(BABYLON || (BABYLON = {}));
  51923. //# sourceMappingURL=babylon.loadingScreen.js.map
  51924. var BABYLON;
  51925. (function (BABYLON) {
  51926. var SceneLoader = /** @class */ (function () {
  51927. function SceneLoader() {
  51928. }
  51929. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51930. get: function () {
  51931. return 0;
  51932. },
  51933. enumerable: true,
  51934. configurable: true
  51935. });
  51936. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51937. get: function () {
  51938. return 1;
  51939. },
  51940. enumerable: true,
  51941. configurable: true
  51942. });
  51943. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51944. get: function () {
  51945. return 2;
  51946. },
  51947. enumerable: true,
  51948. configurable: true
  51949. });
  51950. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  51951. get: function () {
  51952. return 3;
  51953. },
  51954. enumerable: true,
  51955. configurable: true
  51956. });
  51957. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  51958. get: function () {
  51959. return SceneLoader._ForceFullSceneLoadingForIncremental;
  51960. },
  51961. set: function (value) {
  51962. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  51963. },
  51964. enumerable: true,
  51965. configurable: true
  51966. });
  51967. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  51968. get: function () {
  51969. return SceneLoader._ShowLoadingScreen;
  51970. },
  51971. set: function (value) {
  51972. SceneLoader._ShowLoadingScreen = value;
  51973. },
  51974. enumerable: true,
  51975. configurable: true
  51976. });
  51977. Object.defineProperty(SceneLoader, "loggingLevel", {
  51978. get: function () {
  51979. return SceneLoader._loggingLevel;
  51980. },
  51981. set: function (value) {
  51982. SceneLoader._loggingLevel = value;
  51983. },
  51984. enumerable: true,
  51985. configurable: true
  51986. });
  51987. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  51988. get: function () {
  51989. return SceneLoader._CleanBoneMatrixWeights;
  51990. },
  51991. set: function (value) {
  51992. SceneLoader._CleanBoneMatrixWeights = value;
  51993. },
  51994. enumerable: true,
  51995. configurable: true
  51996. });
  51997. SceneLoader._getDefaultPlugin = function () {
  51998. return SceneLoader._registeredPlugins[".babylon"];
  51999. };
  52000. SceneLoader._getPluginForExtension = function (extension) {
  52001. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  52002. if (registeredPlugin) {
  52003. return registeredPlugin;
  52004. }
  52005. return SceneLoader._getDefaultPlugin();
  52006. };
  52007. SceneLoader._getPluginForDirectLoad = function (data) {
  52008. for (var extension in SceneLoader._registeredPlugins) {
  52009. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  52010. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  52011. return SceneLoader._registeredPlugins[extension];
  52012. }
  52013. }
  52014. return SceneLoader._getDefaultPlugin();
  52015. };
  52016. SceneLoader._getPluginForFilename = function (sceneFilename) {
  52017. if (sceneFilename.name) {
  52018. sceneFilename = sceneFilename.name;
  52019. }
  52020. var dotPosition = sceneFilename.lastIndexOf(".");
  52021. var queryStringPosition = sceneFilename.indexOf("?");
  52022. if (queryStringPosition === -1) {
  52023. queryStringPosition = sceneFilename.length;
  52024. }
  52025. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  52026. return SceneLoader._getPluginForExtension(extension);
  52027. };
  52028. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  52029. SceneLoader._getDirectLoad = function (sceneFilename) {
  52030. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  52031. return sceneFilename.substr(5);
  52032. }
  52033. return null;
  52034. };
  52035. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52036. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  52037. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  52038. var plugin = registeredPlugin.plugin;
  52039. var useArrayBuffer = registeredPlugin.isBinary;
  52040. var database;
  52041. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  52042. var dataCallback = function (data) {
  52043. if (scene.isDisposed) {
  52044. onError("Scene has been disposed");
  52045. return;
  52046. }
  52047. scene.database = database;
  52048. try {
  52049. onSuccess(plugin, data);
  52050. }
  52051. catch (e) {
  52052. onError(null, e);
  52053. }
  52054. };
  52055. var manifestChecked = function (success) {
  52056. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  52057. if (request) {
  52058. onError(request.status + " " + request.statusText);
  52059. }
  52060. });
  52061. };
  52062. if (directLoad) {
  52063. dataCallback(directLoad);
  52064. return;
  52065. }
  52066. if (rootUrl.indexOf("file:") === -1) {
  52067. if (scene.getEngine().enableOfflineSupport) {
  52068. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  52069. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  52070. }
  52071. else {
  52072. manifestChecked(true);
  52073. }
  52074. }
  52075. else {
  52076. var fileOrString = sceneFilename;
  52077. if (fileOrString.name) {
  52078. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  52079. }
  52080. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  52081. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  52082. }
  52083. else {
  52084. onError("Unable to find file named " + sceneFilename);
  52085. return;
  52086. }
  52087. }
  52088. };
  52089. // Public functions
  52090. SceneLoader.GetPluginForExtension = function (extension) {
  52091. return SceneLoader._getPluginForExtension(extension).plugin;
  52092. };
  52093. SceneLoader.RegisterPlugin = function (plugin) {
  52094. if (typeof plugin.extensions === "string") {
  52095. var extension = plugin.extensions;
  52096. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52097. plugin: plugin,
  52098. isBinary: false
  52099. };
  52100. }
  52101. else {
  52102. var extensions = plugin.extensions;
  52103. Object.keys(extensions).forEach(function (extension) {
  52104. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52105. plugin: plugin,
  52106. isBinary: extensions[extension].isBinary
  52107. };
  52108. });
  52109. }
  52110. };
  52111. /**
  52112. * Import meshes into a scene
  52113. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  52114. * @param rootUrl a string that defines the root url for scene and resources
  52115. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52116. * @param scene the instance of BABYLON.Scene to append to
  52117. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  52118. * @param onProgress a callback with a progress event for each file being loaded
  52119. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52120. */
  52121. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52122. if (onSuccess === void 0) { onSuccess = null; }
  52123. if (onProgress === void 0) { onProgress = null; }
  52124. if (onError === void 0) { onError = null; }
  52125. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52126. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52127. return;
  52128. }
  52129. var loadingToken = {};
  52130. scene._addPendingData(loadingToken);
  52131. var errorHandler = function (message, exception) {
  52132. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52133. if (onError) {
  52134. onError(scene, errorMessage, exception);
  52135. }
  52136. else {
  52137. BABYLON.Tools.Error(errorMessage);
  52138. // should the exception be thrown?
  52139. }
  52140. scene._removePendingData(loadingToken);
  52141. };
  52142. var progressHandler = function (event) {
  52143. if (onProgress) {
  52144. onProgress(event);
  52145. }
  52146. };
  52147. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52148. if (plugin.importMesh) {
  52149. var syncedPlugin = plugin;
  52150. var meshes = new Array();
  52151. var particleSystems = new Array();
  52152. var skeletons = new Array();
  52153. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  52154. return;
  52155. }
  52156. if (onSuccess) {
  52157. // wrap onSuccess with try-catch to know if something went wrong.
  52158. try {
  52159. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52160. onSuccess(meshes, particleSystems, skeletons);
  52161. scene._removePendingData(loadingToken);
  52162. }
  52163. catch (e) {
  52164. var message = 'Error in onSuccess callback.';
  52165. errorHandler(message, e);
  52166. }
  52167. }
  52168. }
  52169. else {
  52170. var asyncedPlugin = plugin;
  52171. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  52172. if (onSuccess) {
  52173. try {
  52174. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52175. onSuccess(meshes, particleSystems, skeletons);
  52176. scene._removePendingData(loadingToken);
  52177. }
  52178. catch (e) {
  52179. var message = 'Error in onSuccess callback.';
  52180. errorHandler(message, e);
  52181. }
  52182. }
  52183. }, progressHandler, errorHandler);
  52184. }
  52185. }, progressHandler, errorHandler, pluginExtension);
  52186. };
  52187. /**
  52188. * Load a scene
  52189. * @param rootUrl a string that defines the root url for scene and resources
  52190. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52191. * @param engine is the instance of BABYLON.Engine to use to create the scene
  52192. * @param onSuccess a callback with the scene when import succeeds
  52193. * @param onProgress a callback with a progress event for each file being loaded
  52194. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52195. */
  52196. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  52197. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  52198. };
  52199. /**
  52200. * Append a scene
  52201. * @param rootUrl a string that defines the root url for scene and resources
  52202. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52203. * @param scene is the instance of BABYLON.Scene to append to
  52204. * @param onSuccess a callback with the scene when import succeeds
  52205. * @param onProgress a callback with a progress event for each file being loaded
  52206. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52207. */
  52208. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52209. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52210. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52211. return;
  52212. }
  52213. if (SceneLoader.ShowLoadingScreen) {
  52214. scene.getEngine().displayLoadingUI();
  52215. }
  52216. var loadingToken = {};
  52217. scene._addPendingData(loadingToken);
  52218. var errorHandler = function (message, exception) {
  52219. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52220. if (onError) {
  52221. onError(scene, errorMessage, exception);
  52222. }
  52223. else {
  52224. BABYLON.Tools.Error(errorMessage);
  52225. // should the exception be thrown?
  52226. }
  52227. scene._removePendingData(loadingToken);
  52228. scene.getEngine().hideLoadingUI();
  52229. };
  52230. var progressHandler = function (event) {
  52231. if (onProgress) {
  52232. onProgress(event);
  52233. }
  52234. };
  52235. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52236. if (plugin.load) {
  52237. var syncedPlugin = plugin;
  52238. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52239. return;
  52240. }
  52241. if (onSuccess) {
  52242. try {
  52243. onSuccess(scene);
  52244. }
  52245. catch (e) {
  52246. errorHandler("Error in onSuccess callback", e);
  52247. }
  52248. }
  52249. scene.loadingPluginName = plugin.name;
  52250. scene._removePendingData(loadingToken);
  52251. }
  52252. else {
  52253. var asyncedPlugin = plugin;
  52254. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52255. if (onSuccess) {
  52256. onSuccess(scene);
  52257. }
  52258. scene.loadingPluginName = plugin.name;
  52259. scene._removePendingData(loadingToken);
  52260. }, progressHandler, errorHandler);
  52261. }
  52262. if (SceneLoader.ShowLoadingScreen) {
  52263. scene.executeWhenReady(function () {
  52264. scene.getEngine().hideLoadingUI();
  52265. });
  52266. }
  52267. }, progressHandler, errorHandler, pluginExtension);
  52268. };
  52269. // Flags
  52270. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52271. SceneLoader._ShowLoadingScreen = true;
  52272. SceneLoader._CleanBoneMatrixWeights = false;
  52273. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52274. // Members
  52275. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52276. SceneLoader._registeredPlugins = {};
  52277. return SceneLoader;
  52278. }());
  52279. BABYLON.SceneLoader = SceneLoader;
  52280. ;
  52281. })(BABYLON || (BABYLON = {}));
  52282. //# sourceMappingURL=babylon.sceneLoader.js.map
  52283. var BABYLON;
  52284. (function (BABYLON) {
  52285. var Internals;
  52286. (function (Internals) {
  52287. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52288. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52289. var parsedMaterial = parsedData.materials[index];
  52290. if (parsedMaterial.id === id) {
  52291. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52292. }
  52293. }
  52294. return null;
  52295. };
  52296. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52297. for (var i in names) {
  52298. if (mesh.name === names[i]) {
  52299. hierarchyIds.push(mesh.id);
  52300. return true;
  52301. }
  52302. }
  52303. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52304. hierarchyIds.push(mesh.id);
  52305. return true;
  52306. }
  52307. return false;
  52308. };
  52309. var logOperation = function (operation, producer) {
  52310. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52311. };
  52312. BABYLON.SceneLoader.RegisterPlugin({
  52313. name: "babylon.js",
  52314. extensions: ".babylon",
  52315. canDirectLoad: function (data) {
  52316. if (data.indexOf("babylon") !== -1) {
  52317. return true;
  52318. }
  52319. return false;
  52320. },
  52321. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52322. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52323. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52324. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52325. // and avoid problems with multiple concurrent .babylon loads.
  52326. var log = "importMesh has failed JSON parse";
  52327. try {
  52328. var parsedData = JSON.parse(data);
  52329. log = "";
  52330. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52331. if (!meshesNames) {
  52332. meshesNames = null;
  52333. }
  52334. else if (!Array.isArray(meshesNames)) {
  52335. meshesNames = [meshesNames];
  52336. }
  52337. var hierarchyIds = new Array();
  52338. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52339. var loadedSkeletonsIds = [];
  52340. var loadedMaterialsIds = [];
  52341. var index;
  52342. var cache;
  52343. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52344. var parsedMesh = parsedData.meshes[index];
  52345. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52346. if (meshesNames !== null) {
  52347. // Remove found mesh name from list.
  52348. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52349. }
  52350. //Geometry?
  52351. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52352. //does the file contain geometries?
  52353. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52354. //find the correct geometry and add it to the scene
  52355. var found = false;
  52356. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52357. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52358. return;
  52359. }
  52360. else {
  52361. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52362. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52363. switch (geometryType) {
  52364. case "boxes":
  52365. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52366. break;
  52367. case "spheres":
  52368. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52369. break;
  52370. case "cylinders":
  52371. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52372. break;
  52373. case "toruses":
  52374. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52375. break;
  52376. case "grounds":
  52377. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52378. break;
  52379. case "planes":
  52380. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52381. break;
  52382. case "torusKnots":
  52383. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52384. break;
  52385. case "vertexData":
  52386. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52387. break;
  52388. }
  52389. found = true;
  52390. }
  52391. });
  52392. }
  52393. });
  52394. if (found === false) {
  52395. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52396. }
  52397. }
  52398. }
  52399. // Material ?
  52400. if (parsedMesh.materialId) {
  52401. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52402. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52403. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52404. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52405. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52406. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52407. var subMatId = parsedMultiMaterial.materials[matIndex];
  52408. loadedMaterialsIds.push(subMatId);
  52409. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52410. log += "\n\tMaterial " + mat.toString(fullDetails);
  52411. }
  52412. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52413. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52414. materialFound = true;
  52415. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52416. break;
  52417. }
  52418. }
  52419. }
  52420. if (materialFound === false) {
  52421. loadedMaterialsIds.push(parsedMesh.materialId);
  52422. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52423. if (!mat) {
  52424. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52425. }
  52426. else {
  52427. log += "\n\tMaterial " + mat.toString(fullDetails);
  52428. }
  52429. }
  52430. }
  52431. // Skeleton ?
  52432. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52433. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52434. if (skeletonAlreadyLoaded === false) {
  52435. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52436. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52437. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52438. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52439. skeletons.push(skeleton);
  52440. loadedSkeletonsIds.push(parsedSkeleton.id);
  52441. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52442. }
  52443. }
  52444. }
  52445. }
  52446. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52447. meshes.push(mesh);
  52448. log += "\n\tMesh " + mesh.toString(fullDetails);
  52449. }
  52450. }
  52451. // Connecting parents
  52452. var currentMesh;
  52453. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52454. currentMesh = scene.meshes[index];
  52455. if (currentMesh._waitingParentId) {
  52456. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52457. currentMesh._waitingParentId = null;
  52458. }
  52459. }
  52460. // freeze and compute world matrix application
  52461. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52462. currentMesh = scene.meshes[index];
  52463. if (currentMesh._waitingFreezeWorldMatrix) {
  52464. currentMesh.freezeWorldMatrix();
  52465. currentMesh._waitingFreezeWorldMatrix = null;
  52466. }
  52467. else {
  52468. currentMesh.computeWorldMatrix(true);
  52469. }
  52470. }
  52471. }
  52472. // Particles
  52473. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52474. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52475. var parsedParticleSystem = parsedData.particleSystems[index];
  52476. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52477. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52478. }
  52479. }
  52480. }
  52481. return true;
  52482. }
  52483. catch (err) {
  52484. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52485. if (onError) {
  52486. onError(msg, err);
  52487. }
  52488. else {
  52489. BABYLON.Tools.Log(msg);
  52490. throw err;
  52491. }
  52492. }
  52493. finally {
  52494. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52495. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52496. }
  52497. }
  52498. return false;
  52499. },
  52500. load: function (scene, data, rootUrl, onError) {
  52501. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52502. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52503. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52504. // and avoid problems with multiple concurrent .babylon loads.
  52505. var log = "importScene has failed JSON parse";
  52506. try {
  52507. var parsedData = JSON.parse(data);
  52508. log = "";
  52509. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52510. // Scene
  52511. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52512. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52513. }
  52514. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52515. scene.autoClear = parsedData.autoClear;
  52516. }
  52517. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52518. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52519. }
  52520. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52521. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52522. }
  52523. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52524. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52525. }
  52526. // Fog
  52527. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52528. scene.fogMode = parsedData.fogMode;
  52529. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52530. scene.fogStart = parsedData.fogStart;
  52531. scene.fogEnd = parsedData.fogEnd;
  52532. scene.fogDensity = parsedData.fogDensity;
  52533. log += "\tFog mode for scene: ";
  52534. switch (scene.fogMode) {
  52535. // getters not compiling, so using hardcoded
  52536. case 1:
  52537. log += "exp\n";
  52538. break;
  52539. case 2:
  52540. log += "exp2\n";
  52541. break;
  52542. case 3:
  52543. log += "linear\n";
  52544. break;
  52545. }
  52546. }
  52547. //Physics
  52548. if (parsedData.physicsEnabled) {
  52549. var physicsPlugin;
  52550. if (parsedData.physicsEngine === "cannon") {
  52551. physicsPlugin = new BABYLON.CannonJSPlugin();
  52552. }
  52553. else if (parsedData.physicsEngine === "oimo") {
  52554. physicsPlugin = new BABYLON.OimoJSPlugin();
  52555. }
  52556. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52557. //else - default engine, which is currently oimo
  52558. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52559. scene.enablePhysics(physicsGravity, physicsPlugin);
  52560. }
  52561. // Metadata
  52562. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52563. scene.metadata = parsedData.metadata;
  52564. }
  52565. //collisions, if defined. otherwise, default is true
  52566. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52567. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52568. }
  52569. scene.workerCollisions = !!parsedData.workerCollisions;
  52570. var index;
  52571. var cache;
  52572. // Lights
  52573. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52574. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52575. var parsedLight = parsedData.lights[index];
  52576. var light = BABYLON.Light.Parse(parsedLight, scene);
  52577. if (light) {
  52578. log += (index === 0 ? "\n\tLights:" : "");
  52579. log += "\n\t\t" + light.toString(fullDetails);
  52580. }
  52581. }
  52582. }
  52583. // Animations
  52584. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52585. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52586. var parsedAnimation = parsedData.animations[index];
  52587. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52588. scene.animations.push(animation);
  52589. log += (index === 0 ? "\n\tAnimations:" : "");
  52590. log += "\n\t\t" + animation.toString(fullDetails);
  52591. }
  52592. }
  52593. if (parsedData.autoAnimate) {
  52594. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52595. }
  52596. // Materials
  52597. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52598. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52599. var parsedMaterial = parsedData.materials[index];
  52600. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52601. log += (index === 0 ? "\n\tMaterials:" : "");
  52602. log += "\n\t\t" + mat.toString(fullDetails);
  52603. }
  52604. }
  52605. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52606. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52607. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52608. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52609. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52610. log += "\n\t\t" + mmat.toString(fullDetails);
  52611. }
  52612. }
  52613. // Morph targets
  52614. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52615. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52616. var managerData = _a[_i];
  52617. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52618. }
  52619. }
  52620. // Skeletons
  52621. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52622. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52623. var parsedSkeleton = parsedData.skeletons[index];
  52624. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52625. log += (index === 0 ? "\n\tSkeletons:" : "");
  52626. log += "\n\t\t" + skeleton.toString(fullDetails);
  52627. }
  52628. }
  52629. // Geometries
  52630. var geometries = parsedData.geometries;
  52631. if (geometries !== undefined && geometries !== null) {
  52632. // Boxes
  52633. var boxes = geometries.boxes;
  52634. if (boxes !== undefined && boxes !== null) {
  52635. for (index = 0, cache = boxes.length; index < cache; index++) {
  52636. var parsedBox = boxes[index];
  52637. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52638. }
  52639. }
  52640. // Spheres
  52641. var spheres = geometries.spheres;
  52642. if (spheres !== undefined && spheres !== null) {
  52643. for (index = 0, cache = spheres.length; index < cache; index++) {
  52644. var parsedSphere = spheres[index];
  52645. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52646. }
  52647. }
  52648. // Cylinders
  52649. var cylinders = geometries.cylinders;
  52650. if (cylinders !== undefined && cylinders !== null) {
  52651. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52652. var parsedCylinder = cylinders[index];
  52653. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52654. }
  52655. }
  52656. // Toruses
  52657. var toruses = geometries.toruses;
  52658. if (toruses !== undefined && toruses !== null) {
  52659. for (index = 0, cache = toruses.length; index < cache; index++) {
  52660. var parsedTorus = toruses[index];
  52661. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52662. }
  52663. }
  52664. // Grounds
  52665. var grounds = geometries.grounds;
  52666. if (grounds !== undefined && grounds !== null) {
  52667. for (index = 0, cache = grounds.length; index < cache; index++) {
  52668. var parsedGround = grounds[index];
  52669. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52670. }
  52671. }
  52672. // Planes
  52673. var planes = geometries.planes;
  52674. if (planes !== undefined && planes !== null) {
  52675. for (index = 0, cache = planes.length; index < cache; index++) {
  52676. var parsedPlane = planes[index];
  52677. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52678. }
  52679. }
  52680. // TorusKnots
  52681. var torusKnots = geometries.torusKnots;
  52682. if (torusKnots !== undefined && torusKnots !== null) {
  52683. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52684. var parsedTorusKnot = torusKnots[index];
  52685. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52686. }
  52687. }
  52688. // VertexData
  52689. var vertexData = geometries.vertexData;
  52690. if (vertexData !== undefined && vertexData !== null) {
  52691. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52692. var parsedVertexData = vertexData[index];
  52693. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52694. }
  52695. }
  52696. }
  52697. // Meshes
  52698. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52699. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52700. var parsedMesh = parsedData.meshes[index];
  52701. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52702. log += (index === 0 ? "\n\tMeshes:" : "");
  52703. log += "\n\t\t" + mesh.toString(fullDetails);
  52704. }
  52705. }
  52706. // Cameras
  52707. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52708. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52709. var parsedCamera = parsedData.cameras[index];
  52710. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52711. log += (index === 0 ? "\n\tCameras:" : "");
  52712. log += "\n\t\t" + camera.toString(fullDetails);
  52713. }
  52714. }
  52715. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52716. scene.setActiveCameraByID(parsedData.activeCameraID);
  52717. }
  52718. // Browsing all the graph to connect the dots
  52719. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52720. var camera = scene.cameras[index];
  52721. if (camera._waitingParentId) {
  52722. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52723. camera._waitingParentId = null;
  52724. }
  52725. }
  52726. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52727. var light_1 = scene.lights[index];
  52728. if (light_1 && light_1._waitingParentId) {
  52729. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52730. light_1._waitingParentId = null;
  52731. }
  52732. }
  52733. // Sounds
  52734. var loadedSounds = [];
  52735. var loadedSound;
  52736. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52737. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52738. var parsedSound = parsedData.sounds[index];
  52739. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52740. if (!parsedSound.url)
  52741. parsedSound.url = parsedSound.name;
  52742. if (!loadedSounds[parsedSound.url]) {
  52743. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52744. loadedSounds[parsedSound.url] = loadedSound;
  52745. }
  52746. else {
  52747. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52748. }
  52749. }
  52750. else {
  52751. new BABYLON.Sound(parsedSound.name, null, scene);
  52752. }
  52753. }
  52754. }
  52755. loadedSounds = [];
  52756. // Connect parents & children and parse actions
  52757. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52758. var mesh = scene.meshes[index];
  52759. if (mesh._waitingParentId) {
  52760. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52761. mesh._waitingParentId = null;
  52762. }
  52763. if (mesh._waitingActions) {
  52764. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52765. mesh._waitingActions = null;
  52766. }
  52767. }
  52768. // freeze world matrix application
  52769. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52770. var currentMesh = scene.meshes[index];
  52771. if (currentMesh._waitingFreezeWorldMatrix) {
  52772. currentMesh.freezeWorldMatrix();
  52773. currentMesh._waitingFreezeWorldMatrix = null;
  52774. }
  52775. else {
  52776. currentMesh.computeWorldMatrix(true);
  52777. }
  52778. }
  52779. // Particles Systems
  52780. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52781. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52782. var parsedParticleSystem = parsedData.particleSystems[index];
  52783. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52784. }
  52785. }
  52786. // Environment texture
  52787. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52788. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52789. if (parsedData.createDefaultSkybox === true) {
  52790. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52791. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52792. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52793. }
  52794. }
  52795. // Lens flares
  52796. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52797. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52798. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52799. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52800. }
  52801. }
  52802. // Shadows
  52803. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52804. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52805. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52806. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52807. }
  52808. }
  52809. // Lights exclusions / inclusions
  52810. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52811. var light_2 = scene.lights[index];
  52812. // Excluded check
  52813. if (light_2._excludedMeshesIds.length > 0) {
  52814. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52815. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52816. if (excludedMesh) {
  52817. light_2.excludedMeshes.push(excludedMesh);
  52818. }
  52819. }
  52820. light_2._excludedMeshesIds = [];
  52821. }
  52822. // Included check
  52823. if (light_2._includedOnlyMeshesIds.length > 0) {
  52824. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52825. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52826. if (includedOnlyMesh) {
  52827. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52828. }
  52829. }
  52830. light_2._includedOnlyMeshesIds = [];
  52831. }
  52832. }
  52833. // Actions (scene)
  52834. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52835. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52836. }
  52837. // Finish
  52838. return true;
  52839. }
  52840. catch (err) {
  52841. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52842. if (onError) {
  52843. onError(msg, err);
  52844. }
  52845. else {
  52846. BABYLON.Tools.Log(msg);
  52847. throw err;
  52848. }
  52849. }
  52850. finally {
  52851. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52852. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52853. }
  52854. }
  52855. return false;
  52856. }
  52857. });
  52858. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52859. })(BABYLON || (BABYLON = {}));
  52860. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  52861. var BABYLON;
  52862. (function (BABYLON) {
  52863. var FilesInput = /** @class */ (function () {
  52864. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  52865. this.onProcessFileCallback = function () { return true; };
  52866. this._engine = engine;
  52867. this._currentScene = scene;
  52868. this._sceneLoadedCallback = sceneLoadedCallback;
  52869. this._progressCallback = progressCallback;
  52870. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  52871. this._textureLoadingCallback = textureLoadingCallback;
  52872. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  52873. this._onReloadCallback = onReloadCallback;
  52874. this._errorCallback = errorCallback;
  52875. }
  52876. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  52877. var _this = this;
  52878. if (elementToMonitor) {
  52879. this._elementToMonitor = elementToMonitor;
  52880. this._dragEnterHandler = function (e) { _this.drag(e); };
  52881. this._dragOverHandler = function (e) { _this.drag(e); };
  52882. this._dropHandler = function (e) { _this.drop(e); };
  52883. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  52884. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  52885. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  52886. }
  52887. };
  52888. FilesInput.prototype.dispose = function () {
  52889. if (!this._elementToMonitor) {
  52890. return;
  52891. }
  52892. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  52893. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  52894. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  52895. };
  52896. FilesInput.prototype.renderFunction = function () {
  52897. if (this._additionalRenderLoopLogicCallback) {
  52898. this._additionalRenderLoopLogicCallback();
  52899. }
  52900. if (this._currentScene) {
  52901. if (this._textureLoadingCallback) {
  52902. var remaining = this._currentScene.getWaitingItemsCount();
  52903. if (remaining > 0) {
  52904. this._textureLoadingCallback(remaining);
  52905. }
  52906. }
  52907. this._currentScene.render();
  52908. }
  52909. };
  52910. FilesInput.prototype.drag = function (e) {
  52911. e.stopPropagation();
  52912. e.preventDefault();
  52913. };
  52914. FilesInput.prototype.drop = function (eventDrop) {
  52915. eventDrop.stopPropagation();
  52916. eventDrop.preventDefault();
  52917. this.loadFiles(eventDrop);
  52918. };
  52919. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  52920. var _this = this;
  52921. var reader = folder.createReader();
  52922. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  52923. reader.readEntries(function (entries) {
  52924. remaining.count += entries.length;
  52925. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52926. var entry = entries_1[_i];
  52927. if (entry.isFile) {
  52928. entry.file(function (file) {
  52929. file.correctName = relativePath + file.name;
  52930. files.push(file);
  52931. if (--remaining.count === 0) {
  52932. callback();
  52933. }
  52934. });
  52935. }
  52936. else if (entry.isDirectory) {
  52937. _this._traverseFolder(entry, files, remaining, callback);
  52938. }
  52939. }
  52940. if (--remaining.count) {
  52941. callback();
  52942. }
  52943. });
  52944. };
  52945. FilesInput.prototype._processFiles = function (files) {
  52946. var skippedFiles = 0;
  52947. for (var i = 0; i < files.length; i++) {
  52948. var name = files[i].correctName.toLowerCase();
  52949. var extension = name.split('.').pop();
  52950. if (!this.onProcessFileCallback(files[i], name, extension)) {
  52951. skippedFiles++;
  52952. continue;
  52953. }
  52954. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  52955. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  52956. this._sceneFileToLoad = files[i];
  52957. }
  52958. else {
  52959. FilesInput.FilesToLoad[name] = files[i];
  52960. }
  52961. }
  52962. if (this._onReloadCallback) {
  52963. this._onReloadCallback(this._sceneFileToLoad);
  52964. }
  52965. else if (skippedFiles < files.length) {
  52966. this.reload();
  52967. }
  52968. };
  52969. FilesInput.prototype.loadFiles = function (event) {
  52970. var _this = this;
  52971. if (this._startingProcessingFilesCallback)
  52972. this._startingProcessingFilesCallback();
  52973. // Handling data transfer via drag'n'drop
  52974. if (event && event.dataTransfer && event.dataTransfer.files) {
  52975. this._filesToLoad = event.dataTransfer.files;
  52976. }
  52977. // Handling files from input files
  52978. if (event && event.target && event.target.files) {
  52979. this._filesToLoad = event.target.files;
  52980. }
  52981. if (this._filesToLoad && this._filesToLoad.length > 0) {
  52982. var files_1 = new Array();
  52983. var folders = [];
  52984. var items = event.dataTransfer ? event.dataTransfer.items : null;
  52985. for (var i = 0; i < this._filesToLoad.length; i++) {
  52986. var fileToLoad = this._filesToLoad[i];
  52987. var name_1 = fileToLoad.name.toLowerCase();
  52988. var entry = void 0;
  52989. fileToLoad.correctName = name_1;
  52990. if (items) {
  52991. var item = items[i];
  52992. if (item.getAsEntry) {
  52993. entry = item.getAsEntry();
  52994. }
  52995. else if (item.webkitGetAsEntry) {
  52996. entry = item.webkitGetAsEntry();
  52997. }
  52998. }
  52999. if (!entry) {
  53000. files_1.push(fileToLoad);
  53001. }
  53002. else {
  53003. if (entry.isDirectory) {
  53004. folders.push(entry);
  53005. }
  53006. else {
  53007. files_1.push(fileToLoad);
  53008. }
  53009. }
  53010. }
  53011. if (folders.length === 0) {
  53012. this._processFiles(files_1);
  53013. }
  53014. else {
  53015. var remaining = { count: folders.length };
  53016. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  53017. var folder = folders_1[_i];
  53018. this._traverseFolder(folder, files_1, remaining, function () {
  53019. _this._processFiles(files_1);
  53020. });
  53021. }
  53022. }
  53023. }
  53024. };
  53025. FilesInput.prototype.reload = function () {
  53026. var _this = this;
  53027. // If a ".babylon" file has been provided
  53028. if (this._sceneFileToLoad) {
  53029. if (this._currentScene) {
  53030. if (BABYLON.Tools.errorsCount > 0) {
  53031. BABYLON.Tools.ClearLogCache();
  53032. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  53033. }
  53034. this._engine.stopRenderLoop();
  53035. this._currentScene.dispose();
  53036. }
  53037. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  53038. _this._currentScene = newScene;
  53039. if (_this._sceneLoadedCallback) {
  53040. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  53041. }
  53042. // Wait for textures and shaders to be ready
  53043. _this._currentScene.executeWhenReady(function () {
  53044. _this._engine.runRenderLoop(function () {
  53045. _this.renderFunction();
  53046. });
  53047. });
  53048. }, function (progress) {
  53049. if (_this._progressCallback) {
  53050. _this._progressCallback(progress);
  53051. }
  53052. }, function (scene, message) {
  53053. _this._currentScene = scene;
  53054. if (_this._errorCallback) {
  53055. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  53056. }
  53057. });
  53058. }
  53059. else {
  53060. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  53061. }
  53062. };
  53063. FilesInput.FilesToLoad = {};
  53064. return FilesInput;
  53065. }());
  53066. BABYLON.FilesInput = FilesInput;
  53067. })(BABYLON || (BABYLON = {}));
  53068. //# sourceMappingURL=babylon.filesInput.js.map
  53069. var BABYLON;
  53070. (function (BABYLON) {
  53071. /**
  53072. * This class implement a typical dictionary using a string as key and the generic type T as value.
  53073. * The underlying implementation relies on an associative array to ensure the best performances.
  53074. * The value can be anything including 'null' but except 'undefined'
  53075. */
  53076. var StringDictionary = /** @class */ (function () {
  53077. function StringDictionary() {
  53078. this._count = 0;
  53079. this._data = {};
  53080. }
  53081. /**
  53082. * This will clear this dictionary and copy the content from the 'source' one.
  53083. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  53084. * @param source the dictionary to take the content from and copy to this dictionary
  53085. */
  53086. StringDictionary.prototype.copyFrom = function (source) {
  53087. var _this = this;
  53088. this.clear();
  53089. source.forEach(function (t, v) { return _this.add(t, v); });
  53090. };
  53091. /**
  53092. * Get a value based from its key
  53093. * @param key the given key to get the matching value from
  53094. * @return the value if found, otherwise undefined is returned
  53095. */
  53096. StringDictionary.prototype.get = function (key) {
  53097. var val = this._data[key];
  53098. if (val !== undefined) {
  53099. return val;
  53100. }
  53101. return undefined;
  53102. };
  53103. /**
  53104. * Get a value from its key or add it if it doesn't exist.
  53105. * This method will ensure you that a given key/data will be present in the dictionary.
  53106. * @param key the given key to get the matching value from
  53107. * @param factory the factory that will create the value if the key is not present in the dictionary.
  53108. * The factory will only be invoked if there's no data for the given key.
  53109. * @return the value corresponding to the key.
  53110. */
  53111. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  53112. var val = this.get(key);
  53113. if (val !== undefined) {
  53114. return val;
  53115. }
  53116. val = factory(key);
  53117. if (val) {
  53118. this.add(key, val);
  53119. }
  53120. return val;
  53121. };
  53122. /**
  53123. * Get a value from its key if present in the dictionary otherwise add it
  53124. * @param key the key to get the value from
  53125. * @param val if there's no such key/value pair in the dictionary add it with this value
  53126. * @return the value corresponding to the key
  53127. */
  53128. StringDictionary.prototype.getOrAdd = function (key, val) {
  53129. var curVal = this.get(key);
  53130. if (curVal !== undefined) {
  53131. return curVal;
  53132. }
  53133. this.add(key, val);
  53134. return val;
  53135. };
  53136. /**
  53137. * Check if there's a given key in the dictionary
  53138. * @param key the key to check for
  53139. * @return true if the key is present, false otherwise
  53140. */
  53141. StringDictionary.prototype.contains = function (key) {
  53142. return this._data[key] !== undefined;
  53143. };
  53144. /**
  53145. * Add a new key and its corresponding value
  53146. * @param key the key to add
  53147. * @param value the value corresponding to the key
  53148. * @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
  53149. */
  53150. StringDictionary.prototype.add = function (key, value) {
  53151. if (this._data[key] !== undefined) {
  53152. return false;
  53153. }
  53154. this._data[key] = value;
  53155. ++this._count;
  53156. return true;
  53157. };
  53158. StringDictionary.prototype.set = function (key, value) {
  53159. if (this._data[key] === undefined) {
  53160. return false;
  53161. }
  53162. this._data[key] = value;
  53163. return true;
  53164. };
  53165. /**
  53166. * Get the element of the given key and remove it from the dictionary
  53167. * @param key
  53168. */
  53169. StringDictionary.prototype.getAndRemove = function (key) {
  53170. var val = this.get(key);
  53171. if (val !== undefined) {
  53172. delete this._data[key];
  53173. --this._count;
  53174. return val;
  53175. }
  53176. return null;
  53177. };
  53178. /**
  53179. * Remove a key/value from the dictionary.
  53180. * @param key the key to remove
  53181. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  53182. */
  53183. StringDictionary.prototype.remove = function (key) {
  53184. if (this.contains(key)) {
  53185. delete this._data[key];
  53186. --this._count;
  53187. return true;
  53188. }
  53189. return false;
  53190. };
  53191. /**
  53192. * Clear the whole content of the dictionary
  53193. */
  53194. StringDictionary.prototype.clear = function () {
  53195. this._data = {};
  53196. this._count = 0;
  53197. };
  53198. Object.defineProperty(StringDictionary.prototype, "count", {
  53199. get: function () {
  53200. return this._count;
  53201. },
  53202. enumerable: true,
  53203. configurable: true
  53204. });
  53205. /**
  53206. * Execute a callback on each key/val of the dictionary.
  53207. * Note that you can remove any element in this dictionary in the callback implementation
  53208. * @param callback the callback to execute on a given key/value pair
  53209. */
  53210. StringDictionary.prototype.forEach = function (callback) {
  53211. for (var cur in this._data) {
  53212. var val = this._data[cur];
  53213. callback(cur, val);
  53214. }
  53215. };
  53216. /**
  53217. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53218. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53219. * Note that you can remove any element in this dictionary in the callback implementation
  53220. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53221. */
  53222. StringDictionary.prototype.first = function (callback) {
  53223. for (var cur in this._data) {
  53224. var val = this._data[cur];
  53225. var res = callback(cur, val);
  53226. if (res) {
  53227. return res;
  53228. }
  53229. }
  53230. return null;
  53231. };
  53232. return StringDictionary;
  53233. }());
  53234. BABYLON.StringDictionary = StringDictionary;
  53235. })(BABYLON || (BABYLON = {}));
  53236. //# sourceMappingURL=babylon.stringDictionary.js.map
  53237. var BABYLON;
  53238. (function (BABYLON) {
  53239. var Tags = /** @class */ (function () {
  53240. function Tags() {
  53241. }
  53242. Tags.EnableFor = function (obj) {
  53243. obj._tags = obj._tags || {};
  53244. obj.hasTags = function () {
  53245. return Tags.HasTags(obj);
  53246. };
  53247. obj.addTags = function (tagsString) {
  53248. return Tags.AddTagsTo(obj, tagsString);
  53249. };
  53250. obj.removeTags = function (tagsString) {
  53251. return Tags.RemoveTagsFrom(obj, tagsString);
  53252. };
  53253. obj.matchesTagsQuery = function (tagsQuery) {
  53254. return Tags.MatchesQuery(obj, tagsQuery);
  53255. };
  53256. };
  53257. Tags.DisableFor = function (obj) {
  53258. delete obj._tags;
  53259. delete obj.hasTags;
  53260. delete obj.addTags;
  53261. delete obj.removeTags;
  53262. delete obj.matchesTagsQuery;
  53263. };
  53264. Tags.HasTags = function (obj) {
  53265. if (!obj._tags) {
  53266. return false;
  53267. }
  53268. return !BABYLON.Tools.IsEmpty(obj._tags);
  53269. };
  53270. Tags.GetTags = function (obj, asString) {
  53271. if (asString === void 0) { asString = true; }
  53272. if (!obj._tags) {
  53273. return null;
  53274. }
  53275. if (asString) {
  53276. var tagsArray = [];
  53277. for (var tag in obj._tags) {
  53278. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53279. tagsArray.push(tag);
  53280. }
  53281. }
  53282. return tagsArray.join(" ");
  53283. }
  53284. else {
  53285. return obj._tags;
  53286. }
  53287. };
  53288. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53289. // a tag cannot start with '||', '&&', and '!'
  53290. // it cannot contain whitespaces
  53291. Tags.AddTagsTo = function (obj, tagsString) {
  53292. if (!tagsString) {
  53293. return;
  53294. }
  53295. if (typeof tagsString !== "string") {
  53296. return;
  53297. }
  53298. var tags = tagsString.split(" ");
  53299. tags.forEach(function (tag, index, array) {
  53300. Tags._AddTagTo(obj, tag);
  53301. });
  53302. };
  53303. Tags._AddTagTo = function (obj, tag) {
  53304. tag = tag.trim();
  53305. if (tag === "" || tag === "true" || tag === "false") {
  53306. return;
  53307. }
  53308. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53309. return;
  53310. }
  53311. Tags.EnableFor(obj);
  53312. obj._tags[tag] = true;
  53313. };
  53314. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53315. if (!Tags.HasTags(obj)) {
  53316. return;
  53317. }
  53318. var tags = tagsString.split(" ");
  53319. for (var t in tags) {
  53320. Tags._RemoveTagFrom(obj, tags[t]);
  53321. }
  53322. };
  53323. Tags._RemoveTagFrom = function (obj, tag) {
  53324. delete obj._tags[tag];
  53325. };
  53326. Tags.MatchesQuery = function (obj, tagsQuery) {
  53327. if (tagsQuery === undefined) {
  53328. return true;
  53329. }
  53330. if (tagsQuery === "") {
  53331. return Tags.HasTags(obj);
  53332. }
  53333. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53334. };
  53335. return Tags;
  53336. }());
  53337. BABYLON.Tags = Tags;
  53338. })(BABYLON || (BABYLON = {}));
  53339. //# sourceMappingURL=babylon.tags.js.map
  53340. var BABYLON;
  53341. (function (BABYLON) {
  53342. var Internals;
  53343. (function (Internals) {
  53344. var AndOrNotEvaluator = /** @class */ (function () {
  53345. function AndOrNotEvaluator() {
  53346. }
  53347. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53348. if (!query.match(/\([^\(\)]*\)/g)) {
  53349. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53350. }
  53351. else {
  53352. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53353. // remove parenthesis
  53354. r = r.slice(1, r.length - 1);
  53355. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53356. });
  53357. }
  53358. if (query === "true") {
  53359. return true;
  53360. }
  53361. if (query === "false") {
  53362. return false;
  53363. }
  53364. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53365. };
  53366. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53367. evaluateCallback = evaluateCallback || (function (r) {
  53368. return r === "true" ? true : false;
  53369. });
  53370. var result;
  53371. var or = parenthesisContent.split("||");
  53372. for (var i in or) {
  53373. if (or.hasOwnProperty(i)) {
  53374. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53375. var and = ori.split("&&");
  53376. if (and.length > 1) {
  53377. for (var j = 0; j < and.length; ++j) {
  53378. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53379. if (andj !== "true" && andj !== "false") {
  53380. if (andj[0] === "!") {
  53381. result = !evaluateCallback(andj.substring(1));
  53382. }
  53383. else {
  53384. result = evaluateCallback(andj);
  53385. }
  53386. }
  53387. else {
  53388. result = andj === "true" ? true : false;
  53389. }
  53390. if (!result) {
  53391. ori = "false";
  53392. break;
  53393. }
  53394. }
  53395. }
  53396. if (result || ori === "true") {
  53397. result = true;
  53398. break;
  53399. }
  53400. // result equals false (or undefined)
  53401. if (ori !== "true" && ori !== "false") {
  53402. if (ori[0] === "!") {
  53403. result = !evaluateCallback(ori.substring(1));
  53404. }
  53405. else {
  53406. result = evaluateCallback(ori);
  53407. }
  53408. }
  53409. else {
  53410. result = ori === "true" ? true : false;
  53411. }
  53412. }
  53413. }
  53414. // the whole parenthesis scope is replaced by 'true' or 'false'
  53415. return result ? "true" : "false";
  53416. };
  53417. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53418. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53419. // remove whitespaces
  53420. r = r.replace(/[\s]/g, function () { return ""; });
  53421. return r.length % 2 ? "!" : "";
  53422. });
  53423. booleanString = booleanString.trim();
  53424. if (booleanString === "!true") {
  53425. booleanString = "false";
  53426. }
  53427. else if (booleanString === "!false") {
  53428. booleanString = "true";
  53429. }
  53430. return booleanString;
  53431. };
  53432. return AndOrNotEvaluator;
  53433. }());
  53434. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53435. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53436. })(BABYLON || (BABYLON = {}));
  53437. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53438. var BABYLON;
  53439. (function (BABYLON) {
  53440. var Database = /** @class */ (function () {
  53441. function Database(urlToScene, callbackManifestChecked) {
  53442. // Handling various flavors of prefixed version of IndexedDB
  53443. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53444. this.callbackManifestChecked = callbackManifestChecked;
  53445. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53446. this.db = null;
  53447. this._enableSceneOffline = false;
  53448. this._enableTexturesOffline = false;
  53449. this.manifestVersionFound = 0;
  53450. this.mustUpdateRessources = false;
  53451. this.hasReachedQuota = false;
  53452. if (!Database.IDBStorageEnabled) {
  53453. this.callbackManifestChecked(true);
  53454. }
  53455. else {
  53456. this.checkManifestFile();
  53457. }
  53458. }
  53459. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53460. get: function () {
  53461. return this._enableSceneOffline;
  53462. },
  53463. enumerable: true,
  53464. configurable: true
  53465. });
  53466. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53467. get: function () {
  53468. return this._enableTexturesOffline;
  53469. },
  53470. enumerable: true,
  53471. configurable: true
  53472. });
  53473. Database.prototype.checkManifestFile = function () {
  53474. var _this = this;
  53475. var noManifestFile = function () {
  53476. _this._enableSceneOffline = false;
  53477. _this._enableTexturesOffline = false;
  53478. _this.callbackManifestChecked(false);
  53479. };
  53480. var timeStampUsed = false;
  53481. var manifestURL = this.currentSceneUrl + ".manifest";
  53482. var xhr = new XMLHttpRequest();
  53483. if (navigator.onLine) {
  53484. // Adding a timestamp to by-pass browsers' cache
  53485. timeStampUsed = true;
  53486. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53487. }
  53488. xhr.open("GET", manifestURL, true);
  53489. xhr.addEventListener("load", function () {
  53490. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53491. try {
  53492. var manifestFile = JSON.parse(xhr.response);
  53493. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53494. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53495. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53496. _this.manifestVersionFound = manifestFile.version;
  53497. }
  53498. if (_this.callbackManifestChecked) {
  53499. _this.callbackManifestChecked(true);
  53500. }
  53501. }
  53502. catch (ex) {
  53503. noManifestFile();
  53504. }
  53505. }
  53506. else {
  53507. noManifestFile();
  53508. }
  53509. }, false);
  53510. xhr.addEventListener("error", function (event) {
  53511. if (timeStampUsed) {
  53512. timeStampUsed = false;
  53513. // Let's retry without the timeStamp
  53514. // It could fail when coupled with HTML5 Offline API
  53515. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53516. xhr.open("GET", retryManifestURL, true);
  53517. xhr.send();
  53518. }
  53519. else {
  53520. noManifestFile();
  53521. }
  53522. }, false);
  53523. try {
  53524. xhr.send();
  53525. }
  53526. catch (ex) {
  53527. BABYLON.Tools.Error("Error on XHR send request.");
  53528. this.callbackManifestChecked(false);
  53529. }
  53530. };
  53531. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53532. var _this = this;
  53533. var handleError = function () {
  53534. _this.isSupported = false;
  53535. if (errorCallback)
  53536. errorCallback();
  53537. };
  53538. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53539. // Your browser doesn't support IndexedDB
  53540. this.isSupported = false;
  53541. if (errorCallback)
  53542. errorCallback();
  53543. }
  53544. else {
  53545. // If the DB hasn't been opened or created yet
  53546. if (!this.db) {
  53547. this.hasReachedQuota = false;
  53548. this.isSupported = true;
  53549. var request = this.idbFactory.open("babylonjs", 1);
  53550. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53551. request.onerror = function (event) {
  53552. handleError();
  53553. };
  53554. // executes when a version change transaction cannot complete due to other active transactions
  53555. request.onblocked = function (event) {
  53556. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53557. handleError();
  53558. };
  53559. // DB has been opened successfully
  53560. request.onsuccess = function (event) {
  53561. _this.db = request.result;
  53562. successCallback();
  53563. };
  53564. // Initialization of the DB. Creating Scenes & Textures stores
  53565. request.onupgradeneeded = function (event) {
  53566. _this.db = (event.target).result;
  53567. if (_this.db) {
  53568. try {
  53569. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53570. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53571. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53572. }
  53573. catch (ex) {
  53574. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53575. handleError();
  53576. }
  53577. }
  53578. };
  53579. }
  53580. else {
  53581. if (successCallback)
  53582. successCallback();
  53583. }
  53584. }
  53585. };
  53586. Database.prototype.loadImageFromDB = function (url, image) {
  53587. var _this = this;
  53588. var completeURL = Database.ReturnFullUrlLocation(url);
  53589. var saveAndLoadImage = function () {
  53590. if (!_this.hasReachedQuota && _this.db !== null) {
  53591. // the texture is not yet in the DB, let's try to save it
  53592. _this._saveImageIntoDBAsync(completeURL, image);
  53593. }
  53594. else {
  53595. image.src = url;
  53596. }
  53597. };
  53598. if (!this.mustUpdateRessources) {
  53599. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53600. }
  53601. else {
  53602. saveAndLoadImage();
  53603. }
  53604. };
  53605. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53606. if (this.isSupported && this.db !== null) {
  53607. var texture;
  53608. var transaction = this.db.transaction(["textures"]);
  53609. transaction.onabort = function (event) {
  53610. image.src = url;
  53611. };
  53612. transaction.oncomplete = function (event) {
  53613. var blobTextureURL;
  53614. if (texture) {
  53615. var URL = window.URL || window.webkitURL;
  53616. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53617. image.onerror = function () {
  53618. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53619. image.src = url;
  53620. };
  53621. image.src = blobTextureURL;
  53622. }
  53623. else {
  53624. notInDBCallback();
  53625. }
  53626. };
  53627. var getRequest = transaction.objectStore("textures").get(url);
  53628. getRequest.onsuccess = function (event) {
  53629. texture = (event.target).result;
  53630. };
  53631. getRequest.onerror = function (event) {
  53632. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53633. image.src = url;
  53634. };
  53635. }
  53636. else {
  53637. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53638. image.src = url;
  53639. }
  53640. };
  53641. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53642. var _this = this;
  53643. if (this.isSupported) {
  53644. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53645. var generateBlobUrl = function () {
  53646. var blobTextureURL;
  53647. if (blob) {
  53648. var URL = window.URL || window.webkitURL;
  53649. try {
  53650. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53651. }
  53652. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53653. catch (ex) {
  53654. blobTextureURL = URL.createObjectURL(blob);
  53655. }
  53656. }
  53657. if (blobTextureURL) {
  53658. image.src = blobTextureURL;
  53659. }
  53660. };
  53661. if (Database.IsUASupportingBlobStorage) {
  53662. var xhr = new XMLHttpRequest(), blob;
  53663. xhr.open("GET", url, true);
  53664. xhr.responseType = "blob";
  53665. xhr.addEventListener("load", function () {
  53666. if (xhr.status === 200 && _this.db) {
  53667. // Blob as response (XHR2)
  53668. blob = xhr.response;
  53669. var transaction = _this.db.transaction(["textures"], "readwrite");
  53670. // the transaction could abort because of a QuotaExceededError error
  53671. transaction.onabort = function (event) {
  53672. try {
  53673. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53674. var srcElement = (event.srcElement || event.target);
  53675. var error = srcElement.error;
  53676. if (error && error.name === "QuotaExceededError") {
  53677. _this.hasReachedQuota = true;
  53678. }
  53679. }
  53680. catch (ex) { }
  53681. generateBlobUrl();
  53682. };
  53683. transaction.oncomplete = function (event) {
  53684. generateBlobUrl();
  53685. };
  53686. var newTexture = { textureUrl: url, data: blob };
  53687. try {
  53688. // Put the blob into the dabase
  53689. var addRequest = transaction.objectStore("textures").put(newTexture);
  53690. addRequest.onsuccess = function (event) {
  53691. };
  53692. addRequest.onerror = function (event) {
  53693. generateBlobUrl();
  53694. };
  53695. }
  53696. catch (ex) {
  53697. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53698. if (ex.code === 25) {
  53699. Database.IsUASupportingBlobStorage = false;
  53700. }
  53701. image.src = url;
  53702. }
  53703. }
  53704. else {
  53705. image.src = url;
  53706. }
  53707. }, false);
  53708. xhr.addEventListener("error", function (event) {
  53709. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53710. image.src = url;
  53711. }, false);
  53712. xhr.send();
  53713. }
  53714. else {
  53715. image.src = url;
  53716. }
  53717. }
  53718. else {
  53719. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53720. image.src = url;
  53721. }
  53722. };
  53723. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53724. var _this = this;
  53725. var updateVersion = function () {
  53726. // the version is not yet in the DB or we need to update it
  53727. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53728. };
  53729. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53730. };
  53731. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53732. var _this = this;
  53733. if (this.isSupported && this.db) {
  53734. var version;
  53735. try {
  53736. var transaction = this.db.transaction(["versions"]);
  53737. transaction.oncomplete = function (event) {
  53738. if (version) {
  53739. // If the version in the JSON file is > than the version in DB
  53740. if (_this.manifestVersionFound > version.data) {
  53741. _this.mustUpdateRessources = true;
  53742. updateInDBCallback();
  53743. }
  53744. else {
  53745. callback(version.data);
  53746. }
  53747. }
  53748. else {
  53749. _this.mustUpdateRessources = true;
  53750. updateInDBCallback();
  53751. }
  53752. };
  53753. transaction.onabort = function (event) {
  53754. callback(-1);
  53755. };
  53756. var getRequest = transaction.objectStore("versions").get(url);
  53757. getRequest.onsuccess = function (event) {
  53758. version = (event.target).result;
  53759. };
  53760. getRequest.onerror = function (event) {
  53761. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53762. callback(-1);
  53763. };
  53764. }
  53765. catch (ex) {
  53766. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53767. callback(-1);
  53768. }
  53769. }
  53770. else {
  53771. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53772. callback(-1);
  53773. }
  53774. };
  53775. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53776. var _this = this;
  53777. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53778. try {
  53779. // Open a transaction to the database
  53780. var transaction = this.db.transaction(["versions"], "readwrite");
  53781. // the transaction could abort because of a QuotaExceededError error
  53782. transaction.onabort = function (event) {
  53783. try {
  53784. var error = event.srcElement['error'];
  53785. if (error && error.name === "QuotaExceededError") {
  53786. _this.hasReachedQuota = true;
  53787. }
  53788. }
  53789. catch (ex) { }
  53790. callback(-1);
  53791. };
  53792. transaction.oncomplete = function (event) {
  53793. callback(_this.manifestVersionFound);
  53794. };
  53795. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53796. // Put the scene into the database
  53797. var addRequest = transaction.objectStore("versions").put(newVersion);
  53798. addRequest.onsuccess = function (event) {
  53799. };
  53800. addRequest.onerror = function (event) {
  53801. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53802. };
  53803. }
  53804. catch (ex) {
  53805. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53806. callback(-1);
  53807. }
  53808. }
  53809. else {
  53810. callback(-1);
  53811. }
  53812. };
  53813. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53814. var _this = this;
  53815. var completeUrl = Database.ReturnFullUrlLocation(url);
  53816. var saveAndLoadFile = function () {
  53817. // the scene is not yet in the DB, let's try to save it
  53818. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53819. };
  53820. this._checkVersionFromDB(completeUrl, function (version) {
  53821. if (version !== -1) {
  53822. if (!_this.mustUpdateRessources) {
  53823. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53824. }
  53825. else {
  53826. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53827. }
  53828. }
  53829. else {
  53830. if (errorCallback) {
  53831. errorCallback();
  53832. }
  53833. }
  53834. });
  53835. };
  53836. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53837. if (this.isSupported && this.db) {
  53838. var targetStore;
  53839. if (url.indexOf(".babylon") !== -1) {
  53840. targetStore = "scenes";
  53841. }
  53842. else {
  53843. targetStore = "textures";
  53844. }
  53845. var file;
  53846. var transaction = this.db.transaction([targetStore]);
  53847. transaction.oncomplete = function (event) {
  53848. if (file) {
  53849. callback(file.data);
  53850. }
  53851. else {
  53852. notInDBCallback();
  53853. }
  53854. };
  53855. transaction.onabort = function (event) {
  53856. notInDBCallback();
  53857. };
  53858. var getRequest = transaction.objectStore(targetStore).get(url);
  53859. getRequest.onsuccess = function (event) {
  53860. file = (event.target).result;
  53861. };
  53862. getRequest.onerror = function (event) {
  53863. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  53864. notInDBCallback();
  53865. };
  53866. }
  53867. else {
  53868. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53869. callback();
  53870. }
  53871. };
  53872. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  53873. var _this = this;
  53874. if (this.isSupported) {
  53875. var targetStore;
  53876. if (url.indexOf(".babylon") !== -1) {
  53877. targetStore = "scenes";
  53878. }
  53879. else {
  53880. targetStore = "textures";
  53881. }
  53882. // Create XHR
  53883. var xhr = new XMLHttpRequest();
  53884. var fileData;
  53885. xhr.open("GET", url, true);
  53886. if (useArrayBuffer) {
  53887. xhr.responseType = "arraybuffer";
  53888. }
  53889. if (progressCallback) {
  53890. xhr.onprogress = progressCallback;
  53891. }
  53892. xhr.addEventListener("load", function () {
  53893. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  53894. // Blob as response (XHR2)
  53895. //fileData = xhr.responseText;
  53896. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  53897. if (!_this.hasReachedQuota && _this.db) {
  53898. // Open a transaction to the database
  53899. var transaction = _this.db.transaction([targetStore], "readwrite");
  53900. // the transaction could abort because of a QuotaExceededError error
  53901. transaction.onabort = function (event) {
  53902. try {
  53903. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53904. var error = event.srcElement['error'];
  53905. if (error && error.name === "QuotaExceededError") {
  53906. _this.hasReachedQuota = true;
  53907. }
  53908. }
  53909. catch (ex) { }
  53910. callback(fileData);
  53911. };
  53912. transaction.oncomplete = function (event) {
  53913. callback(fileData);
  53914. };
  53915. var newFile;
  53916. if (targetStore === "scenes") {
  53917. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  53918. }
  53919. else {
  53920. newFile = { textureUrl: url, data: fileData };
  53921. }
  53922. try {
  53923. // Put the scene into the database
  53924. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53925. addRequest.onsuccess = function (event) {
  53926. };
  53927. addRequest.onerror = function (event) {
  53928. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53929. };
  53930. }
  53931. catch (ex) {
  53932. callback(fileData);
  53933. }
  53934. }
  53935. else {
  53936. callback(fileData);
  53937. }
  53938. }
  53939. else {
  53940. callback();
  53941. }
  53942. }, false);
  53943. xhr.addEventListener("error", function (event) {
  53944. BABYLON.Tools.Error("error on XHR request.");
  53945. callback();
  53946. }, false);
  53947. xhr.send();
  53948. }
  53949. else {
  53950. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53951. callback();
  53952. }
  53953. };
  53954. Database.IsUASupportingBlobStorage = true;
  53955. Database.IDBStorageEnabled = true;
  53956. Database.parseURL = function (url) {
  53957. var a = document.createElement('a');
  53958. a.href = url;
  53959. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  53960. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  53961. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  53962. return absLocation;
  53963. };
  53964. Database.ReturnFullUrlLocation = function (url) {
  53965. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  53966. return (Database.parseURL(window.location.href) + url);
  53967. }
  53968. else {
  53969. return url;
  53970. }
  53971. };
  53972. return Database;
  53973. }());
  53974. BABYLON.Database = Database;
  53975. })(BABYLON || (BABYLON = {}));
  53976. //# sourceMappingURL=babylon.database.js.map
  53977. var BABYLON;
  53978. (function (BABYLON) {
  53979. var FresnelParameters = /** @class */ (function () {
  53980. function FresnelParameters() {
  53981. this._isEnabled = true;
  53982. this.leftColor = BABYLON.Color3.White();
  53983. this.rightColor = BABYLON.Color3.Black();
  53984. this.bias = 0;
  53985. this.power = 1;
  53986. }
  53987. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  53988. get: function () {
  53989. return this._isEnabled;
  53990. },
  53991. set: function (value) {
  53992. if (this._isEnabled === value) {
  53993. return;
  53994. }
  53995. this._isEnabled = value;
  53996. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  53997. },
  53998. enumerable: true,
  53999. configurable: true
  54000. });
  54001. FresnelParameters.prototype.clone = function () {
  54002. var newFresnelParameters = new FresnelParameters();
  54003. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  54004. return newFresnelParameters;
  54005. };
  54006. FresnelParameters.prototype.serialize = function () {
  54007. var serializationObject = {};
  54008. serializationObject.isEnabled = this.isEnabled;
  54009. serializationObject.leftColor = this.leftColor;
  54010. serializationObject.rightColor = this.rightColor;
  54011. serializationObject.bias = this.bias;
  54012. serializationObject.power = this.power;
  54013. return serializationObject;
  54014. };
  54015. FresnelParameters.Parse = function (parsedFresnelParameters) {
  54016. var fresnelParameters = new FresnelParameters();
  54017. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  54018. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  54019. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  54020. fresnelParameters.bias = parsedFresnelParameters.bias;
  54021. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  54022. return fresnelParameters;
  54023. };
  54024. return FresnelParameters;
  54025. }());
  54026. BABYLON.FresnelParameters = FresnelParameters;
  54027. })(BABYLON || (BABYLON = {}));
  54028. //# sourceMappingURL=babylon.fresnelParameters.js.map
  54029. var BABYLON;
  54030. (function (BABYLON) {
  54031. var MultiMaterial = /** @class */ (function (_super) {
  54032. __extends(MultiMaterial, _super);
  54033. function MultiMaterial(name, scene) {
  54034. var _this = _super.call(this, name, scene, true) || this;
  54035. scene.multiMaterials.push(_this);
  54036. _this.subMaterials = new Array();
  54037. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  54038. return _this;
  54039. }
  54040. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  54041. get: function () {
  54042. return this._subMaterials;
  54043. },
  54044. set: function (value) {
  54045. this._subMaterials = value;
  54046. this._hookArray(value);
  54047. },
  54048. enumerable: true,
  54049. configurable: true
  54050. });
  54051. MultiMaterial.prototype._hookArray = function (array) {
  54052. var _this = this;
  54053. var oldPush = array.push;
  54054. array.push = function () {
  54055. var items = [];
  54056. for (var _i = 0; _i < arguments.length; _i++) {
  54057. items[_i] = arguments[_i];
  54058. }
  54059. var result = oldPush.apply(array, items);
  54060. _this._markAllSubMeshesAsTexturesDirty();
  54061. return result;
  54062. };
  54063. var oldSplice = array.splice;
  54064. array.splice = function (index, deleteCount) {
  54065. var deleted = oldSplice.apply(array, [index, deleteCount]);
  54066. _this._markAllSubMeshesAsTexturesDirty();
  54067. return deleted;
  54068. };
  54069. };
  54070. // Properties
  54071. MultiMaterial.prototype.getSubMaterial = function (index) {
  54072. if (index < 0 || index >= this.subMaterials.length) {
  54073. return this.getScene().defaultMaterial;
  54074. }
  54075. return this.subMaterials[index];
  54076. };
  54077. MultiMaterial.prototype.getActiveTextures = function () {
  54078. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  54079. if (subMaterial) {
  54080. return subMaterial.getActiveTextures();
  54081. }
  54082. else {
  54083. return [];
  54084. }
  54085. }));
  54086. var _a;
  54087. };
  54088. // Methods
  54089. MultiMaterial.prototype.getClassName = function () {
  54090. return "MultiMaterial";
  54091. };
  54092. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  54093. for (var index = 0; index < this.subMaterials.length; index++) {
  54094. var subMaterial = this.subMaterials[index];
  54095. if (subMaterial) {
  54096. if (subMaterial.storeEffectOnSubMeshes) {
  54097. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  54098. return false;
  54099. }
  54100. continue;
  54101. }
  54102. if (!subMaterial.isReady(mesh)) {
  54103. return false;
  54104. }
  54105. }
  54106. }
  54107. return true;
  54108. };
  54109. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  54110. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  54111. for (var index = 0; index < this.subMaterials.length; index++) {
  54112. var subMaterial = null;
  54113. var current = this.subMaterials[index];
  54114. if (cloneChildren && current) {
  54115. subMaterial = current.clone(name + "-" + current.name);
  54116. }
  54117. else {
  54118. subMaterial = this.subMaterials[index];
  54119. }
  54120. newMultiMaterial.subMaterials.push(subMaterial);
  54121. }
  54122. return newMultiMaterial;
  54123. };
  54124. MultiMaterial.prototype.serialize = function () {
  54125. var serializationObject = {};
  54126. serializationObject.name = this.name;
  54127. serializationObject.id = this.id;
  54128. serializationObject.tags = BABYLON.Tags.GetTags(this);
  54129. serializationObject.materials = [];
  54130. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  54131. var subMat = this.subMaterials[matIndex];
  54132. if (subMat) {
  54133. serializationObject.materials.push(subMat.id);
  54134. }
  54135. else {
  54136. serializationObject.materials.push(null);
  54137. }
  54138. }
  54139. return serializationObject;
  54140. };
  54141. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54142. var scene = this.getScene();
  54143. if (!scene) {
  54144. return;
  54145. }
  54146. var index = scene.multiMaterials.indexOf(this);
  54147. if (index >= 0) {
  54148. scene.multiMaterials.splice(index, 1);
  54149. }
  54150. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54151. };
  54152. return MultiMaterial;
  54153. }(BABYLON.Material));
  54154. BABYLON.MultiMaterial = MultiMaterial;
  54155. })(BABYLON || (BABYLON = {}));
  54156. //# sourceMappingURL=babylon.multiMaterial.js.map
  54157. var BABYLON;
  54158. (function (BABYLON) {
  54159. var FreeCameraTouchInput = /** @class */ (function () {
  54160. function FreeCameraTouchInput() {
  54161. this._offsetX = null;
  54162. this._offsetY = null;
  54163. this._pointerCount = 0;
  54164. this._pointerPressed = new Array();
  54165. this.touchAngularSensibility = 200000.0;
  54166. this.touchMoveSensibility = 250.0;
  54167. }
  54168. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  54169. var _this = this;
  54170. var previousPosition = null;
  54171. if (this._pointerInput === undefined) {
  54172. this._onLostFocus = function (evt) {
  54173. _this._offsetX = null;
  54174. _this._offsetY = null;
  54175. };
  54176. this._pointerInput = function (p, s) {
  54177. var evt = p.event;
  54178. if (evt.pointerType === "mouse") {
  54179. return;
  54180. }
  54181. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  54182. if (!noPreventDefault) {
  54183. evt.preventDefault();
  54184. }
  54185. _this._pointerPressed.push(evt.pointerId);
  54186. if (_this._pointerPressed.length !== 1) {
  54187. return;
  54188. }
  54189. previousPosition = {
  54190. x: evt.clientX,
  54191. y: evt.clientY
  54192. };
  54193. }
  54194. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  54195. if (!noPreventDefault) {
  54196. evt.preventDefault();
  54197. }
  54198. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54199. if (index === -1) {
  54200. return;
  54201. }
  54202. _this._pointerPressed.splice(index, 1);
  54203. if (index != 0) {
  54204. return;
  54205. }
  54206. previousPosition = null;
  54207. _this._offsetX = null;
  54208. _this._offsetY = null;
  54209. }
  54210. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54211. if (!noPreventDefault) {
  54212. evt.preventDefault();
  54213. }
  54214. if (!previousPosition) {
  54215. return;
  54216. }
  54217. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54218. if (index != 0) {
  54219. return;
  54220. }
  54221. _this._offsetX = evt.clientX - previousPosition.x;
  54222. _this._offsetY = -(evt.clientY - previousPosition.y);
  54223. }
  54224. };
  54225. }
  54226. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54227. if (this._onLostFocus) {
  54228. element.addEventListener("blur", this._onLostFocus);
  54229. }
  54230. };
  54231. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54232. if (this._pointerInput && element) {
  54233. if (this._observer) {
  54234. this.camera.getScene().onPointerObservable.remove(this._observer);
  54235. this._observer = null;
  54236. }
  54237. if (this._onLostFocus) {
  54238. element.removeEventListener("blur", this._onLostFocus);
  54239. this._onLostFocus = null;
  54240. }
  54241. this._pointerPressed = [];
  54242. this._offsetX = null;
  54243. this._offsetY = null;
  54244. this._pointerCount = 0;
  54245. }
  54246. };
  54247. FreeCameraTouchInput.prototype.checkInputs = function () {
  54248. if (this._offsetX && this._offsetY) {
  54249. var camera = this.camera;
  54250. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54251. if (this._pointerPressed.length > 1) {
  54252. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54253. }
  54254. else {
  54255. var speed = camera._computeLocalCameraSpeed();
  54256. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54257. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54258. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54259. }
  54260. }
  54261. };
  54262. FreeCameraTouchInput.prototype.getClassName = function () {
  54263. return "FreeCameraTouchInput";
  54264. };
  54265. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54266. return "touch";
  54267. };
  54268. __decorate([
  54269. BABYLON.serialize()
  54270. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54271. __decorate([
  54272. BABYLON.serialize()
  54273. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54274. return FreeCameraTouchInput;
  54275. }());
  54276. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54277. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54278. })(BABYLON || (BABYLON = {}));
  54279. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54280. var BABYLON;
  54281. (function (BABYLON) {
  54282. // We're mainly based on the logic defined into the FreeCamera code
  54283. var TouchCamera = /** @class */ (function (_super) {
  54284. __extends(TouchCamera, _super);
  54285. //-- end properties for backward compatibility for inputs
  54286. function TouchCamera(name, position, scene) {
  54287. var _this = _super.call(this, name, position, scene) || this;
  54288. _this.inputs.addTouch();
  54289. _this._setupInputs();
  54290. return _this;
  54291. }
  54292. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54293. //-- Begin properties for backward compatibility for inputs
  54294. get: function () {
  54295. var touch = this.inputs.attached["touch"];
  54296. if (touch)
  54297. return touch.touchAngularSensibility;
  54298. return 0;
  54299. },
  54300. set: function (value) {
  54301. var touch = this.inputs.attached["touch"];
  54302. if (touch)
  54303. touch.touchAngularSensibility = value;
  54304. },
  54305. enumerable: true,
  54306. configurable: true
  54307. });
  54308. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54309. get: function () {
  54310. var touch = this.inputs.attached["touch"];
  54311. if (touch)
  54312. return touch.touchMoveSensibility;
  54313. return 0;
  54314. },
  54315. set: function (value) {
  54316. var touch = this.inputs.attached["touch"];
  54317. if (touch)
  54318. touch.touchMoveSensibility = value;
  54319. },
  54320. enumerable: true,
  54321. configurable: true
  54322. });
  54323. TouchCamera.prototype.getClassName = function () {
  54324. return "TouchCamera";
  54325. };
  54326. TouchCamera.prototype._setupInputs = function () {
  54327. var mouse = this.inputs.attached["mouse"];
  54328. if (mouse) {
  54329. mouse.touchEnabled = false;
  54330. }
  54331. };
  54332. return TouchCamera;
  54333. }(BABYLON.FreeCamera));
  54334. BABYLON.TouchCamera = TouchCamera;
  54335. })(BABYLON || (BABYLON = {}));
  54336. //# sourceMappingURL=babylon.touchCamera.js.map
  54337. var BABYLON;
  54338. (function (BABYLON) {
  54339. var ProceduralTexture = /** @class */ (function (_super) {
  54340. __extends(ProceduralTexture, _super);
  54341. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54342. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54343. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54344. if (isCube === void 0) { isCube = false; }
  54345. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54346. _this.isCube = isCube;
  54347. _this.isEnabled = true;
  54348. _this._currentRefreshId = -1;
  54349. _this._refreshRate = 1;
  54350. _this._vertexBuffers = {};
  54351. _this._uniforms = new Array();
  54352. _this._samplers = new Array();
  54353. _this._textures = {};
  54354. _this._floats = {};
  54355. _this._floatsArrays = {};
  54356. _this._colors3 = {};
  54357. _this._colors4 = {};
  54358. _this._vectors2 = {};
  54359. _this._vectors3 = {};
  54360. _this._matrices = {};
  54361. _this._fallbackTextureUsed = false;
  54362. scene._proceduralTextures.push(_this);
  54363. _this._engine = scene.getEngine();
  54364. _this.name = name;
  54365. _this.isRenderTarget = true;
  54366. _this._size = size;
  54367. _this._generateMipMaps = generateMipMaps;
  54368. _this.setFragment(fragment);
  54369. _this._fallbackTexture = fallbackTexture;
  54370. if (isCube) {
  54371. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54372. _this.setFloat("face", 0);
  54373. }
  54374. else {
  54375. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54376. }
  54377. // VBO
  54378. var vertices = [];
  54379. vertices.push(1, 1);
  54380. vertices.push(-1, 1);
  54381. vertices.push(-1, -1);
  54382. vertices.push(1, -1);
  54383. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54384. _this._createIndexBuffer();
  54385. return _this;
  54386. }
  54387. ProceduralTexture.prototype._createIndexBuffer = function () {
  54388. var engine = this._engine;
  54389. // Indices
  54390. var indices = [];
  54391. indices.push(0);
  54392. indices.push(1);
  54393. indices.push(2);
  54394. indices.push(0);
  54395. indices.push(2);
  54396. indices.push(3);
  54397. this._indexBuffer = engine.createIndexBuffer(indices);
  54398. };
  54399. ProceduralTexture.prototype._rebuild = function () {
  54400. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54401. if (vb) {
  54402. vb._rebuild();
  54403. }
  54404. this._createIndexBuffer();
  54405. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54406. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54407. }
  54408. };
  54409. ProceduralTexture.prototype.reset = function () {
  54410. if (this._effect === undefined) {
  54411. return;
  54412. }
  54413. var engine = this._engine;
  54414. engine._releaseEffect(this._effect);
  54415. };
  54416. ProceduralTexture.prototype.isReady = function () {
  54417. var _this = this;
  54418. var engine = this._engine;
  54419. var shaders;
  54420. if (!this._fragment) {
  54421. return false;
  54422. }
  54423. if (this._fallbackTextureUsed) {
  54424. return true;
  54425. }
  54426. if (this._fragment.fragmentElement !== undefined) {
  54427. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54428. }
  54429. else {
  54430. shaders = { vertex: "procedural", fragment: this._fragment };
  54431. }
  54432. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54433. _this.releaseInternalTexture();
  54434. if (_this._fallbackTexture) {
  54435. _this._texture = _this._fallbackTexture._texture;
  54436. if (_this._texture) {
  54437. _this._texture.incrementReferences();
  54438. }
  54439. }
  54440. _this._fallbackTextureUsed = true;
  54441. });
  54442. return this._effect.isReady();
  54443. };
  54444. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54445. this._currentRefreshId = -1;
  54446. };
  54447. ProceduralTexture.prototype.setFragment = function (fragment) {
  54448. this._fragment = fragment;
  54449. };
  54450. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54451. get: function () {
  54452. return this._refreshRate;
  54453. },
  54454. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54455. set: function (value) {
  54456. this._refreshRate = value;
  54457. this.resetRefreshCounter();
  54458. },
  54459. enumerable: true,
  54460. configurable: true
  54461. });
  54462. ProceduralTexture.prototype._shouldRender = function () {
  54463. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54464. return false;
  54465. }
  54466. if (this._fallbackTextureUsed) {
  54467. return false;
  54468. }
  54469. if (this._currentRefreshId === -1) {
  54470. this._currentRefreshId = 1;
  54471. return true;
  54472. }
  54473. if (this.refreshRate === this._currentRefreshId) {
  54474. this._currentRefreshId = 1;
  54475. return true;
  54476. }
  54477. this._currentRefreshId++;
  54478. return false;
  54479. };
  54480. ProceduralTexture.prototype.getRenderSize = function () {
  54481. return this._size;
  54482. };
  54483. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54484. if (this._fallbackTextureUsed) {
  54485. return;
  54486. }
  54487. this.releaseInternalTexture();
  54488. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54489. };
  54490. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54491. if (this._uniforms.indexOf(uniformName) === -1) {
  54492. this._uniforms.push(uniformName);
  54493. }
  54494. };
  54495. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54496. if (this._samplers.indexOf(name) === -1) {
  54497. this._samplers.push(name);
  54498. }
  54499. this._textures[name] = texture;
  54500. return this;
  54501. };
  54502. ProceduralTexture.prototype.setFloat = function (name, value) {
  54503. this._checkUniform(name);
  54504. this._floats[name] = value;
  54505. return this;
  54506. };
  54507. ProceduralTexture.prototype.setFloats = function (name, value) {
  54508. this._checkUniform(name);
  54509. this._floatsArrays[name] = value;
  54510. return this;
  54511. };
  54512. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54513. this._checkUniform(name);
  54514. this._colors3[name] = value;
  54515. return this;
  54516. };
  54517. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54518. this._checkUniform(name);
  54519. this._colors4[name] = value;
  54520. return this;
  54521. };
  54522. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54523. this._checkUniform(name);
  54524. this._vectors2[name] = value;
  54525. return this;
  54526. };
  54527. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54528. this._checkUniform(name);
  54529. this._vectors3[name] = value;
  54530. return this;
  54531. };
  54532. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54533. this._checkUniform(name);
  54534. this._matrices[name] = value;
  54535. return this;
  54536. };
  54537. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54538. var scene = this.getScene();
  54539. if (!scene) {
  54540. return;
  54541. }
  54542. var engine = this._engine;
  54543. // Render
  54544. engine.enableEffect(this._effect);
  54545. engine.setState(false);
  54546. // Texture
  54547. for (var name in this._textures) {
  54548. this._effect.setTexture(name, this._textures[name]);
  54549. }
  54550. // Float
  54551. for (name in this._floats) {
  54552. this._effect.setFloat(name, this._floats[name]);
  54553. }
  54554. // Floats
  54555. for (name in this._floatsArrays) {
  54556. this._effect.setArray(name, this._floatsArrays[name]);
  54557. }
  54558. // Color3
  54559. for (name in this._colors3) {
  54560. this._effect.setColor3(name, this._colors3[name]);
  54561. }
  54562. // Color4
  54563. for (name in this._colors4) {
  54564. var color = this._colors4[name];
  54565. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54566. }
  54567. // Vector2
  54568. for (name in this._vectors2) {
  54569. this._effect.setVector2(name, this._vectors2[name]);
  54570. }
  54571. // Vector3
  54572. for (name in this._vectors3) {
  54573. this._effect.setVector3(name, this._vectors3[name]);
  54574. }
  54575. // Matrix
  54576. for (name in this._matrices) {
  54577. this._effect.setMatrix(name, this._matrices[name]);
  54578. }
  54579. if (!this._texture) {
  54580. return;
  54581. }
  54582. if (this.isCube) {
  54583. for (var face = 0; face < 6; face++) {
  54584. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54585. // VBOs
  54586. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54587. this._effect.setFloat("face", face);
  54588. // Clear
  54589. engine.clear(scene.clearColor, true, true, true);
  54590. // Draw order
  54591. engine.draw(true, 0, 6);
  54592. // Mipmaps
  54593. if (face === 5) {
  54594. engine.generateMipMapsForCubemap(this._texture);
  54595. }
  54596. }
  54597. }
  54598. else {
  54599. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54600. // VBOs
  54601. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54602. // Clear
  54603. engine.clear(scene.clearColor, true, true, true);
  54604. // Draw order
  54605. engine.draw(true, 0, 6);
  54606. }
  54607. // Unbind
  54608. engine.unBindFramebuffer(this._texture, this.isCube);
  54609. if (this.onGenerated) {
  54610. this.onGenerated();
  54611. }
  54612. };
  54613. ProceduralTexture.prototype.clone = function () {
  54614. var textureSize = this.getSize();
  54615. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54616. // Base texture
  54617. newTexture.hasAlpha = this.hasAlpha;
  54618. newTexture.level = this.level;
  54619. // RenderTarget Texture
  54620. newTexture.coordinatesMode = this.coordinatesMode;
  54621. return newTexture;
  54622. };
  54623. ProceduralTexture.prototype.dispose = function () {
  54624. var scene = this.getScene();
  54625. if (!scene) {
  54626. return;
  54627. }
  54628. var index = scene._proceduralTextures.indexOf(this);
  54629. if (index >= 0) {
  54630. scene._proceduralTextures.splice(index, 1);
  54631. }
  54632. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54633. if (vertexBuffer) {
  54634. vertexBuffer.dispose();
  54635. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54636. }
  54637. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54638. this._indexBuffer = null;
  54639. }
  54640. _super.prototype.dispose.call(this);
  54641. };
  54642. return ProceduralTexture;
  54643. }(BABYLON.Texture));
  54644. BABYLON.ProceduralTexture = ProceduralTexture;
  54645. })(BABYLON || (BABYLON = {}));
  54646. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54647. var BABYLON;
  54648. (function (BABYLON) {
  54649. var CustomProceduralTexture = /** @class */ (function (_super) {
  54650. __extends(CustomProceduralTexture, _super);
  54651. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54652. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54653. _this._animate = true;
  54654. _this._time = 0;
  54655. _this._texturePath = texturePath;
  54656. //Try to load json
  54657. _this.loadJson(texturePath);
  54658. _this.refreshRate = 1;
  54659. return _this;
  54660. }
  54661. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54662. var _this = this;
  54663. var noConfigFile = function () {
  54664. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54665. try {
  54666. _this.setFragment(_this._texturePath);
  54667. }
  54668. catch (ex) {
  54669. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54670. }
  54671. };
  54672. var configFileUrl = jsonUrl + "/config.json";
  54673. var xhr = new XMLHttpRequest();
  54674. xhr.open("GET", configFileUrl, true);
  54675. xhr.addEventListener("load", function () {
  54676. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54677. try {
  54678. _this._config = JSON.parse(xhr.response);
  54679. _this.updateShaderUniforms();
  54680. _this.updateTextures();
  54681. _this.setFragment(_this._texturePath + "/custom");
  54682. _this._animate = _this._config.animate;
  54683. _this.refreshRate = _this._config.refreshrate;
  54684. }
  54685. catch (ex) {
  54686. noConfigFile();
  54687. }
  54688. }
  54689. else {
  54690. noConfigFile();
  54691. }
  54692. }, false);
  54693. xhr.addEventListener("error", function () {
  54694. noConfigFile();
  54695. }, false);
  54696. try {
  54697. xhr.send();
  54698. }
  54699. catch (ex) {
  54700. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54701. }
  54702. };
  54703. CustomProceduralTexture.prototype.isReady = function () {
  54704. if (!_super.prototype.isReady.call(this)) {
  54705. return false;
  54706. }
  54707. for (var name in this._textures) {
  54708. var texture = this._textures[name];
  54709. if (!texture.isReady()) {
  54710. return false;
  54711. }
  54712. }
  54713. return true;
  54714. };
  54715. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54716. var scene = this.getScene();
  54717. if (this._animate && scene) {
  54718. this._time += scene.getAnimationRatio() * 0.03;
  54719. this.updateShaderUniforms();
  54720. }
  54721. _super.prototype.render.call(this, useCameraPostProcess);
  54722. };
  54723. CustomProceduralTexture.prototype.updateTextures = function () {
  54724. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54725. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54726. }
  54727. };
  54728. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54729. if (this._config) {
  54730. for (var j = 0; j < this._config.uniforms.length; j++) {
  54731. var uniform = this._config.uniforms[j];
  54732. switch (uniform.type) {
  54733. case "float":
  54734. this.setFloat(uniform.name, uniform.value);
  54735. break;
  54736. case "color3":
  54737. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54738. break;
  54739. case "color4":
  54740. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54741. break;
  54742. case "vector2":
  54743. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54744. break;
  54745. case "vector3":
  54746. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54747. break;
  54748. }
  54749. }
  54750. }
  54751. this.setFloat("time", this._time);
  54752. };
  54753. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54754. get: function () {
  54755. return this._animate;
  54756. },
  54757. set: function (value) {
  54758. this._animate = value;
  54759. },
  54760. enumerable: true,
  54761. configurable: true
  54762. });
  54763. return CustomProceduralTexture;
  54764. }(BABYLON.ProceduralTexture));
  54765. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54766. })(BABYLON || (BABYLON = {}));
  54767. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54768. var BABYLON;
  54769. (function (BABYLON) {
  54770. var FreeCameraGamepadInput = /** @class */ (function () {
  54771. function FreeCameraGamepadInput() {
  54772. this.gamepadAngularSensibility = 200;
  54773. this.gamepadMoveSensibility = 40;
  54774. // private members
  54775. this._cameraTransform = BABYLON.Matrix.Identity();
  54776. this._deltaTransform = BABYLON.Vector3.Zero();
  54777. this._vector3 = BABYLON.Vector3.Zero();
  54778. this._vector2 = BABYLON.Vector2.Zero();
  54779. }
  54780. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54781. var _this = this;
  54782. var manager = this.camera.getScene().gamepadManager;
  54783. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54784. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54785. // prioritize XBOX gamepads.
  54786. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54787. _this.gamepad = gamepad;
  54788. }
  54789. }
  54790. });
  54791. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54792. if (_this.gamepad === gamepad) {
  54793. _this.gamepad = null;
  54794. }
  54795. });
  54796. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54797. };
  54798. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54799. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54800. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54801. this.gamepad = null;
  54802. };
  54803. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54804. if (this.gamepad && this.gamepad.leftStick) {
  54805. var camera = this.camera;
  54806. var LSValues = this.gamepad.leftStick;
  54807. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54808. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54809. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54810. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54811. var RSValues = this.gamepad.rightStick;
  54812. if (RSValues) {
  54813. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54814. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54815. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54816. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54817. }
  54818. else {
  54819. RSValues = { x: 0, y: 0 };
  54820. }
  54821. if (!camera.rotationQuaternion) {
  54822. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54823. }
  54824. else {
  54825. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54826. }
  54827. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54828. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54829. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54830. camera.cameraDirection.addInPlace(this._deltaTransform);
  54831. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54832. camera.cameraRotation.addInPlace(this._vector2);
  54833. }
  54834. };
  54835. FreeCameraGamepadInput.prototype.getClassName = function () {
  54836. return "FreeCameraGamepadInput";
  54837. };
  54838. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54839. return "gamepad";
  54840. };
  54841. __decorate([
  54842. BABYLON.serialize()
  54843. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54844. __decorate([
  54845. BABYLON.serialize()
  54846. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54847. return FreeCameraGamepadInput;
  54848. }());
  54849. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  54850. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  54851. })(BABYLON || (BABYLON = {}));
  54852. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  54853. var BABYLON;
  54854. (function (BABYLON) {
  54855. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  54856. function ArcRotateCameraGamepadInput() {
  54857. this.gamepadRotationSensibility = 80;
  54858. this.gamepadMoveSensibility = 40;
  54859. }
  54860. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54861. var _this = this;
  54862. var manager = this.camera.getScene().gamepadManager;
  54863. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54864. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54865. // prioritize XBOX gamepads.
  54866. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54867. _this.gamepad = gamepad;
  54868. }
  54869. }
  54870. });
  54871. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54872. if (_this.gamepad === gamepad) {
  54873. _this.gamepad = null;
  54874. }
  54875. });
  54876. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54877. };
  54878. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  54879. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54880. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54881. this.gamepad = null;
  54882. };
  54883. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  54884. if (this.gamepad) {
  54885. var camera = this.camera;
  54886. var RSValues = this.gamepad.rightStick;
  54887. if (RSValues) {
  54888. if (RSValues.x != 0) {
  54889. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  54890. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  54891. camera.inertialAlphaOffset += normalizedRX;
  54892. }
  54893. }
  54894. if (RSValues.y != 0) {
  54895. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  54896. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  54897. camera.inertialBetaOffset += normalizedRY;
  54898. }
  54899. }
  54900. }
  54901. var LSValues = this.gamepad.leftStick;
  54902. if (LSValues && LSValues.y != 0) {
  54903. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54904. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  54905. this.camera.inertialRadiusOffset -= normalizedLY;
  54906. }
  54907. }
  54908. }
  54909. };
  54910. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  54911. return "ArcRotateCameraGamepadInput";
  54912. };
  54913. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  54914. return "gamepad";
  54915. };
  54916. __decorate([
  54917. BABYLON.serialize()
  54918. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  54919. __decorate([
  54920. BABYLON.serialize()
  54921. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54922. return ArcRotateCameraGamepadInput;
  54923. }());
  54924. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  54925. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  54926. })(BABYLON || (BABYLON = {}));
  54927. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  54928. var BABYLON;
  54929. (function (BABYLON) {
  54930. var GamepadManager = /** @class */ (function () {
  54931. function GamepadManager() {
  54932. var _this = this;
  54933. this._babylonGamepads = [];
  54934. this._oneGamepadConnected = false;
  54935. this._isMonitoring = false;
  54936. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  54937. if (!BABYLON.Tools.IsWindowObjectExist()) {
  54938. this._gamepadEventSupported = false;
  54939. }
  54940. else {
  54941. this._gamepadEventSupported = 'GamepadEvent' in window;
  54942. this._gamepadSupport = (navigator.getGamepads ||
  54943. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  54944. }
  54945. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  54946. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54947. for (var i in _this._babylonGamepads) {
  54948. var gamepad = _this._babylonGamepads[i];
  54949. if (gamepad && gamepad._isConnected) {
  54950. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  54951. }
  54952. }
  54953. });
  54954. this._onGamepadConnectedEvent = function (evt) {
  54955. var gamepad = evt.gamepad;
  54956. if (gamepad.index in _this._babylonGamepads) {
  54957. if (_this._babylonGamepads[gamepad.index].isConnected) {
  54958. return;
  54959. }
  54960. }
  54961. var newGamepad;
  54962. if (_this._babylonGamepads[gamepad.index]) {
  54963. newGamepad = _this._babylonGamepads[gamepad.index];
  54964. newGamepad.browserGamepad = gamepad;
  54965. newGamepad._isConnected = true;
  54966. }
  54967. else {
  54968. newGamepad = _this._addNewGamepad(gamepad);
  54969. }
  54970. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54971. _this._startMonitoringGamepads();
  54972. };
  54973. this._onGamepadDisconnectedEvent = function (evt) {
  54974. var gamepad = evt.gamepad;
  54975. // Remove the gamepad from the list of gamepads to monitor.
  54976. for (var i in _this._babylonGamepads) {
  54977. if (_this._babylonGamepads[i].index === gamepad.index) {
  54978. var disconnectedGamepad = _this._babylonGamepads[i];
  54979. disconnectedGamepad._isConnected = false;
  54980. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  54981. break;
  54982. }
  54983. }
  54984. };
  54985. if (this._gamepadSupport) {
  54986. //first add already-connected gamepads
  54987. this._updateGamepadObjects();
  54988. if (this._babylonGamepads.length) {
  54989. this._startMonitoringGamepads();
  54990. }
  54991. // Checking if the gamepad connected event is supported (like in Firefox)
  54992. if (this._gamepadEventSupported) {
  54993. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54994. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  54995. }
  54996. else {
  54997. this._startMonitoringGamepads();
  54998. }
  54999. }
  55000. }
  55001. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  55002. get: function () {
  55003. return this._babylonGamepads;
  55004. },
  55005. enumerable: true,
  55006. configurable: true
  55007. });
  55008. GamepadManager.prototype.getGamepadByType = function (type) {
  55009. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  55010. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  55011. var gamepad = _a[_i];
  55012. if (gamepad && gamepad.type === type) {
  55013. return gamepad;
  55014. }
  55015. }
  55016. return null;
  55017. };
  55018. GamepadManager.prototype.dispose = function () {
  55019. if (this._gamepadEventSupported) {
  55020. if (this._onGamepadConnectedEvent) {
  55021. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  55022. }
  55023. if (this._onGamepadDisconnectedEvent) {
  55024. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  55025. }
  55026. this._onGamepadConnectedEvent = null;
  55027. this._onGamepadDisconnectedEvent = null;
  55028. }
  55029. this._babylonGamepads.forEach(function (gamepad) {
  55030. gamepad.dispose();
  55031. });
  55032. this.onGamepadConnectedObservable.clear();
  55033. this.onGamepadDisconnectedObservable.clear();
  55034. this._oneGamepadConnected = false;
  55035. this._stopMonitoringGamepads();
  55036. this._babylonGamepads = [];
  55037. };
  55038. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  55039. if (!this._oneGamepadConnected) {
  55040. this._oneGamepadConnected = true;
  55041. }
  55042. var newGamepad;
  55043. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  55044. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55045. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  55046. }
  55047. else if (gamepad.pose) {
  55048. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  55049. }
  55050. else {
  55051. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  55052. }
  55053. this._babylonGamepads[newGamepad.index] = newGamepad;
  55054. return newGamepad;
  55055. };
  55056. GamepadManager.prototype._startMonitoringGamepads = function () {
  55057. if (!this._isMonitoring) {
  55058. this._isMonitoring = true;
  55059. this._checkGamepadsStatus();
  55060. }
  55061. };
  55062. GamepadManager.prototype._stopMonitoringGamepads = function () {
  55063. this._isMonitoring = false;
  55064. };
  55065. GamepadManager.prototype._checkGamepadsStatus = function () {
  55066. var _this = this;
  55067. // Hack to be compatible Chrome
  55068. this._updateGamepadObjects();
  55069. for (var i in this._babylonGamepads) {
  55070. var gamepad = this._babylonGamepads[i];
  55071. if (!gamepad || !gamepad.isConnected) {
  55072. continue;
  55073. }
  55074. gamepad.update();
  55075. }
  55076. if (this._isMonitoring) {
  55077. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  55078. }
  55079. };
  55080. // This function is called only on Chrome, which does not properly support
  55081. // connection/disconnection events and forces you to recopy again the gamepad object
  55082. GamepadManager.prototype._updateGamepadObjects = function () {
  55083. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55084. for (var i = 0; i < gamepads.length; i++) {
  55085. if (gamepads[i]) {
  55086. if (!this._babylonGamepads[gamepads[i].index]) {
  55087. var newGamepad = this._addNewGamepad(gamepads[i]);
  55088. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55089. }
  55090. else {
  55091. // Forced to copy again this object for Chrome for unknown reason
  55092. this._babylonGamepads[i].browserGamepad = gamepads[i];
  55093. if (!this._babylonGamepads[i].isConnected) {
  55094. this._babylonGamepads[i]._isConnected = true;
  55095. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  55096. }
  55097. }
  55098. }
  55099. }
  55100. };
  55101. return GamepadManager;
  55102. }());
  55103. BABYLON.GamepadManager = GamepadManager;
  55104. })(BABYLON || (BABYLON = {}));
  55105. //# sourceMappingURL=babylon.gamepadManager.js.map
  55106. var BABYLON;
  55107. (function (BABYLON) {
  55108. var StickValues = /** @class */ (function () {
  55109. function StickValues(x, y) {
  55110. this.x = x;
  55111. this.y = y;
  55112. }
  55113. return StickValues;
  55114. }());
  55115. BABYLON.StickValues = StickValues;
  55116. var Gamepad = /** @class */ (function () {
  55117. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  55118. if (leftStickX === void 0) { leftStickX = 0; }
  55119. if (leftStickY === void 0) { leftStickY = 1; }
  55120. if (rightStickX === void 0) { rightStickX = 2; }
  55121. if (rightStickY === void 0) { rightStickY = 3; }
  55122. this.id = id;
  55123. this.index = index;
  55124. this.browserGamepad = browserGamepad;
  55125. this._isConnected = true;
  55126. this.type = Gamepad.GAMEPAD;
  55127. this._leftStickAxisX = leftStickX;
  55128. this._leftStickAxisY = leftStickY;
  55129. this._rightStickAxisX = rightStickX;
  55130. this._rightStickAxisY = rightStickY;
  55131. if (this.browserGamepad.axes.length >= 2) {
  55132. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55133. }
  55134. if (this.browserGamepad.axes.length >= 4) {
  55135. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55136. }
  55137. }
  55138. Object.defineProperty(Gamepad.prototype, "isConnected", {
  55139. get: function () {
  55140. return this._isConnected;
  55141. },
  55142. enumerable: true,
  55143. configurable: true
  55144. });
  55145. Gamepad.prototype.onleftstickchanged = function (callback) {
  55146. this._onleftstickchanged = callback;
  55147. };
  55148. Gamepad.prototype.onrightstickchanged = function (callback) {
  55149. this._onrightstickchanged = callback;
  55150. };
  55151. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55152. get: function () {
  55153. return this._leftStick;
  55154. },
  55155. set: function (newValues) {
  55156. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55157. this._onleftstickchanged(newValues);
  55158. }
  55159. this._leftStick = newValues;
  55160. },
  55161. enumerable: true,
  55162. configurable: true
  55163. });
  55164. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55165. get: function () {
  55166. return this._rightStick;
  55167. },
  55168. set: function (newValues) {
  55169. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55170. this._onrightstickchanged(newValues);
  55171. }
  55172. this._rightStick = newValues;
  55173. },
  55174. enumerable: true,
  55175. configurable: true
  55176. });
  55177. Gamepad.prototype.update = function () {
  55178. if (this._leftStick) {
  55179. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55180. }
  55181. if (this._rightStick) {
  55182. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55183. }
  55184. };
  55185. Gamepad.prototype.dispose = function () {
  55186. };
  55187. Gamepad.GAMEPAD = 0;
  55188. Gamepad.GENERIC = 1;
  55189. Gamepad.XBOX = 2;
  55190. Gamepad.POSE_ENABLED = 3;
  55191. return Gamepad;
  55192. }());
  55193. BABYLON.Gamepad = Gamepad;
  55194. var GenericPad = /** @class */ (function (_super) {
  55195. __extends(GenericPad, _super);
  55196. function GenericPad(id, index, browserGamepad) {
  55197. var _this = _super.call(this, id, index, browserGamepad) || this;
  55198. _this.onButtonDownObservable = new BABYLON.Observable();
  55199. _this.onButtonUpObservable = new BABYLON.Observable();
  55200. _this.type = Gamepad.GENERIC;
  55201. _this._buttons = new Array(browserGamepad.buttons.length);
  55202. return _this;
  55203. }
  55204. GenericPad.prototype.onbuttondown = function (callback) {
  55205. this._onbuttondown = callback;
  55206. };
  55207. GenericPad.prototype.onbuttonup = function (callback) {
  55208. this._onbuttonup = callback;
  55209. };
  55210. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55211. if (newValue !== currentValue) {
  55212. if (newValue === 1) {
  55213. if (this._onbuttondown) {
  55214. this._onbuttondown(buttonIndex);
  55215. }
  55216. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55217. }
  55218. if (newValue === 0) {
  55219. if (this._onbuttonup) {
  55220. this._onbuttonup(buttonIndex);
  55221. }
  55222. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55223. }
  55224. }
  55225. return newValue;
  55226. };
  55227. GenericPad.prototype.update = function () {
  55228. _super.prototype.update.call(this);
  55229. for (var index = 0; index < this._buttons.length; index++) {
  55230. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55231. }
  55232. };
  55233. return GenericPad;
  55234. }(Gamepad));
  55235. BABYLON.GenericPad = GenericPad;
  55236. })(BABYLON || (BABYLON = {}));
  55237. //# sourceMappingURL=babylon.gamepad.js.map
  55238. var BABYLON;
  55239. (function (BABYLON) {
  55240. var Xbox360Button;
  55241. (function (Xbox360Button) {
  55242. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55243. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55244. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55245. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55246. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55247. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55248. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55249. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55250. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55251. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55252. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55253. var Xbox360Dpad;
  55254. (function (Xbox360Dpad) {
  55255. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55256. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55257. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55258. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55259. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55260. var Xbox360Pad = /** @class */ (function (_super) {
  55261. __extends(Xbox360Pad, _super);
  55262. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55263. if (xboxOne === void 0) { xboxOne = false; }
  55264. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55265. _this._leftTrigger = 0;
  55266. _this._rightTrigger = 0;
  55267. _this.onButtonDownObservable = new BABYLON.Observable();
  55268. _this.onButtonUpObservable = new BABYLON.Observable();
  55269. _this.onPadDownObservable = new BABYLON.Observable();
  55270. _this.onPadUpObservable = new BABYLON.Observable();
  55271. _this._buttonA = 0;
  55272. _this._buttonB = 0;
  55273. _this._buttonX = 0;
  55274. _this._buttonY = 0;
  55275. _this._buttonBack = 0;
  55276. _this._buttonStart = 0;
  55277. _this._buttonLB = 0;
  55278. _this._buttonRB = 0;
  55279. _this._buttonLeftStick = 0;
  55280. _this._buttonRightStick = 0;
  55281. _this._dPadUp = 0;
  55282. _this._dPadDown = 0;
  55283. _this._dPadLeft = 0;
  55284. _this._dPadRight = 0;
  55285. _this._isXboxOnePad = false;
  55286. _this.type = BABYLON.Gamepad.XBOX;
  55287. _this._isXboxOnePad = xboxOne;
  55288. return _this;
  55289. }
  55290. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55291. this._onlefttriggerchanged = callback;
  55292. };
  55293. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55294. this._onrighttriggerchanged = callback;
  55295. };
  55296. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55297. get: function () {
  55298. return this._leftTrigger;
  55299. },
  55300. set: function (newValue) {
  55301. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55302. this._onlefttriggerchanged(newValue);
  55303. }
  55304. this._leftTrigger = newValue;
  55305. },
  55306. enumerable: true,
  55307. configurable: true
  55308. });
  55309. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55310. get: function () {
  55311. return this._rightTrigger;
  55312. },
  55313. set: function (newValue) {
  55314. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55315. this._onrighttriggerchanged(newValue);
  55316. }
  55317. this._rightTrigger = newValue;
  55318. },
  55319. enumerable: true,
  55320. configurable: true
  55321. });
  55322. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55323. this._onbuttondown = callback;
  55324. };
  55325. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55326. this._onbuttonup = callback;
  55327. };
  55328. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55329. this._ondpaddown = callback;
  55330. };
  55331. Xbox360Pad.prototype.ondpadup = function (callback) {
  55332. this._ondpadup = callback;
  55333. };
  55334. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55335. if (newValue !== currentValue) {
  55336. if (newValue === 1) {
  55337. if (this._onbuttondown) {
  55338. this._onbuttondown(buttonType);
  55339. }
  55340. this.onButtonDownObservable.notifyObservers(buttonType);
  55341. }
  55342. if (newValue === 0) {
  55343. if (this._onbuttonup) {
  55344. this._onbuttonup(buttonType);
  55345. }
  55346. this.onButtonUpObservable.notifyObservers(buttonType);
  55347. }
  55348. }
  55349. return newValue;
  55350. };
  55351. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55352. if (newValue !== currentValue) {
  55353. if (newValue === 1) {
  55354. if (this._ondpaddown) {
  55355. this._ondpaddown(buttonType);
  55356. }
  55357. this.onPadDownObservable.notifyObservers(buttonType);
  55358. }
  55359. if (newValue === 0) {
  55360. if (this._ondpadup) {
  55361. this._ondpadup(buttonType);
  55362. }
  55363. this.onPadUpObservable.notifyObservers(buttonType);
  55364. }
  55365. }
  55366. return newValue;
  55367. };
  55368. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55369. get: function () {
  55370. return this._buttonA;
  55371. },
  55372. set: function (value) {
  55373. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55374. },
  55375. enumerable: true,
  55376. configurable: true
  55377. });
  55378. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55379. get: function () {
  55380. return this._buttonB;
  55381. },
  55382. set: function (value) {
  55383. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55384. },
  55385. enumerable: true,
  55386. configurable: true
  55387. });
  55388. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55389. get: function () {
  55390. return this._buttonX;
  55391. },
  55392. set: function (value) {
  55393. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55394. },
  55395. enumerable: true,
  55396. configurable: true
  55397. });
  55398. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55399. get: function () {
  55400. return this._buttonY;
  55401. },
  55402. set: function (value) {
  55403. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55404. },
  55405. enumerable: true,
  55406. configurable: true
  55407. });
  55408. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55409. get: function () {
  55410. return this._buttonStart;
  55411. },
  55412. set: function (value) {
  55413. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55414. },
  55415. enumerable: true,
  55416. configurable: true
  55417. });
  55418. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55419. get: function () {
  55420. return this._buttonBack;
  55421. },
  55422. set: function (value) {
  55423. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55424. },
  55425. enumerable: true,
  55426. configurable: true
  55427. });
  55428. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55429. get: function () {
  55430. return this._buttonLB;
  55431. },
  55432. set: function (value) {
  55433. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55434. },
  55435. enumerable: true,
  55436. configurable: true
  55437. });
  55438. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55439. get: function () {
  55440. return this._buttonRB;
  55441. },
  55442. set: function (value) {
  55443. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55444. },
  55445. enumerable: true,
  55446. configurable: true
  55447. });
  55448. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55449. get: function () {
  55450. return this._buttonLeftStick;
  55451. },
  55452. set: function (value) {
  55453. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55454. },
  55455. enumerable: true,
  55456. configurable: true
  55457. });
  55458. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55459. get: function () {
  55460. return this._buttonRightStick;
  55461. },
  55462. set: function (value) {
  55463. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55464. },
  55465. enumerable: true,
  55466. configurable: true
  55467. });
  55468. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55469. get: function () {
  55470. return this._dPadUp;
  55471. },
  55472. set: function (value) {
  55473. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55474. },
  55475. enumerable: true,
  55476. configurable: true
  55477. });
  55478. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55479. get: function () {
  55480. return this._dPadDown;
  55481. },
  55482. set: function (value) {
  55483. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55484. },
  55485. enumerable: true,
  55486. configurable: true
  55487. });
  55488. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55489. get: function () {
  55490. return this._dPadLeft;
  55491. },
  55492. set: function (value) {
  55493. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55494. },
  55495. enumerable: true,
  55496. configurable: true
  55497. });
  55498. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55499. get: function () {
  55500. return this._dPadRight;
  55501. },
  55502. set: function (value) {
  55503. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55504. },
  55505. enumerable: true,
  55506. configurable: true
  55507. });
  55508. Xbox360Pad.prototype.update = function () {
  55509. _super.prototype.update.call(this);
  55510. if (this._isXboxOnePad) {
  55511. this.buttonA = this.browserGamepad.buttons[0].value;
  55512. this.buttonB = this.browserGamepad.buttons[1].value;
  55513. this.buttonX = this.browserGamepad.buttons[2].value;
  55514. this.buttonY = this.browserGamepad.buttons[3].value;
  55515. this.buttonLB = this.browserGamepad.buttons[4].value;
  55516. this.buttonRB = this.browserGamepad.buttons[5].value;
  55517. this.leftTrigger = this.browserGamepad.axes[2];
  55518. this.rightTrigger = this.browserGamepad.axes[5];
  55519. this.buttonBack = this.browserGamepad.buttons[9].value;
  55520. this.buttonStart = this.browserGamepad.buttons[8].value;
  55521. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55522. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55523. this.dPadUp = this.browserGamepad.buttons[11].value;
  55524. this.dPadDown = this.browserGamepad.buttons[12].value;
  55525. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55526. this.dPadRight = this.browserGamepad.buttons[14].value;
  55527. }
  55528. else {
  55529. this.buttonA = this.browserGamepad.buttons[0].value;
  55530. this.buttonB = this.browserGamepad.buttons[1].value;
  55531. this.buttonX = this.browserGamepad.buttons[2].value;
  55532. this.buttonY = this.browserGamepad.buttons[3].value;
  55533. this.buttonLB = this.browserGamepad.buttons[4].value;
  55534. this.buttonRB = this.browserGamepad.buttons[5].value;
  55535. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55536. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55537. this.buttonBack = this.browserGamepad.buttons[8].value;
  55538. this.buttonStart = this.browserGamepad.buttons[9].value;
  55539. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55540. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55541. this.dPadUp = this.browserGamepad.buttons[12].value;
  55542. this.dPadDown = this.browserGamepad.buttons[13].value;
  55543. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55544. this.dPadRight = this.browserGamepad.buttons[15].value;
  55545. }
  55546. };
  55547. return Xbox360Pad;
  55548. }(BABYLON.Gamepad));
  55549. BABYLON.Xbox360Pad = Xbox360Pad;
  55550. })(BABYLON || (BABYLON = {}));
  55551. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55552. var BABYLON;
  55553. (function (BABYLON) {
  55554. var PoseEnabledControllerType;
  55555. (function (PoseEnabledControllerType) {
  55556. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55557. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55558. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55559. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55560. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55561. var PoseEnabledControllerHelper = /** @class */ (function () {
  55562. function PoseEnabledControllerHelper() {
  55563. }
  55564. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55565. // Oculus Touch
  55566. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55567. return new BABYLON.OculusTouchController(vrGamepad);
  55568. }
  55569. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55570. return new BABYLON.WindowsMotionController(vrGamepad);
  55571. }
  55572. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55573. return new BABYLON.ViveController(vrGamepad);
  55574. }
  55575. else {
  55576. return new BABYLON.GenericController(vrGamepad);
  55577. }
  55578. };
  55579. return PoseEnabledControllerHelper;
  55580. }());
  55581. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55582. var PoseEnabledController = /** @class */ (function (_super) {
  55583. __extends(PoseEnabledController, _super);
  55584. function PoseEnabledController(browserGamepad) {
  55585. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55586. _this.deviceScaleFactor = 1;
  55587. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55588. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55589. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55590. _this.position = BABYLON.Vector3.Zero();
  55591. _this.rotationQuaternion = new BABYLON.Quaternion();
  55592. _this.devicePosition = BABYLON.Vector3.Zero();
  55593. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55594. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55595. _this._calculatedRotation = new BABYLON.Quaternion();
  55596. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55597. return _this;
  55598. }
  55599. PoseEnabledController.prototype.update = function () {
  55600. _super.prototype.update.call(this);
  55601. var pose = this.browserGamepad.pose;
  55602. this.updateFromDevice(pose);
  55603. if (this._mesh) {
  55604. this._mesh.position.copyFrom(this._calculatedPosition);
  55605. if (this._mesh.rotationQuaternion) {
  55606. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55607. }
  55608. }
  55609. };
  55610. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55611. if (poseData) {
  55612. this.rawPose = poseData;
  55613. if (poseData.position) {
  55614. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55615. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55616. this.devicePosition.z *= -1;
  55617. }
  55618. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55619. this._calculatedPosition.addInPlace(this.position);
  55620. }
  55621. var pose = this.rawPose;
  55622. if (poseData.orientation && pose.orientation) {
  55623. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55624. if (this._mesh) {
  55625. if (this._mesh.getScene().useRightHandedSystem) {
  55626. this.deviceRotationQuaternion.z *= -1;
  55627. this.deviceRotationQuaternion.w *= -1;
  55628. }
  55629. else {
  55630. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55631. }
  55632. }
  55633. // if the camera is set, rotate to the camera's rotation
  55634. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55635. }
  55636. }
  55637. };
  55638. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55639. if (this._mesh) {
  55640. this._mesh.parent = null;
  55641. }
  55642. this._mesh = mesh;
  55643. if (this._poseControlledCamera) {
  55644. this._mesh.parent = this._poseControlledCamera;
  55645. }
  55646. if (!this._mesh.rotationQuaternion) {
  55647. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55648. }
  55649. };
  55650. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55651. this._poseControlledCamera = camera;
  55652. if (this._mesh) {
  55653. this._mesh.parent = this._poseControlledCamera;
  55654. }
  55655. };
  55656. PoseEnabledController.prototype.dispose = function () {
  55657. if (this._mesh) {
  55658. this._mesh.dispose();
  55659. }
  55660. this._mesh = null;
  55661. _super.prototype.dispose.call(this);
  55662. };
  55663. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55664. get: function () {
  55665. return this._mesh;
  55666. },
  55667. enumerable: true,
  55668. configurable: true
  55669. });
  55670. PoseEnabledController.prototype.getForwardRay = function (length) {
  55671. if (length === void 0) { length = 100; }
  55672. if (!this.mesh) {
  55673. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55674. }
  55675. var m = this.mesh.getWorldMatrix();
  55676. var origin = m.getTranslation();
  55677. var forward = new BABYLON.Vector3(0, 0, -1);
  55678. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55679. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55680. return new BABYLON.Ray(origin, direction, length);
  55681. };
  55682. return PoseEnabledController;
  55683. }(BABYLON.Gamepad));
  55684. BABYLON.PoseEnabledController = PoseEnabledController;
  55685. })(BABYLON || (BABYLON = {}));
  55686. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55687. var BABYLON;
  55688. (function (BABYLON) {
  55689. var WebVRController = /** @class */ (function (_super) {
  55690. __extends(WebVRController, _super);
  55691. function WebVRController(vrGamepad) {
  55692. var _this = _super.call(this, vrGamepad) || this;
  55693. // Observables
  55694. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55695. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55696. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55697. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55698. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55699. _this.pad = { x: 0, y: 0 };
  55700. // avoid GC, store state in a tmp object
  55701. _this._changes = {
  55702. pressChanged: false,
  55703. touchChanged: false,
  55704. valueChanged: false,
  55705. changed: false
  55706. };
  55707. _this._buttons = new Array(vrGamepad.buttons.length);
  55708. _this.hand = vrGamepad.hand;
  55709. return _this;
  55710. }
  55711. WebVRController.prototype.onButtonStateChange = function (callback) {
  55712. this._onButtonStateChange = callback;
  55713. };
  55714. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55715. get: function () {
  55716. return this._defaultModel;
  55717. },
  55718. enumerable: true,
  55719. configurable: true
  55720. });
  55721. WebVRController.prototype.update = function () {
  55722. _super.prototype.update.call(this);
  55723. for (var index = 0; index < this._buttons.length; index++) {
  55724. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55725. }
  55726. ;
  55727. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55728. this.pad.x = this.leftStick.x;
  55729. this.pad.y = this.leftStick.y;
  55730. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55731. }
  55732. };
  55733. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55734. if (!newState) {
  55735. newState = {
  55736. pressed: false,
  55737. touched: false,
  55738. value: 0
  55739. };
  55740. }
  55741. if (!currentState) {
  55742. this._buttons[buttonIndex] = {
  55743. pressed: newState.pressed,
  55744. touched: newState.touched,
  55745. value: newState.value
  55746. };
  55747. return;
  55748. }
  55749. this._checkChanges(newState, currentState);
  55750. if (this._changes.changed) {
  55751. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55752. this.handleButtonChange(buttonIndex, newState, this._changes);
  55753. }
  55754. this._buttons[buttonIndex].pressed = newState.pressed;
  55755. this._buttons[buttonIndex].touched = newState.touched;
  55756. // oculus triggers are never 0, thou not touched.
  55757. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55758. };
  55759. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55760. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55761. this._changes.touchChanged = newState.touched !== currentState.touched;
  55762. this._changes.valueChanged = newState.value !== currentState.value;
  55763. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55764. return this._changes;
  55765. };
  55766. WebVRController.prototype.dispose = function () {
  55767. _super.prototype.dispose.call(this);
  55768. this.onTriggerStateChangedObservable.clear();
  55769. this.onMainButtonStateChangedObservable.clear();
  55770. this.onSecondaryButtonStateChangedObservable.clear();
  55771. this.onPadStateChangedObservable.clear();
  55772. this.onPadValuesChangedObservable.clear();
  55773. };
  55774. return WebVRController;
  55775. }(BABYLON.PoseEnabledController));
  55776. BABYLON.WebVRController = WebVRController;
  55777. })(BABYLON || (BABYLON = {}));
  55778. //# sourceMappingURL=babylon.webVRController.js.map
  55779. var BABYLON;
  55780. (function (BABYLON) {
  55781. var OculusTouchController = /** @class */ (function (_super) {
  55782. __extends(OculusTouchController, _super);
  55783. function OculusTouchController(vrGamepad) {
  55784. var _this = _super.call(this, vrGamepad) || this;
  55785. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55786. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55787. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55788. return _this;
  55789. }
  55790. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55791. var _this = this;
  55792. var meshName;
  55793. // Hand
  55794. if (this.hand === 'left') {
  55795. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55796. }
  55797. else {
  55798. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55799. }
  55800. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55801. /*
  55802. Parent Mesh name: oculus_touch_left
  55803. - body
  55804. - trigger
  55805. - thumbstick
  55806. - grip
  55807. - button_y
  55808. - button_x
  55809. - button_enter
  55810. */
  55811. _this._defaultModel = newMeshes[1];
  55812. _this.attachToMesh(_this._defaultModel);
  55813. if (meshLoaded) {
  55814. meshLoaded(_this._defaultModel);
  55815. }
  55816. });
  55817. };
  55818. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55819. // helper getters for left and right hand.
  55820. get: function () {
  55821. if (this.hand === 'right') {
  55822. return this.onMainButtonStateChangedObservable;
  55823. }
  55824. else {
  55825. throw new Error('No A button on left hand');
  55826. }
  55827. },
  55828. enumerable: true,
  55829. configurable: true
  55830. });
  55831. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55832. get: function () {
  55833. if (this.hand === 'right') {
  55834. return this.onSecondaryButtonStateChangedObservable;
  55835. }
  55836. else {
  55837. throw new Error('No B button on left hand');
  55838. }
  55839. },
  55840. enumerable: true,
  55841. configurable: true
  55842. });
  55843. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55844. get: function () {
  55845. if (this.hand === 'left') {
  55846. return this.onMainButtonStateChangedObservable;
  55847. }
  55848. else {
  55849. throw new Error('No X button on right hand');
  55850. }
  55851. },
  55852. enumerable: true,
  55853. configurable: true
  55854. });
  55855. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  55856. get: function () {
  55857. if (this.hand === 'left') {
  55858. return this.onSecondaryButtonStateChangedObservable;
  55859. }
  55860. else {
  55861. throw new Error('No Y button on right hand');
  55862. }
  55863. },
  55864. enumerable: true,
  55865. configurable: true
  55866. });
  55867. /*
  55868. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  55869. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  55870. 2) secondary trigger (same)
  55871. 3) A (right) X (left), touch, pressed = value
  55872. 4) B / Y
  55873. 5) thumb rest
  55874. */
  55875. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55876. var notifyObject = state; //{ state: state, changes: changes };
  55877. var triggerDirection = this.hand === 'right' ? -1 : 1;
  55878. switch (buttonIdx) {
  55879. case 0:
  55880. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55881. return;
  55882. case 1:// index trigger
  55883. if (this._defaultModel) {
  55884. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  55885. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  55886. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  55887. }
  55888. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55889. return;
  55890. case 2:// secondary trigger
  55891. if (this._defaultModel) {
  55892. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  55893. }
  55894. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  55895. return;
  55896. case 3:
  55897. if (this._defaultModel) {
  55898. if (notifyObject.pressed) {
  55899. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  55900. }
  55901. else {
  55902. (this._defaultModel.getChildren()[1]).position.y = 0;
  55903. }
  55904. }
  55905. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55906. return;
  55907. case 4:
  55908. if (this._defaultModel) {
  55909. if (notifyObject.pressed) {
  55910. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55911. }
  55912. else {
  55913. (this._defaultModel.getChildren()[2]).position.y = 0;
  55914. }
  55915. }
  55916. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55917. return;
  55918. case 5:
  55919. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  55920. return;
  55921. }
  55922. };
  55923. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  55924. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  55925. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  55926. return OculusTouchController;
  55927. }(BABYLON.WebVRController));
  55928. BABYLON.OculusTouchController = OculusTouchController;
  55929. })(BABYLON || (BABYLON = {}));
  55930. //# sourceMappingURL=babylon.oculusTouchController.js.map
  55931. var BABYLON;
  55932. (function (BABYLON) {
  55933. var ViveController = /** @class */ (function (_super) {
  55934. __extends(ViveController, _super);
  55935. function ViveController(vrGamepad) {
  55936. var _this = _super.call(this, vrGamepad) || this;
  55937. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  55938. return _this;
  55939. }
  55940. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55941. var _this = this;
  55942. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  55943. /*
  55944. Parent Mesh name: ViveWand
  55945. - body
  55946. - r_gripper
  55947. - l_gripper
  55948. - menu_button
  55949. - system_button
  55950. - trackpad
  55951. - trigger
  55952. - LED
  55953. */
  55954. _this._defaultModel = newMeshes[1];
  55955. _this.attachToMesh(_this._defaultModel);
  55956. if (meshLoaded) {
  55957. meshLoaded(_this._defaultModel);
  55958. }
  55959. });
  55960. };
  55961. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  55962. get: function () {
  55963. return this.onMainButtonStateChangedObservable;
  55964. },
  55965. enumerable: true,
  55966. configurable: true
  55967. });
  55968. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  55969. get: function () {
  55970. return this.onMainButtonStateChangedObservable;
  55971. },
  55972. enumerable: true,
  55973. configurable: true
  55974. });
  55975. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  55976. get: function () {
  55977. return this.onSecondaryButtonStateChangedObservable;
  55978. },
  55979. enumerable: true,
  55980. configurable: true
  55981. });
  55982. /**
  55983. * Vive mapping:
  55984. * 0: touchpad
  55985. * 1: trigger
  55986. * 2: left AND right buttons
  55987. * 3: menu button
  55988. */
  55989. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55990. var notifyObject = state; //{ state: state, changes: changes };
  55991. switch (buttonIdx) {
  55992. case 0:
  55993. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55994. return;
  55995. case 1:// index trigger
  55996. if (this._defaultModel) {
  55997. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  55998. }
  55999. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56000. return;
  56001. case 2:// left AND right button
  56002. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56003. return;
  56004. case 3:
  56005. if (this._defaultModel) {
  56006. if (notifyObject.pressed) {
  56007. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56008. }
  56009. else {
  56010. (this._defaultModel.getChildren()[2]).position.y = 0;
  56011. }
  56012. }
  56013. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56014. return;
  56015. }
  56016. };
  56017. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  56018. ViveController.MODEL_FILENAME = 'wand.babylon';
  56019. return ViveController;
  56020. }(BABYLON.WebVRController));
  56021. BABYLON.ViveController = ViveController;
  56022. })(BABYLON || (BABYLON = {}));
  56023. //# sourceMappingURL=babylon.viveController.js.map
  56024. var BABYLON;
  56025. (function (BABYLON) {
  56026. var GenericController = /** @class */ (function (_super) {
  56027. __extends(GenericController, _super);
  56028. function GenericController(vrGamepad) {
  56029. return _super.call(this, vrGamepad) || this;
  56030. }
  56031. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56032. var _this = this;
  56033. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  56034. _this._defaultModel = newMeshes[1];
  56035. _this.attachToMesh(_this._defaultModel);
  56036. if (meshLoaded) {
  56037. meshLoaded(_this._defaultModel);
  56038. }
  56039. });
  56040. };
  56041. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56042. console.log("Button id: " + buttonIdx + "state: ");
  56043. console.dir(state);
  56044. };
  56045. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  56046. GenericController.MODEL_FILENAME = 'generic.babylon';
  56047. return GenericController;
  56048. }(BABYLON.WebVRController));
  56049. BABYLON.GenericController = GenericController;
  56050. })(BABYLON || (BABYLON = {}));
  56051. //# sourceMappingURL=babylon.genericController.js.map
  56052. var BABYLON;
  56053. (function (BABYLON) {
  56054. var LoadedMeshInfo = /** @class */ (function () {
  56055. function LoadedMeshInfo() {
  56056. this.buttonMeshes = {};
  56057. this.axisMeshes = {};
  56058. }
  56059. return LoadedMeshInfo;
  56060. }());
  56061. var WindowsMotionController = /** @class */ (function (_super) {
  56062. __extends(WindowsMotionController, _super);
  56063. function WindowsMotionController(vrGamepad) {
  56064. var _this = _super.call(this, vrGamepad) || this;
  56065. _this._mapping = {
  56066. // Semantic button names
  56067. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  56068. // A mapping of the button name to glTF model node name
  56069. // that should be transformed by button value.
  56070. buttonMeshNames: {
  56071. 'trigger': 'SELECT',
  56072. 'menu': 'MENU',
  56073. 'grip': 'GRASP',
  56074. 'thumbstick': 'THUMBSTICK_PRESS',
  56075. 'trackpad': 'TOUCHPAD_PRESS'
  56076. },
  56077. // This mapping is used to translate from the Motion Controller to Babylon semantics
  56078. buttonObservableNames: {
  56079. 'trigger': 'onTriggerStateChangedObservable',
  56080. 'menu': 'onSecondaryButtonStateChangedObservable',
  56081. 'grip': 'onMainButtonStateChangedObservable',
  56082. 'thumbstick': 'onPadStateChangedObservable',
  56083. 'trackpad': 'onTrackpadChangedObservable'
  56084. },
  56085. // A mapping of the axis name to glTF model node name
  56086. // that should be transformed by axis value.
  56087. // This array mirrors the browserGamepad.axes array, such that
  56088. // the mesh corresponding to axis 0 is in this array index 0.
  56089. axisMeshNames: [
  56090. 'THUMBSTICK_X',
  56091. 'THUMBSTICK_Y',
  56092. 'TOUCHPAD_TOUCH_X',
  56093. 'TOUCHPAD_TOUCH_Y'
  56094. ],
  56095. pointingPoseMeshName: 'POINTING_POSE'
  56096. };
  56097. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  56098. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  56099. _this._loadedMeshInfo = null;
  56100. return _this;
  56101. }
  56102. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  56103. get: function () {
  56104. return this.onTriggerStateChangedObservable;
  56105. },
  56106. enumerable: true,
  56107. configurable: true
  56108. });
  56109. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  56110. get: function () {
  56111. return this.onSecondaryButtonStateChangedObservable;
  56112. },
  56113. enumerable: true,
  56114. configurable: true
  56115. });
  56116. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  56117. get: function () {
  56118. return this.onMainButtonStateChangedObservable;
  56119. },
  56120. enumerable: true,
  56121. configurable: true
  56122. });
  56123. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56124. get: function () {
  56125. return this.onPadStateChangedObservable;
  56126. },
  56127. enumerable: true,
  56128. configurable: true
  56129. });
  56130. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  56131. get: function () {
  56132. return this.onTrackpadChangedObservable;
  56133. },
  56134. enumerable: true,
  56135. configurable: true
  56136. });
  56137. /**
  56138. * Called once per frame by the engine.
  56139. */
  56140. WindowsMotionController.prototype.update = function () {
  56141. _super.prototype.update.call(this);
  56142. // Only need to animate axes if there is a loaded mesh
  56143. if (this._loadedMeshInfo) {
  56144. if (this.browserGamepad.axes) {
  56145. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  56146. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  56147. }
  56148. }
  56149. }
  56150. };
  56151. /**
  56152. * Called once for each button that changed state since the last frame
  56153. * @param buttonIdx Which button index changed
  56154. * @param state New state of the button
  56155. * @param changes Which properties on the state changed since last frame
  56156. */
  56157. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56158. var buttonName = this._mapping.buttons[buttonIdx];
  56159. if (!buttonName) {
  56160. return;
  56161. }
  56162. // Only emit events for buttons that we know how to map from index to name
  56163. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  56164. if (observable) {
  56165. observable.notifyObservers(state);
  56166. }
  56167. this.lerpButtonTransform(buttonName, state.value);
  56168. };
  56169. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  56170. // If there is no loaded mesh, there is nothing to transform.
  56171. if (!this._loadedMeshInfo) {
  56172. return;
  56173. }
  56174. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  56175. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56176. return;
  56177. }
  56178. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  56179. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  56180. };
  56181. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  56182. if (!this._loadedMeshInfo) {
  56183. return;
  56184. }
  56185. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  56186. if (!meshInfo) {
  56187. return;
  56188. }
  56189. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56190. return;
  56191. }
  56192. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  56193. var lerpValue = axisValue * 0.5 + 0.5;
  56194. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  56195. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  56196. };
  56197. /**
  56198. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  56199. * @param scene scene in which to add meshes
  56200. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  56201. */
  56202. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  56203. var _this = this;
  56204. if (forceDefault === void 0) { forceDefault = false; }
  56205. var path;
  56206. var filename;
  56207. // Checking if GLB loader is present
  56208. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56209. // Determine the device specific folder based on the ID suffix
  56210. var device = 'default';
  56211. if (this.id && !forceDefault) {
  56212. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56213. device = ((match && match[0]) || device);
  56214. }
  56215. // Hand
  56216. if (this.hand === 'left') {
  56217. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56218. }
  56219. else {
  56220. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56221. }
  56222. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56223. }
  56224. else {
  56225. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56226. path = BABYLON.GenericController.MODEL_BASE_URL;
  56227. filename = BABYLON.GenericController.MODEL_FILENAME;
  56228. }
  56229. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56230. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56231. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56232. if (!_this._loadedMeshInfo) {
  56233. return;
  56234. }
  56235. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56236. _this.attachToMesh(_this._defaultModel);
  56237. if (meshLoaded) {
  56238. meshLoaded(_this._defaultModel);
  56239. }
  56240. }, null, function (scene, message) {
  56241. BABYLON.Tools.Log(message);
  56242. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56243. if (!forceDefault) {
  56244. _this.initControllerMesh(scene, meshLoaded, true);
  56245. }
  56246. });
  56247. };
  56248. /**
  56249. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56250. * can be transformed by button presses and axes values, based on this._mapping.
  56251. *
  56252. * @param scene scene in which the meshes exist
  56253. * @param meshes list of meshes that make up the controller model to process
  56254. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56255. */
  56256. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56257. var loadedMeshInfo = null;
  56258. // Create a new mesh to contain the glTF hierarchy
  56259. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56260. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56261. var childMesh = null;
  56262. for (var i = 0; i < meshes.length; i++) {
  56263. var mesh = meshes[i];
  56264. if (!mesh.parent) {
  56265. // Exclude controller meshes from picking results
  56266. mesh.isPickable = false;
  56267. // Handle root node, attach to the new parentMesh
  56268. childMesh = mesh;
  56269. break;
  56270. }
  56271. }
  56272. if (childMesh) {
  56273. childMesh.setParent(parentMesh);
  56274. // Create our mesh info. Note that this method will always return non-null.
  56275. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56276. }
  56277. else {
  56278. BABYLON.Tools.Warn('Could not find root node in model file.');
  56279. }
  56280. return loadedMeshInfo;
  56281. };
  56282. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56283. var loadedMeshInfo = new LoadedMeshInfo();
  56284. var i;
  56285. loadedMeshInfo.rootNode = rootNode;
  56286. // Reset the caches
  56287. loadedMeshInfo.buttonMeshes = {};
  56288. loadedMeshInfo.axisMeshes = {};
  56289. // Button Meshes
  56290. for (i = 0; i < this._mapping.buttons.length; i++) {
  56291. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56292. if (!buttonMeshName) {
  56293. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56294. continue;
  56295. }
  56296. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56297. if (!buttonMesh) {
  56298. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56299. continue;
  56300. }
  56301. var buttonMeshInfo = {
  56302. index: i,
  56303. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56304. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56305. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56306. };
  56307. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56308. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56309. }
  56310. else {
  56311. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56312. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56313. '(VALUE: ' + !!buttonMeshInfo.value +
  56314. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56315. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56316. ')');
  56317. }
  56318. }
  56319. // Axis Meshes
  56320. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56321. var axisMeshName = this._mapping.axisMeshNames[i];
  56322. if (!axisMeshName) {
  56323. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56324. continue;
  56325. }
  56326. var axisMesh = getChildByName(rootNode, axisMeshName);
  56327. if (!axisMesh) {
  56328. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56329. continue;
  56330. }
  56331. var axisMeshInfo = {
  56332. index: i,
  56333. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56334. min: getImmediateChildByName(axisMesh, 'MIN'),
  56335. max: getImmediateChildByName(axisMesh, 'MAX')
  56336. };
  56337. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56338. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56339. }
  56340. else {
  56341. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56342. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56343. '(VALUE: ' + !!axisMeshInfo.value +
  56344. ', MIN: ' + !!axisMeshInfo.min +
  56345. ', MAX:' + !!axisMeshInfo.max +
  56346. ')');
  56347. }
  56348. }
  56349. // Pointing Ray
  56350. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56351. if (!loadedMeshInfo.pointingPoseNode) {
  56352. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56353. }
  56354. return loadedMeshInfo;
  56355. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56356. function getChildByName(node, name) {
  56357. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56358. }
  56359. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56360. function getImmediateChildByName(node, name) {
  56361. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56362. }
  56363. };
  56364. WindowsMotionController.prototype.getForwardRay = function (length) {
  56365. if (length === void 0) { length = 100; }
  56366. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56367. return _super.prototype.getForwardRay.call(this, length);
  56368. }
  56369. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56370. var origin = m.getTranslation();
  56371. var forward = new BABYLON.Vector3(0, 0, -1);
  56372. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56373. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56374. return new BABYLON.Ray(origin, direction, length);
  56375. };
  56376. WindowsMotionController.prototype.dispose = function () {
  56377. _super.prototype.dispose.call(this);
  56378. this.onTrackpadChangedObservable.clear();
  56379. };
  56380. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56381. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56382. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56383. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56384. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56385. return WindowsMotionController;
  56386. }(BABYLON.WebVRController));
  56387. BABYLON.WindowsMotionController = WindowsMotionController;
  56388. })(BABYLON || (BABYLON = {}));
  56389. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56390. var BABYLON;
  56391. (function (BABYLON) {
  56392. var FollowCamera = /** @class */ (function (_super) {
  56393. __extends(FollowCamera, _super);
  56394. function FollowCamera(name, position, scene, lockedTarget) {
  56395. if (lockedTarget === void 0) { lockedTarget = null; }
  56396. var _this = _super.call(this, name, position, scene) || this;
  56397. _this.radius = 12;
  56398. _this.rotationOffset = 0;
  56399. _this.heightOffset = 4;
  56400. _this.cameraAcceleration = 0.05;
  56401. _this.maxCameraSpeed = 20;
  56402. _this.lockedTarget = lockedTarget;
  56403. return _this;
  56404. }
  56405. FollowCamera.prototype.getRadians = function (degrees) {
  56406. return degrees * Math.PI / 180;
  56407. };
  56408. FollowCamera.prototype.follow = function (cameraTarget) {
  56409. if (!cameraTarget)
  56410. return;
  56411. var yRotation;
  56412. if (cameraTarget.rotationQuaternion) {
  56413. var rotMatrix = new BABYLON.Matrix();
  56414. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56415. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56416. }
  56417. else {
  56418. yRotation = cameraTarget.rotation.y;
  56419. }
  56420. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56421. var targetPosition = cameraTarget.getAbsolutePosition();
  56422. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56423. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56424. var dx = targetX - this.position.x;
  56425. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56426. var dz = (targetZ) - this.position.z;
  56427. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56428. var vy = dy * this.cameraAcceleration;
  56429. var vz = dz * this.cameraAcceleration * 2;
  56430. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56431. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56432. }
  56433. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56434. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56435. }
  56436. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56437. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56438. }
  56439. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56440. this.setTarget(targetPosition);
  56441. };
  56442. FollowCamera.prototype._checkInputs = function () {
  56443. _super.prototype._checkInputs.call(this);
  56444. if (this.lockedTarget) {
  56445. this.follow(this.lockedTarget);
  56446. }
  56447. };
  56448. FollowCamera.prototype.getClassName = function () {
  56449. return "FollowCamera";
  56450. };
  56451. __decorate([
  56452. BABYLON.serialize()
  56453. ], FollowCamera.prototype, "radius", void 0);
  56454. __decorate([
  56455. BABYLON.serialize()
  56456. ], FollowCamera.prototype, "rotationOffset", void 0);
  56457. __decorate([
  56458. BABYLON.serialize()
  56459. ], FollowCamera.prototype, "heightOffset", void 0);
  56460. __decorate([
  56461. BABYLON.serialize()
  56462. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56463. __decorate([
  56464. BABYLON.serialize()
  56465. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56466. __decorate([
  56467. BABYLON.serializeAsMeshReference("lockedTargetId")
  56468. ], FollowCamera.prototype, "lockedTarget", void 0);
  56469. return FollowCamera;
  56470. }(BABYLON.TargetCamera));
  56471. BABYLON.FollowCamera = FollowCamera;
  56472. var ArcFollowCamera = /** @class */ (function (_super) {
  56473. __extends(ArcFollowCamera, _super);
  56474. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56475. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56476. _this.alpha = alpha;
  56477. _this.beta = beta;
  56478. _this.radius = radius;
  56479. _this.target = target;
  56480. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56481. _this.follow();
  56482. return _this;
  56483. }
  56484. ArcFollowCamera.prototype.follow = function () {
  56485. if (!this.target) {
  56486. return;
  56487. }
  56488. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56489. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56490. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56491. var targetPosition = this.target.getAbsolutePosition();
  56492. this.position = targetPosition.add(this._cartesianCoordinates);
  56493. this.setTarget(targetPosition);
  56494. };
  56495. ArcFollowCamera.prototype._checkInputs = function () {
  56496. _super.prototype._checkInputs.call(this);
  56497. this.follow();
  56498. };
  56499. ArcFollowCamera.prototype.getClassName = function () {
  56500. return "ArcFollowCamera";
  56501. };
  56502. return ArcFollowCamera;
  56503. }(BABYLON.TargetCamera));
  56504. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56505. })(BABYLON || (BABYLON = {}));
  56506. //# sourceMappingURL=babylon.followCamera.js.map
  56507. var BABYLON;
  56508. (function (BABYLON) {
  56509. // We're mainly based on the logic defined into the FreeCamera code
  56510. var UniversalCamera = /** @class */ (function (_super) {
  56511. __extends(UniversalCamera, _super);
  56512. //-- end properties for backward compatibility for inputs
  56513. function UniversalCamera(name, position, scene) {
  56514. var _this = _super.call(this, name, position, scene) || this;
  56515. _this.inputs.addGamepad();
  56516. return _this;
  56517. }
  56518. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56519. //-- Begin properties for backward compatibility for inputs
  56520. get: function () {
  56521. var gamepad = this.inputs.attached["gamepad"];
  56522. if (gamepad)
  56523. return gamepad.gamepadAngularSensibility;
  56524. return 0;
  56525. },
  56526. set: function (value) {
  56527. var gamepad = this.inputs.attached["gamepad"];
  56528. if (gamepad)
  56529. gamepad.gamepadAngularSensibility = value;
  56530. },
  56531. enumerable: true,
  56532. configurable: true
  56533. });
  56534. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56535. get: function () {
  56536. var gamepad = this.inputs.attached["gamepad"];
  56537. if (gamepad)
  56538. return gamepad.gamepadMoveSensibility;
  56539. return 0;
  56540. },
  56541. set: function (value) {
  56542. var gamepad = this.inputs.attached["gamepad"];
  56543. if (gamepad)
  56544. gamepad.gamepadMoveSensibility = value;
  56545. },
  56546. enumerable: true,
  56547. configurable: true
  56548. });
  56549. UniversalCamera.prototype.getClassName = function () {
  56550. return "UniversalCamera";
  56551. };
  56552. return UniversalCamera;
  56553. }(BABYLON.TouchCamera));
  56554. BABYLON.UniversalCamera = UniversalCamera;
  56555. })(BABYLON || (BABYLON = {}));
  56556. //# sourceMappingURL=babylon.universalCamera.js.map
  56557. var BABYLON;
  56558. (function (BABYLON) {
  56559. // We're mainly based on the logic defined into the FreeCamera code
  56560. var GamepadCamera = /** @class */ (function (_super) {
  56561. __extends(GamepadCamera, _super);
  56562. //-- end properties for backward compatibility for inputs
  56563. function GamepadCamera(name, position, scene) {
  56564. return _super.call(this, name, position, scene) || this;
  56565. }
  56566. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56567. //-- Begin properties for backward compatibility for inputs
  56568. get: function () {
  56569. var gamepad = this.inputs.attached["gamepad"];
  56570. if (gamepad)
  56571. return gamepad.gamepadAngularSensibility;
  56572. return 0;
  56573. },
  56574. set: function (value) {
  56575. var gamepad = this.inputs.attached["gamepad"];
  56576. if (gamepad)
  56577. gamepad.gamepadAngularSensibility = value;
  56578. },
  56579. enumerable: true,
  56580. configurable: true
  56581. });
  56582. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56583. get: function () {
  56584. var gamepad = this.inputs.attached["gamepad"];
  56585. if (gamepad)
  56586. return gamepad.gamepadMoveSensibility;
  56587. return 0;
  56588. },
  56589. set: function (value) {
  56590. var gamepad = this.inputs.attached["gamepad"];
  56591. if (gamepad)
  56592. gamepad.gamepadMoveSensibility = value;
  56593. },
  56594. enumerable: true,
  56595. configurable: true
  56596. });
  56597. GamepadCamera.prototype.getClassName = function () {
  56598. return "GamepadCamera";
  56599. };
  56600. return GamepadCamera;
  56601. }(BABYLON.UniversalCamera));
  56602. BABYLON.GamepadCamera = GamepadCamera;
  56603. })(BABYLON || (BABYLON = {}));
  56604. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56605. var BABYLON;
  56606. (function (BABYLON) {
  56607. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56608. function PostProcessRenderPipelineManager() {
  56609. this._renderPipelines = {};
  56610. }
  56611. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56612. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56613. };
  56614. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56615. if (unique === void 0) { unique = false; }
  56616. var renderPipeline = this._renderPipelines[renderPipelineName];
  56617. if (!renderPipeline) {
  56618. return;
  56619. }
  56620. renderPipeline._attachCameras(cameras, unique);
  56621. };
  56622. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56623. var renderPipeline = this._renderPipelines[renderPipelineName];
  56624. if (!renderPipeline) {
  56625. return;
  56626. }
  56627. renderPipeline._detachCameras(cameras);
  56628. };
  56629. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56630. var renderPipeline = this._renderPipelines[renderPipelineName];
  56631. if (!renderPipeline) {
  56632. return;
  56633. }
  56634. renderPipeline._enableEffect(renderEffectName, cameras);
  56635. };
  56636. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56637. var renderPipeline = this._renderPipelines[renderPipelineName];
  56638. if (!renderPipeline) {
  56639. return;
  56640. }
  56641. renderPipeline._disableEffect(renderEffectName, cameras);
  56642. };
  56643. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56644. var renderPipeline = this._renderPipelines[renderPipelineName];
  56645. if (!renderPipeline) {
  56646. return;
  56647. }
  56648. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56649. };
  56650. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56651. var renderPipeline = this._renderPipelines[renderPipelineName];
  56652. if (!renderPipeline) {
  56653. return;
  56654. }
  56655. renderPipeline._disableDisplayOnlyPass(cameras);
  56656. };
  56657. PostProcessRenderPipelineManager.prototype.update = function () {
  56658. for (var renderPipelineName in this._renderPipelines) {
  56659. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56660. var pipeline = this._renderPipelines[renderPipelineName];
  56661. if (!pipeline.isSupported) {
  56662. pipeline.dispose();
  56663. delete this._renderPipelines[renderPipelineName];
  56664. }
  56665. else {
  56666. pipeline._update();
  56667. }
  56668. }
  56669. }
  56670. };
  56671. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56672. for (var renderPipelineName in this._renderPipelines) {
  56673. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56674. var pipeline = this._renderPipelines[renderPipelineName];
  56675. pipeline._rebuild();
  56676. }
  56677. }
  56678. };
  56679. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56680. for (var renderPipelineName in this._renderPipelines) {
  56681. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56682. var pipeline = this._renderPipelines[renderPipelineName];
  56683. pipeline.dispose();
  56684. }
  56685. }
  56686. };
  56687. return PostProcessRenderPipelineManager;
  56688. }());
  56689. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56690. })(BABYLON || (BABYLON = {}));
  56691. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56692. var BABYLON;
  56693. (function (BABYLON) {
  56694. var PostProcessRenderPass = /** @class */ (function () {
  56695. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56696. this._refCount = 0;
  56697. this._name = name;
  56698. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56699. this.setRenderList(renderList);
  56700. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56701. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56702. this._scene = scene;
  56703. this._renderList = renderList;
  56704. }
  56705. // private
  56706. PostProcessRenderPass.prototype._incRefCount = function () {
  56707. if (this._refCount === 0) {
  56708. this._scene.customRenderTargets.push(this._renderTexture);
  56709. }
  56710. return ++this._refCount;
  56711. };
  56712. PostProcessRenderPass.prototype._decRefCount = function () {
  56713. this._refCount--;
  56714. if (this._refCount <= 0) {
  56715. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56716. }
  56717. return this._refCount;
  56718. };
  56719. PostProcessRenderPass.prototype._update = function () {
  56720. this.setRenderList(this._renderList);
  56721. };
  56722. // public
  56723. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56724. this._renderTexture.renderList = renderList;
  56725. };
  56726. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56727. return this._renderTexture;
  56728. };
  56729. return PostProcessRenderPass;
  56730. }());
  56731. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56732. })(BABYLON || (BABYLON = {}));
  56733. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56734. var BABYLON;
  56735. (function (BABYLON) {
  56736. var PostProcessRenderEffect = /** @class */ (function () {
  56737. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56738. this._engine = engine;
  56739. this._name = name;
  56740. this._singleInstance = singleInstance || true;
  56741. this._getPostProcess = getPostProcess;
  56742. this._cameras = {};
  56743. this._indicesForCamera = {};
  56744. this._postProcesses = {};
  56745. this._renderPasses = {};
  56746. this._renderEffectAsPasses = {};
  56747. }
  56748. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56749. get: function () {
  56750. for (var index in this._postProcesses) {
  56751. if (!this._postProcesses[index].isSupported) {
  56752. return false;
  56753. }
  56754. }
  56755. return true;
  56756. },
  56757. enumerable: true,
  56758. configurable: true
  56759. });
  56760. PostProcessRenderEffect.prototype._update = function () {
  56761. for (var renderPassName in this._renderPasses) {
  56762. this._renderPasses[renderPassName]._update();
  56763. }
  56764. };
  56765. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56766. this._renderPasses[renderPass._name] = renderPass;
  56767. this._linkParameters();
  56768. };
  56769. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56770. delete this._renderPasses[renderPass._name];
  56771. this._linkParameters();
  56772. };
  56773. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56774. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56775. this._linkParameters();
  56776. };
  56777. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56778. for (var renderPassName in this._renderPasses) {
  56779. if (renderPassName === passName) {
  56780. return this._renderPasses[passName];
  56781. }
  56782. }
  56783. return null;
  56784. };
  56785. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56786. this._renderPasses = {};
  56787. this._linkParameters();
  56788. };
  56789. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56790. var cameraKey;
  56791. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56792. if (!cams) {
  56793. return;
  56794. }
  56795. for (var i = 0; i < cams.length; i++) {
  56796. var camera = cams[i];
  56797. var cameraName = camera.name;
  56798. if (this._singleInstance) {
  56799. cameraKey = 0;
  56800. }
  56801. else {
  56802. cameraKey = cameraName;
  56803. }
  56804. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56805. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56806. if (!this._indicesForCamera[cameraName]) {
  56807. this._indicesForCamera[cameraName] = [];
  56808. }
  56809. this._indicesForCamera[cameraName].push(index);
  56810. if (!this._cameras[cameraName]) {
  56811. this._cameras[cameraName] = camera;
  56812. }
  56813. for (var passName in this._renderPasses) {
  56814. this._renderPasses[passName]._incRefCount();
  56815. }
  56816. }
  56817. this._linkParameters();
  56818. };
  56819. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56820. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56821. if (!cams) {
  56822. return;
  56823. }
  56824. for (var i = 0; i < cams.length; i++) {
  56825. var camera = cams[i];
  56826. var cameraName = camera.name;
  56827. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56828. if (this._cameras[cameraName]) {
  56829. //this._indicesForCamera.splice(index, 1);
  56830. this._cameras[cameraName] = null;
  56831. }
  56832. for (var passName in this._renderPasses) {
  56833. this._renderPasses[passName]._decRefCount();
  56834. }
  56835. }
  56836. };
  56837. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56838. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56839. if (!cams) {
  56840. return;
  56841. }
  56842. for (var i = 0; i < cams.length; i++) {
  56843. var camera = cams[i];
  56844. var cameraName = camera.name;
  56845. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56846. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56847. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  56848. }
  56849. }
  56850. for (var passName in this._renderPasses) {
  56851. this._renderPasses[passName]._incRefCount();
  56852. }
  56853. }
  56854. };
  56855. PostProcessRenderEffect.prototype._disable = function (cameras) {
  56856. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56857. if (!cams) {
  56858. return;
  56859. }
  56860. for (var i = 0; i < cams.length; i++) {
  56861. var camera = cams[i];
  56862. var cameraName = camera.Name;
  56863. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56864. for (var passName in this._renderPasses) {
  56865. this._renderPasses[passName]._decRefCount();
  56866. }
  56867. }
  56868. };
  56869. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  56870. if (this._singleInstance) {
  56871. return this._postProcesses[0];
  56872. }
  56873. else {
  56874. if (!camera) {
  56875. return null;
  56876. }
  56877. return this._postProcesses[camera.name];
  56878. }
  56879. };
  56880. PostProcessRenderEffect.prototype._linkParameters = function () {
  56881. var _this = this;
  56882. for (var index in this._postProcesses) {
  56883. if (this.applyParameters) {
  56884. this.applyParameters(this._postProcesses[index]);
  56885. }
  56886. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  56887. _this._linkTextures(effect);
  56888. });
  56889. }
  56890. };
  56891. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  56892. for (var renderPassName in this._renderPasses) {
  56893. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  56894. }
  56895. for (var renderEffectName in this._renderEffectAsPasses) {
  56896. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  56897. }
  56898. };
  56899. return PostProcessRenderEffect;
  56900. }());
  56901. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  56902. })(BABYLON || (BABYLON = {}));
  56903. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  56904. var BABYLON;
  56905. (function (BABYLON) {
  56906. var PostProcessRenderPipeline = /** @class */ (function () {
  56907. function PostProcessRenderPipeline(engine, name) {
  56908. this._engine = engine;
  56909. this._name = name;
  56910. this._renderEffects = {};
  56911. this._renderEffectsForIsolatedPass = new Array();
  56912. this._cameras = [];
  56913. }
  56914. PostProcessRenderPipeline.prototype.getClassName = function () {
  56915. return "PostProcessRenderPipeline";
  56916. };
  56917. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  56918. get: function () {
  56919. for (var renderEffectName in this._renderEffects) {
  56920. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56921. if (!this._renderEffects[renderEffectName].isSupported) {
  56922. return false;
  56923. }
  56924. }
  56925. }
  56926. return true;
  56927. },
  56928. enumerable: true,
  56929. configurable: true
  56930. });
  56931. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  56932. this._renderEffects[renderEffect._name] = renderEffect;
  56933. };
  56934. // private
  56935. PostProcessRenderPipeline.prototype._rebuild = function () {
  56936. };
  56937. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  56938. var renderEffects = this._renderEffects[renderEffectName];
  56939. if (!renderEffects) {
  56940. return;
  56941. }
  56942. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56943. };
  56944. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  56945. var renderEffects = this._renderEffects[renderEffectName];
  56946. if (!renderEffects) {
  56947. return;
  56948. }
  56949. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56950. };
  56951. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  56952. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56953. if (!cams) {
  56954. return;
  56955. }
  56956. var indicesToDelete = [];
  56957. var i;
  56958. for (i = 0; i < cams.length; i++) {
  56959. var camera = cams[i];
  56960. var cameraName = camera.name;
  56961. if (this._cameras.indexOf(camera) === -1) {
  56962. this._cameras[cameraName] = camera;
  56963. }
  56964. else if (unique) {
  56965. indicesToDelete.push(i);
  56966. }
  56967. }
  56968. for (i = 0; i < indicesToDelete.length; i++) {
  56969. cameras.splice(indicesToDelete[i], 1);
  56970. }
  56971. for (var renderEffectName in this._renderEffects) {
  56972. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56973. this._renderEffects[renderEffectName]._attachCameras(cams);
  56974. }
  56975. }
  56976. };
  56977. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  56978. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56979. if (!cams) {
  56980. return;
  56981. }
  56982. for (var renderEffectName in this._renderEffects) {
  56983. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56984. this._renderEffects[renderEffectName]._detachCameras(cams);
  56985. }
  56986. }
  56987. for (var i = 0; i < cams.length; i++) {
  56988. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  56989. }
  56990. };
  56991. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  56992. var _this = this;
  56993. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56994. if (!cams) {
  56995. return;
  56996. }
  56997. var pass = null;
  56998. var renderEffectName;
  56999. for (renderEffectName in this._renderEffects) {
  57000. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57001. pass = this._renderEffects[renderEffectName].getPass(passName);
  57002. if (pass != null) {
  57003. break;
  57004. }
  57005. }
  57006. }
  57007. if (pass === null) {
  57008. return;
  57009. }
  57010. for (renderEffectName in this._renderEffects) {
  57011. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57012. this._renderEffects[renderEffectName]._disable(cams);
  57013. }
  57014. }
  57015. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  57016. for (var i = 0; i < cams.length; i++) {
  57017. var camera = cams[i];
  57018. var cameraName = camera.name;
  57019. 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); });
  57020. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  57021. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  57022. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  57023. }
  57024. };
  57025. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  57026. var _this = this;
  57027. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57028. if (!cams) {
  57029. return;
  57030. }
  57031. for (var i = 0; i < cams.length; i++) {
  57032. var camera = cams[i];
  57033. var cameraName = camera.name;
  57034. 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); });
  57035. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  57036. }
  57037. for (var renderEffectName in this._renderEffects) {
  57038. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57039. this._renderEffects[renderEffectName]._enable(cams);
  57040. }
  57041. }
  57042. };
  57043. PostProcessRenderPipeline.prototype._update = function () {
  57044. for (var renderEffectName in this._renderEffects) {
  57045. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57046. this._renderEffects[renderEffectName]._update();
  57047. }
  57048. }
  57049. for (var i = 0; i < this._cameras.length; i++) {
  57050. var cameraName = this._cameras[i].name;
  57051. if (this._renderEffectsForIsolatedPass[cameraName]) {
  57052. this._renderEffectsForIsolatedPass[cameraName]._update();
  57053. }
  57054. }
  57055. };
  57056. PostProcessRenderPipeline.prototype._reset = function () {
  57057. this._renderEffects = {};
  57058. this._renderEffectsForIsolatedPass = new Array();
  57059. };
  57060. PostProcessRenderPipeline.prototype.dispose = function () {
  57061. // Must be implemented by children
  57062. };
  57063. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  57064. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  57065. __decorate([
  57066. BABYLON.serialize()
  57067. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  57068. return PostProcessRenderPipeline;
  57069. }());
  57070. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  57071. })(BABYLON || (BABYLON = {}));
  57072. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  57073. var BABYLON;
  57074. (function (BABYLON) {
  57075. var DepthRenderer = /** @class */ (function () {
  57076. function DepthRenderer(scene, type) {
  57077. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  57078. var _this = this;
  57079. this._scene = scene;
  57080. var engine = scene.getEngine();
  57081. // Render target
  57082. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  57083. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57084. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57085. this._depthMap.refreshRate = 1;
  57086. this._depthMap.renderParticles = false;
  57087. this._depthMap.renderList = null;
  57088. // set default depth value to 1.0 (far away)
  57089. this._depthMap.onClearObservable.add(function (engine) {
  57090. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  57091. });
  57092. // Custom render function
  57093. var renderSubMesh = function (subMesh) {
  57094. var mesh = subMesh.getRenderingMesh();
  57095. var scene = _this._scene;
  57096. var engine = scene.getEngine();
  57097. var material = subMesh.getMaterial();
  57098. if (!material) {
  57099. return;
  57100. }
  57101. // Culling
  57102. engine.setState(material.backFaceCulling);
  57103. // Managing instances
  57104. var batch = mesh._getInstancesRenderList(subMesh._id);
  57105. if (batch.mustReturn) {
  57106. return;
  57107. }
  57108. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57109. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  57110. engine.enableEffect(_this._effect);
  57111. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57112. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57113. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  57114. // Alpha test
  57115. if (material && material.needAlphaTesting()) {
  57116. var alphaTexture = material.getAlphaTestTexture();
  57117. if (alphaTexture) {
  57118. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57119. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57120. }
  57121. }
  57122. // Bones
  57123. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57124. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57125. }
  57126. // Draw
  57127. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57128. }
  57129. };
  57130. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57131. var index;
  57132. if (depthOnlySubMeshes.length) {
  57133. engine.setColorWrite(false);
  57134. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57135. renderSubMesh(depthOnlySubMeshes.data[index]);
  57136. }
  57137. engine.setColorWrite(true);
  57138. }
  57139. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57140. renderSubMesh(opaqueSubMeshes.data[index]);
  57141. }
  57142. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57143. renderSubMesh(alphaTestSubMeshes.data[index]);
  57144. }
  57145. };
  57146. }
  57147. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  57148. var material = subMesh.getMaterial();
  57149. if (material.disableDepthWrite) {
  57150. return false;
  57151. }
  57152. var defines = [];
  57153. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57154. var mesh = subMesh.getMesh();
  57155. // Alpha test
  57156. if (material && material.needAlphaTesting()) {
  57157. defines.push("#define ALPHATEST");
  57158. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57159. attribs.push(BABYLON.VertexBuffer.UVKind);
  57160. defines.push("#define UV1");
  57161. }
  57162. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57163. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57164. defines.push("#define UV2");
  57165. }
  57166. }
  57167. // Bones
  57168. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57169. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57170. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57171. if (mesh.numBoneInfluencers > 4) {
  57172. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57173. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57174. }
  57175. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57176. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  57177. }
  57178. else {
  57179. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57180. }
  57181. // Instances
  57182. if (useInstances) {
  57183. defines.push("#define INSTANCES");
  57184. attribs.push("world0");
  57185. attribs.push("world1");
  57186. attribs.push("world2");
  57187. attribs.push("world3");
  57188. }
  57189. // Get correct effect
  57190. var join = defines.join("\n");
  57191. if (this._cachedDefines !== join) {
  57192. this._cachedDefines = join;
  57193. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  57194. }
  57195. return this._effect.isReady();
  57196. };
  57197. DepthRenderer.prototype.getDepthMap = function () {
  57198. return this._depthMap;
  57199. };
  57200. // Methods
  57201. DepthRenderer.prototype.dispose = function () {
  57202. this._depthMap.dispose();
  57203. };
  57204. return DepthRenderer;
  57205. }());
  57206. BABYLON.DepthRenderer = DepthRenderer;
  57207. })(BABYLON || (BABYLON = {}));
  57208. //# sourceMappingURL=babylon.depthRenderer.js.map
  57209. var BABYLON;
  57210. (function (BABYLON) {
  57211. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57212. __extends(SSAORenderingPipeline, _super);
  57213. /**
  57214. * @constructor
  57215. * @param {string} name - The rendering pipeline name
  57216. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57217. * @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 }
  57218. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57219. */
  57220. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57221. var _this = _super.call(this, scene.getEngine(), name) || this;
  57222. // Members
  57223. /**
  57224. * The PassPostProcess id in the pipeline that contains the original scene color
  57225. * @type {string}
  57226. */
  57227. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57228. /**
  57229. * The SSAO PostProcess id in the pipeline
  57230. * @type {string}
  57231. */
  57232. _this.SSAORenderEffect = "SSAORenderEffect";
  57233. /**
  57234. * The horizontal blur PostProcess id in the pipeline
  57235. * @type {string}
  57236. */
  57237. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57238. /**
  57239. * The vertical blur PostProcess id in the pipeline
  57240. * @type {string}
  57241. */
  57242. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57243. /**
  57244. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57245. * @type {string}
  57246. */
  57247. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57248. /**
  57249. * The output strength of the SSAO post-process. Default value is 1.0.
  57250. * @type {number}
  57251. */
  57252. _this.totalStrength = 1.0;
  57253. /**
  57254. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57255. * @type {number}
  57256. */
  57257. _this.radius = 0.0001;
  57258. /**
  57259. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57260. * Must not be equal to fallOff and superior to fallOff.
  57261. * Default value is 0.975
  57262. * @type {number}
  57263. */
  57264. _this.area = 0.0075;
  57265. /**
  57266. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57267. * Must not be equal to area and inferior to area.
  57268. * Default value is 0.0
  57269. * @type {number}
  57270. */
  57271. _this.fallOff = 0.000001;
  57272. /**
  57273. * The base color of the SSAO post-process
  57274. * The final result is "base + ssao" between [0, 1]
  57275. * @type {number}
  57276. */
  57277. _this.base = 0.5;
  57278. _this._firstUpdate = true;
  57279. _this._scene = scene;
  57280. // Set up assets
  57281. _this._createRandomTexture();
  57282. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57283. var ssaoRatio = ratio.ssaoRatio || ratio;
  57284. var combineRatio = ratio.combineRatio || ratio;
  57285. _this._ratio = {
  57286. ssaoRatio: ssaoRatio,
  57287. combineRatio: combineRatio
  57288. };
  57289. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57290. _this._createSSAOPostProcess(ssaoRatio);
  57291. _this._createBlurPostProcess(ssaoRatio);
  57292. _this._createSSAOCombinePostProcess(combineRatio);
  57293. // Set up pipeline
  57294. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57295. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57296. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57297. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57298. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57299. // Finish
  57300. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57301. if (cameras)
  57302. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57303. return _this;
  57304. }
  57305. // Public Methods
  57306. /**
  57307. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57308. */
  57309. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57310. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57311. for (var i = 0; i < this._scene.cameras.length; i++) {
  57312. var camera = this._scene.cameras[i];
  57313. this._originalColorPostProcess.dispose(camera);
  57314. this._ssaoPostProcess.dispose(camera);
  57315. this._blurHPostProcess.dispose(camera);
  57316. this._blurVPostProcess.dispose(camera);
  57317. this._ssaoCombinePostProcess.dispose(camera);
  57318. }
  57319. this._randomTexture.dispose();
  57320. if (disableDepthRender)
  57321. this._scene.disableDepthRenderer();
  57322. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57323. _super.prototype.dispose.call(this);
  57324. };
  57325. // Private Methods
  57326. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57327. var _this = this;
  57328. /*
  57329. var samplerOffsets = [
  57330. -8.0, -6.0, -4.0, -2.0,
  57331. 0.0,
  57332. 2.0, 4.0, 6.0, 8.0
  57333. ];
  57334. */
  57335. var samplerOffsets = new Array();
  57336. for (var i = -8; i < 8; i++) {
  57337. samplerOffsets.push(i * 2);
  57338. }
  57339. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  57340. this._blurHPostProcess.onApply = function (effect) {
  57341. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57342. effect.setTexture("depthSampler", _this._depthTexture);
  57343. if (_this._firstUpdate) {
  57344. effect.setArray("samplerOffsets", samplerOffsets);
  57345. }
  57346. };
  57347. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  57348. this._blurVPostProcess.onApply = function (effect) {
  57349. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57350. effect.setTexture("depthSampler", _this._depthTexture);
  57351. if (_this._firstUpdate) {
  57352. effect.setArray("samplerOffsets", samplerOffsets);
  57353. _this._firstUpdate = false;
  57354. }
  57355. };
  57356. };
  57357. SSAORenderingPipeline.prototype._rebuild = function () {
  57358. this._firstUpdate = true;
  57359. _super.prototype._rebuild.call(this);
  57360. };
  57361. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57362. var _this = this;
  57363. var numSamples = 16;
  57364. var sampleSphere = [
  57365. 0.5381, 0.1856, -0.4319,
  57366. 0.1379, 0.2486, 0.4430,
  57367. 0.3371, 0.5679, -0.0057,
  57368. -0.6999, -0.0451, -0.0019,
  57369. 0.0689, -0.1598, -0.8547,
  57370. 0.0560, 0.0069, -0.1843,
  57371. -0.0146, 0.1402, 0.0762,
  57372. 0.0100, -0.1924, -0.0344,
  57373. -0.3577, -0.5301, -0.4358,
  57374. -0.3169, 0.1063, 0.0158,
  57375. 0.0103, -0.5869, 0.0046,
  57376. -0.0897, -0.4940, 0.3287,
  57377. 0.7119, -0.0154, -0.0918,
  57378. -0.0533, 0.0596, -0.5411,
  57379. 0.0352, -0.0631, 0.5460,
  57380. -0.4776, 0.2847, -0.0271
  57381. ];
  57382. var samplesFactor = 1.0 / numSamples;
  57383. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57384. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57385. "area", "fallOff", "base", "range", "viewport"
  57386. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57387. this._ssaoPostProcess.onApply = function (effect) {
  57388. if (_this._firstUpdate) {
  57389. effect.setArray3("sampleSphere", sampleSphere);
  57390. effect.setFloat("samplesFactor", samplesFactor);
  57391. effect.setFloat("randTextureTiles", 4.0);
  57392. }
  57393. effect.setFloat("totalStrength", _this.totalStrength);
  57394. effect.setFloat("radius", _this.radius);
  57395. effect.setFloat("area", _this.area);
  57396. effect.setFloat("fallOff", _this.fallOff);
  57397. effect.setFloat("base", _this.base);
  57398. effect.setTexture("textureSampler", _this._depthTexture);
  57399. effect.setTexture("randomSampler", _this._randomTexture);
  57400. };
  57401. };
  57402. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57403. var _this = this;
  57404. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57405. this._ssaoCombinePostProcess.onApply = function (effect) {
  57406. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57407. };
  57408. };
  57409. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57410. var size = 512;
  57411. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57412. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57413. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57414. var context = this._randomTexture.getContext();
  57415. var rand = function (min, max) {
  57416. return Math.random() * (max - min) + min;
  57417. };
  57418. var randVector = BABYLON.Vector3.Zero();
  57419. for (var x = 0; x < size; x++) {
  57420. for (var y = 0; y < size; y++) {
  57421. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57422. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57423. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57424. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57425. context.fillRect(x, y, 1, 1);
  57426. }
  57427. }
  57428. this._randomTexture.update(false);
  57429. };
  57430. __decorate([
  57431. BABYLON.serialize()
  57432. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57433. __decorate([
  57434. BABYLON.serialize()
  57435. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57436. __decorate([
  57437. BABYLON.serialize()
  57438. ], SSAORenderingPipeline.prototype, "area", void 0);
  57439. __decorate([
  57440. BABYLON.serialize()
  57441. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57442. __decorate([
  57443. BABYLON.serialize()
  57444. ], SSAORenderingPipeline.prototype, "base", void 0);
  57445. __decorate([
  57446. BABYLON.serialize()
  57447. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57448. return SSAORenderingPipeline;
  57449. }(BABYLON.PostProcessRenderPipeline));
  57450. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57451. })(BABYLON || (BABYLON = {}));
  57452. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57453. var BABYLON;
  57454. (function (BABYLON) {
  57455. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57456. __extends(SSAO2RenderingPipeline, _super);
  57457. /**
  57458. * @constructor
  57459. * @param {string} name - The rendering pipeline name
  57460. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57461. * @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 }
  57462. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57463. */
  57464. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57465. var _this = _super.call(this, scene.getEngine(), name) || this;
  57466. // Members
  57467. /**
  57468. * The PassPostProcess id in the pipeline that contains the original scene color
  57469. * @type {string}
  57470. */
  57471. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57472. /**
  57473. * The SSAO PostProcess id in the pipeline
  57474. * @type {string}
  57475. */
  57476. _this.SSAORenderEffect = "SSAORenderEffect";
  57477. /**
  57478. * The horizontal blur PostProcess id in the pipeline
  57479. * @type {string}
  57480. */
  57481. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57482. /**
  57483. * The vertical blur PostProcess id in the pipeline
  57484. * @type {string}
  57485. */
  57486. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57487. /**
  57488. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57489. * @type {string}
  57490. */
  57491. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57492. /**
  57493. * The output strength of the SSAO post-process. Default value is 1.0.
  57494. * @type {number}
  57495. */
  57496. _this.totalStrength = 1.0;
  57497. /**
  57498. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57499. * @type {number}
  57500. */
  57501. _this.maxZ = 100.0;
  57502. /**
  57503. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57504. * @type {number}
  57505. */
  57506. _this.minZAspect = 0.2;
  57507. /**
  57508. * Number of samples used for the SSAO calculations. Default value is 8
  57509. * @type {number}
  57510. */
  57511. _this._samples = 8;
  57512. /**
  57513. * Are we using bilateral blur ?
  57514. * @type {boolean}
  57515. */
  57516. _this._expensiveBlur = true;
  57517. /**
  57518. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57519. * @type {number}
  57520. */
  57521. _this.radius = 2.0;
  57522. /**
  57523. * The base color of the SSAO post-process
  57524. * The final result is "base + ssao" between [0, 1]
  57525. * @type {number}
  57526. */
  57527. _this.base = 0.1;
  57528. _this._firstUpdate = true;
  57529. _this._scene = scene;
  57530. if (!_this.isSupported) {
  57531. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57532. return _this;
  57533. }
  57534. var ssaoRatio = ratio.ssaoRatio || ratio;
  57535. var blurRatio = ratio.blurRatio || ratio;
  57536. _this._ratio = {
  57537. ssaoRatio: ssaoRatio,
  57538. blurRatio: blurRatio
  57539. };
  57540. // Set up assets
  57541. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57542. _this._createRandomTexture();
  57543. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57544. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57545. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57546. _this._createSSAOPostProcess(1.0);
  57547. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57548. _this._createSSAOCombinePostProcess(blurRatio);
  57549. // Set up pipeline
  57550. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57551. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57552. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57554. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57555. // Finish
  57556. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57557. if (cameras)
  57558. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57559. return _this;
  57560. }
  57561. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57562. get: function () {
  57563. return this._samples;
  57564. },
  57565. set: function (n) {
  57566. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57567. this._samples = n;
  57568. this._sampleSphere = this._generateHemisphere();
  57569. this._firstUpdate = true;
  57570. },
  57571. enumerable: true,
  57572. configurable: true
  57573. });
  57574. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57575. get: function () {
  57576. return this._expensiveBlur;
  57577. },
  57578. set: function (b) {
  57579. 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"]);
  57580. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57581. this._expensiveBlur = b;
  57582. this._firstUpdate = true;
  57583. },
  57584. enumerable: true,
  57585. configurable: true
  57586. });
  57587. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57588. /**
  57589. * Support test.
  57590. * @type {boolean}
  57591. */
  57592. get: function () {
  57593. var engine = BABYLON.Engine.LastCreatedEngine;
  57594. if (!engine) {
  57595. return false;
  57596. }
  57597. return engine.getCaps().drawBuffersExtension;
  57598. },
  57599. enumerable: true,
  57600. configurable: true
  57601. });
  57602. // Public Methods
  57603. /**
  57604. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57605. */
  57606. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57607. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57608. for (var i = 0; i < this._scene.cameras.length; i++) {
  57609. var camera = this._scene.cameras[i];
  57610. this._originalColorPostProcess.dispose(camera);
  57611. this._ssaoPostProcess.dispose(camera);
  57612. this._blurHPostProcess.dispose(camera);
  57613. this._blurVPostProcess.dispose(camera);
  57614. this._ssaoCombinePostProcess.dispose(camera);
  57615. }
  57616. this._randomTexture.dispose();
  57617. if (disableGeometryBufferRenderer)
  57618. this._scene.disableGeometryBufferRenderer();
  57619. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57620. _super.prototype.dispose.call(this);
  57621. };
  57622. // Private Methods
  57623. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57624. var _this = this;
  57625. this._samplerOffsets = [];
  57626. var expensive = this.expensiveBlur;
  57627. for (var i = -8; i < 8; i++) {
  57628. this._samplerOffsets.push(i * 2 + 0.5);
  57629. }
  57630. 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");
  57631. this._blurHPostProcess.onApply = function (effect) {
  57632. if (!_this._scene.activeCamera) {
  57633. return;
  57634. }
  57635. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57636. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57637. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57638. effect.setFloat("radius", _this.radius);
  57639. effect.setTexture("depthSampler", _this._depthTexture);
  57640. if (_this._firstUpdate) {
  57641. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57642. }
  57643. };
  57644. 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");
  57645. this._blurVPostProcess.onApply = function (effect) {
  57646. if (!_this._scene.activeCamera) {
  57647. return;
  57648. }
  57649. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57650. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57651. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57652. effect.setFloat("radius", _this.radius);
  57653. effect.setTexture("depthSampler", _this._depthTexture);
  57654. if (_this._firstUpdate) {
  57655. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57656. _this._firstUpdate = false;
  57657. }
  57658. };
  57659. };
  57660. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57661. this._firstUpdate = true;
  57662. _super.prototype._rebuild.call(this);
  57663. };
  57664. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57665. var numSamples = this.samples;
  57666. var result = [];
  57667. var vector, scale;
  57668. var rand = function (min, max) {
  57669. return Math.random() * (max - min) + min;
  57670. };
  57671. var i = 0;
  57672. while (i < numSamples) {
  57673. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57674. vector.normalize();
  57675. scale = i / numSamples;
  57676. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57677. vector.scaleInPlace(scale);
  57678. result.push(vector.x, vector.y, vector.z);
  57679. i++;
  57680. }
  57681. return result;
  57682. };
  57683. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57684. var _this = this;
  57685. var numSamples = this.samples;
  57686. this._sampleSphere = this._generateHemisphere();
  57687. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57688. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57689. "base", "range", "projection", "near", "far", "texelSize",
  57690. "xViewport", "yViewport", "maxZ", "minZAspect"
  57691. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57692. this._ssaoPostProcess.onApply = function (effect) {
  57693. if (_this._firstUpdate) {
  57694. effect.setArray3("sampleSphere", _this._sampleSphere);
  57695. effect.setFloat("randTextureTiles", 4.0);
  57696. }
  57697. if (!_this._scene.activeCamera) {
  57698. return;
  57699. }
  57700. effect.setFloat("samplesFactor", 1 / _this.samples);
  57701. effect.setFloat("totalStrength", _this.totalStrength);
  57702. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57703. effect.setFloat("radius", _this.radius);
  57704. effect.setFloat("maxZ", _this.maxZ);
  57705. effect.setFloat("minZAspect", _this.minZAspect);
  57706. effect.setFloat("base", _this.base);
  57707. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57708. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57709. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57710. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57711. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57712. effect.setTexture("textureSampler", _this._depthTexture);
  57713. effect.setTexture("normalSampler", _this._normalTexture);
  57714. effect.setTexture("randomSampler", _this._randomTexture);
  57715. };
  57716. };
  57717. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57718. var _this = this;
  57719. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57720. this._ssaoCombinePostProcess.onApply = function (effect) {
  57721. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57722. };
  57723. };
  57724. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57725. var size = 512;
  57726. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57727. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57728. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57729. var context = this._randomTexture.getContext();
  57730. var rand = function (min, max) {
  57731. return Math.random() * (max - min) + min;
  57732. };
  57733. var randVector = BABYLON.Vector3.Zero();
  57734. for (var x = 0; x < size; x++) {
  57735. for (var y = 0; y < size; y++) {
  57736. randVector.x = rand(0.0, 1.0);
  57737. randVector.y = rand(0.0, 1.0);
  57738. randVector.z = 0.0;
  57739. randVector.normalize();
  57740. randVector.scaleInPlace(255);
  57741. randVector.x = Math.floor(randVector.x);
  57742. randVector.y = Math.floor(randVector.y);
  57743. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57744. context.fillRect(x, y, 1, 1);
  57745. }
  57746. }
  57747. this._randomTexture.update(false);
  57748. };
  57749. __decorate([
  57750. BABYLON.serialize()
  57751. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57752. __decorate([
  57753. BABYLON.serialize()
  57754. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57755. __decorate([
  57756. BABYLON.serialize()
  57757. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57758. __decorate([
  57759. BABYLON.serialize("samples")
  57760. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57761. __decorate([
  57762. BABYLON.serialize("expensiveBlur")
  57763. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57764. __decorate([
  57765. BABYLON.serialize()
  57766. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57767. __decorate([
  57768. BABYLON.serialize()
  57769. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57770. __decorate([
  57771. BABYLON.serialize()
  57772. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57773. return SSAO2RenderingPipeline;
  57774. }(BABYLON.PostProcessRenderPipeline));
  57775. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57776. })(BABYLON || (BABYLON = {}));
  57777. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57778. // BABYLON.JS Chromatic Aberration GLSL Shader
  57779. // Author: Olivier Guyot
  57780. // Separates very slightly R, G and B colors on the edges of the screen
  57781. // Inspired by Francois Tarlier & Martins Upitis
  57782. var BABYLON;
  57783. (function (BABYLON) {
  57784. var LensRenderingPipeline = /** @class */ (function (_super) {
  57785. __extends(LensRenderingPipeline, _super);
  57786. /**
  57787. * @constructor
  57788. *
  57789. * Effect parameters are as follow:
  57790. * {
  57791. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57792. * edge_blur: number; // from 0 to x (1 for realism)
  57793. * distortion: number; // from 0 to x (1 for realism)
  57794. * grain_amount: number; // from 0 to 1
  57795. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57796. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57797. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57798. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57799. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57800. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57801. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57802. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57803. * }
  57804. * Note: if an effect parameter is unset, effect is disabled
  57805. *
  57806. * @param {string} name - The rendering pipeline name
  57807. * @param {object} parameters - An object containing all parameters (see above)
  57808. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57809. * @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)
  57810. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57811. */
  57812. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57813. if (ratio === void 0) { ratio = 1.0; }
  57814. var _this = _super.call(this, scene.getEngine(), name) || this;
  57815. // Lens effects can be of the following:
  57816. // - chromatic aberration (slight shift of RGB colors)
  57817. // - blur on the edge of the lens
  57818. // - lens distortion
  57819. // - depth-of-field blur & highlights enhancing
  57820. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57821. // - grain effect (noise or custom texture)
  57822. // Two additional texture samplers are needed:
  57823. // - depth map (for depth-of-field)
  57824. // - grain texture
  57825. /**
  57826. * The chromatic aberration PostProcess id in the pipeline
  57827. * @type {string}
  57828. */
  57829. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57830. /**
  57831. * The highlights enhancing PostProcess id in the pipeline
  57832. * @type {string}
  57833. */
  57834. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57835. /**
  57836. * The depth-of-field PostProcess id in the pipeline
  57837. * @type {string}
  57838. */
  57839. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57840. _this._scene = scene;
  57841. // Fetch texture samplers
  57842. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57843. if (parameters.grain_texture) {
  57844. _this._grainTexture = parameters.grain_texture;
  57845. }
  57846. else {
  57847. _this._createGrainTexture();
  57848. }
  57849. // save parameters
  57850. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  57851. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  57852. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  57853. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  57854. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  57855. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  57856. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  57857. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  57858. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  57859. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  57860. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  57861. // Create effects
  57862. _this._createChromaticAberrationPostProcess(ratio);
  57863. _this._createHighlightsPostProcess(ratio);
  57864. _this._createDepthOfFieldPostProcess(ratio / 4);
  57865. // Set up pipeline
  57866. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  57867. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  57868. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  57869. if (_this._highlightsGain === -1) {
  57870. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  57871. }
  57872. // Finish
  57873. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57874. if (cameras) {
  57875. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57876. }
  57877. return _this;
  57878. }
  57879. // public methods (self explanatory)
  57880. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  57881. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  57882. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  57883. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  57884. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  57885. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  57886. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  57887. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  57888. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  57889. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  57890. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  57891. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  57892. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  57893. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  57894. };
  57895. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  57896. this._highlightsPostProcess.updateEffect();
  57897. };
  57898. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  57899. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  57900. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  57901. this._highlightsGain = amount;
  57902. };
  57903. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  57904. if (this._highlightsGain === -1) {
  57905. this._highlightsGain = 1.0;
  57906. }
  57907. this._highlightsThreshold = amount;
  57908. };
  57909. LensRenderingPipeline.prototype.disableHighlights = function () {
  57910. this._highlightsGain = -1;
  57911. };
  57912. /**
  57913. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  57914. */
  57915. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57916. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57917. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57918. this._chromaticAberrationPostProcess = null;
  57919. this._highlightsPostProcess = null;
  57920. this._depthOfFieldPostProcess = null;
  57921. this._grainTexture.dispose();
  57922. if (disableDepthRender)
  57923. this._scene.disableDepthRenderer();
  57924. };
  57925. // colors shifting and distortion
  57926. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  57927. var _this = this;
  57928. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  57929. [], // samplers
  57930. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57931. this._chromaticAberrationPostProcess.onApply = function (effect) {
  57932. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  57933. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57934. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57935. };
  57936. };
  57937. // highlights enhancing
  57938. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  57939. var _this = this;
  57940. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  57941. [], // samplers
  57942. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  57943. this._highlightsPostProcess.onApply = function (effect) {
  57944. effect.setFloat('gain', _this._highlightsGain);
  57945. effect.setFloat('threshold', _this._highlightsThreshold);
  57946. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  57947. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57948. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57949. };
  57950. };
  57951. // colors shifting and distortion
  57952. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  57953. var _this = this;
  57954. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  57955. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  57956. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  57957. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57958. this._depthOfFieldPostProcess.onApply = function (effect) {
  57959. effect.setTexture("depthSampler", _this._depthTexture);
  57960. effect.setTexture("grainSampler", _this._grainTexture);
  57961. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  57962. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  57963. effect.setFloat('grain_amount', _this._grainAmount);
  57964. effect.setBool('blur_noise', _this._blurNoise);
  57965. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57966. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57967. effect.setFloat('distortion', _this._distortion);
  57968. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  57969. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  57970. effect.setFloat('aperture', _this._dofAperture);
  57971. effect.setFloat('darken', _this._dofDarken);
  57972. effect.setFloat('edge_blur', _this._edgeBlur);
  57973. effect.setBool('highlights', (_this._highlightsGain !== -1));
  57974. if (_this._scene.activeCamera) {
  57975. effect.setFloat('near', _this._scene.activeCamera.minZ);
  57976. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  57977. }
  57978. };
  57979. };
  57980. // creates a black and white random noise texture, 512x512
  57981. LensRenderingPipeline.prototype._createGrainTexture = function () {
  57982. var size = 512;
  57983. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57984. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57985. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57986. var context = this._grainTexture.getContext();
  57987. var rand = function (min, max) {
  57988. return Math.random() * (max - min) + min;
  57989. };
  57990. var value;
  57991. for (var x = 0; x < size; x++) {
  57992. for (var y = 0; y < size; y++) {
  57993. value = Math.floor(rand(0.42, 0.58) * 255);
  57994. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  57995. context.fillRect(x, y, 1, 1);
  57996. }
  57997. }
  57998. this._grainTexture.update(false);
  57999. };
  58000. return LensRenderingPipeline;
  58001. }(BABYLON.PostProcessRenderPipeline));
  58002. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  58003. })(BABYLON || (BABYLON = {}));
  58004. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  58005. var BABYLON;
  58006. (function (BABYLON) {
  58007. var StandardRenderingPipeline = /** @class */ (function (_super) {
  58008. __extends(StandardRenderingPipeline, _super);
  58009. /**
  58010. * @constructor
  58011. * @param {string} name - The rendering pipeline name
  58012. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58013. * @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)
  58014. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58015. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58016. */
  58017. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58018. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58019. var _this = _super.call(this, scene.getEngine(), name) || this;
  58020. _this.downSampleX4PostProcess = null;
  58021. _this.brightPassPostProcess = null;
  58022. _this.blurHPostProcesses = [];
  58023. _this.blurVPostProcesses = [];
  58024. _this.textureAdderPostProcess = null;
  58025. _this.volumetricLightPostProcess = null;
  58026. _this.volumetricLightSmoothXPostProcess = null;
  58027. _this.volumetricLightSmoothYPostProcess = null;
  58028. _this.volumetricLightMergePostProces = null;
  58029. _this.volumetricLightFinalPostProcess = null;
  58030. _this.luminancePostProcess = null;
  58031. _this.luminanceDownSamplePostProcesses = [];
  58032. _this.hdrPostProcess = null;
  58033. _this.textureAdderFinalPostProcess = null;
  58034. _this.lensFlareFinalPostProcess = null;
  58035. _this.hdrFinalPostProcess = null;
  58036. _this.lensFlarePostProcess = null;
  58037. _this.lensFlareComposePostProcess = null;
  58038. _this.motionBlurPostProcess = null;
  58039. _this.depthOfFieldPostProcess = null;
  58040. // Values
  58041. _this.brightThreshold = 1.0;
  58042. _this.blurWidth = 512.0;
  58043. _this.horizontalBlur = false;
  58044. _this.exposure = 1.0;
  58045. _this.lensTexture = null;
  58046. _this.volumetricLightCoefficient = 0.2;
  58047. _this.volumetricLightPower = 4.0;
  58048. _this.volumetricLightBlurScale = 64.0;
  58049. _this.sourceLight = null;
  58050. _this.hdrMinimumLuminance = 1.0;
  58051. _this.hdrDecreaseRate = 0.5;
  58052. _this.hdrIncreaseRate = 0.5;
  58053. _this.lensColorTexture = null;
  58054. _this.lensFlareStrength = 20.0;
  58055. _this.lensFlareGhostDispersal = 1.4;
  58056. _this.lensFlareHaloWidth = 0.7;
  58057. _this.lensFlareDistortionStrength = 16.0;
  58058. _this.lensStarTexture = null;
  58059. _this.lensFlareDirtTexture = null;
  58060. _this.depthOfFieldDistance = 10.0;
  58061. _this.depthOfFieldBlurWidth = 64.0;
  58062. _this.motionStrength = 1.0;
  58063. // IAnimatable
  58064. _this.animations = [];
  58065. _this._currentDepthOfFieldSource = null;
  58066. _this._hdrCurrentLuminance = 1.0;
  58067. // Getters and setters
  58068. _this._bloomEnabled = true;
  58069. _this._depthOfFieldEnabled = false;
  58070. _this._vlsEnabled = false;
  58071. _this._lensFlareEnabled = false;
  58072. _this._hdrEnabled = false;
  58073. _this._motionBlurEnabled = false;
  58074. _this._motionBlurSamples = 64.0;
  58075. _this._volumetricLightStepsCount = 50.0;
  58076. _this._cameras = cameras || [];
  58077. // Initialize
  58078. _this._scene = scene;
  58079. _this._basePostProcess = originalPostProcess;
  58080. _this._ratio = ratio;
  58081. // Misc
  58082. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58083. // Finish
  58084. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58085. _this._buildPipeline();
  58086. return _this;
  58087. }
  58088. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  58089. get: function () {
  58090. return this._bloomEnabled;
  58091. },
  58092. set: function (enabled) {
  58093. if (this._bloomEnabled === enabled) {
  58094. return;
  58095. }
  58096. this._bloomEnabled = enabled;
  58097. this._buildPipeline();
  58098. },
  58099. enumerable: true,
  58100. configurable: true
  58101. });
  58102. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  58103. get: function () {
  58104. return this._depthOfFieldEnabled;
  58105. },
  58106. set: function (enabled) {
  58107. if (this._depthOfFieldEnabled === enabled) {
  58108. return;
  58109. }
  58110. this._depthOfFieldEnabled = enabled;
  58111. this._buildPipeline();
  58112. },
  58113. enumerable: true,
  58114. configurable: true
  58115. });
  58116. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  58117. get: function () {
  58118. return this._lensFlareEnabled;
  58119. },
  58120. set: function (enabled) {
  58121. if (this._lensFlareEnabled === enabled) {
  58122. return;
  58123. }
  58124. this._lensFlareEnabled = enabled;
  58125. this._buildPipeline();
  58126. },
  58127. enumerable: true,
  58128. configurable: true
  58129. });
  58130. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58131. get: function () {
  58132. return this._hdrEnabled;
  58133. },
  58134. set: function (enabled) {
  58135. if (this._hdrEnabled === enabled) {
  58136. return;
  58137. }
  58138. this._hdrEnabled = enabled;
  58139. this._buildPipeline();
  58140. },
  58141. enumerable: true,
  58142. configurable: true
  58143. });
  58144. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58145. get: function () {
  58146. return this._vlsEnabled;
  58147. },
  58148. set: function (enabled) {
  58149. if (this._vlsEnabled === enabled) {
  58150. return;
  58151. }
  58152. if (enabled) {
  58153. var geometry = this._scene.enableGeometryBufferRenderer();
  58154. if (!geometry) {
  58155. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58156. return;
  58157. }
  58158. }
  58159. this._vlsEnabled = enabled;
  58160. this._buildPipeline();
  58161. },
  58162. enumerable: true,
  58163. configurable: true
  58164. });
  58165. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  58166. get: function () {
  58167. return this._motionBlurEnabled;
  58168. },
  58169. set: function (enabled) {
  58170. if (this._motionBlurEnabled === enabled) {
  58171. return;
  58172. }
  58173. this._motionBlurEnabled = enabled;
  58174. this._buildPipeline();
  58175. },
  58176. enumerable: true,
  58177. configurable: true
  58178. });
  58179. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  58180. get: function () {
  58181. return this._volumetricLightStepsCount;
  58182. },
  58183. set: function (count) {
  58184. if (this.volumetricLightPostProcess) {
  58185. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  58186. }
  58187. this._volumetricLightStepsCount = count;
  58188. },
  58189. enumerable: true,
  58190. configurable: true
  58191. });
  58192. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  58193. get: function () {
  58194. return this._motionBlurSamples;
  58195. },
  58196. set: function (samples) {
  58197. if (this.motionBlurPostProcess) {
  58198. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  58199. }
  58200. this._motionBlurSamples = samples;
  58201. },
  58202. enumerable: true,
  58203. configurable: true
  58204. });
  58205. StandardRenderingPipeline.prototype._buildPipeline = function () {
  58206. var _this = this;
  58207. var ratio = this._ratio;
  58208. var scene = this._scene;
  58209. this._disposePostProcesses();
  58210. this._reset();
  58211. // Create pass post-process
  58212. if (!this._basePostProcess) {
  58213. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58214. this.originalPostProcess.onApply = function (effect) {
  58215. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58216. };
  58217. }
  58218. else {
  58219. this.originalPostProcess = this._basePostProcess;
  58220. }
  58221. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58222. this._currentDepthOfFieldSource = this.originalPostProcess;
  58223. if (this._vlsEnabled) {
  58224. // Create volumetric light
  58225. this._createVolumetricLightPostProcess(scene, ratio);
  58226. // Create volumetric light final post-process
  58227. 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);
  58228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58229. }
  58230. if (this._bloomEnabled) {
  58231. // Create down sample X4 post-process
  58232. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58233. // Create bright pass post-process
  58234. this._createBrightPassPostProcess(scene, ratio / 2);
  58235. // Create gaussian blur post-processes (down sampling blurs)
  58236. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58237. // Create texture adder post-process
  58238. this._createTextureAdderPostProcess(scene, ratio);
  58239. // Create depth-of-field source post-process
  58240. 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);
  58241. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58242. }
  58243. if (this._lensFlareEnabled) {
  58244. // Create lens flare post-process
  58245. this._createLensFlarePostProcess(scene, ratio);
  58246. // Create depth-of-field source post-process post lens-flare and disable it now
  58247. 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);
  58248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58249. }
  58250. if (this._hdrEnabled) {
  58251. // Create luminance
  58252. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58253. // Create HDR
  58254. this._createHdrPostProcess(scene, ratio);
  58255. // Create depth-of-field source post-process post hdr and disable it now
  58256. 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);
  58257. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58258. }
  58259. if (this._depthOfFieldEnabled) {
  58260. // Create gaussian blur used by depth-of-field
  58261. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58262. // Create depth-of-field post-process
  58263. this._createDepthOfFieldPostProcess(scene, ratio);
  58264. }
  58265. if (this._motionBlurEnabled) {
  58266. // Create motion blur post-process
  58267. this._createMotionBlurPostProcess(scene, ratio);
  58268. }
  58269. if (this._cameras !== null) {
  58270. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58271. }
  58272. };
  58273. // Down Sample X4 Post-Processs
  58274. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58275. var _this = this;
  58276. var downSampleX4Offsets = new Array(32);
  58277. 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);
  58278. this.downSampleX4PostProcess.onApply = function (effect) {
  58279. var id = 0;
  58280. var width = _this.downSampleX4PostProcess.width;
  58281. var height = _this.downSampleX4PostProcess.height;
  58282. for (var i = -2; i < 2; i++) {
  58283. for (var j = -2; j < 2; j++) {
  58284. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58285. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58286. id += 2;
  58287. }
  58288. }
  58289. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58290. };
  58291. // Add to pipeline
  58292. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58293. };
  58294. // Brightpass Post-Process
  58295. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58296. var _this = this;
  58297. var brightOffsets = new Array(8);
  58298. 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);
  58299. this.brightPassPostProcess.onApply = function (effect) {
  58300. var sU = (1.0 / _this.brightPassPostProcess.width);
  58301. var sV = (1.0 / _this.brightPassPostProcess.height);
  58302. brightOffsets[0] = -0.5 * sU;
  58303. brightOffsets[1] = 0.5 * sV;
  58304. brightOffsets[2] = 0.5 * sU;
  58305. brightOffsets[3] = 0.5 * sV;
  58306. brightOffsets[4] = -0.5 * sU;
  58307. brightOffsets[5] = -0.5 * sV;
  58308. brightOffsets[6] = 0.5 * sU;
  58309. brightOffsets[7] = -0.5 * sV;
  58310. effect.setArray2("dsOffsets", brightOffsets);
  58311. effect.setFloat("brightThreshold", _this.brightThreshold);
  58312. };
  58313. // Add to pipeline
  58314. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58315. };
  58316. // Create blur H&V post-processes
  58317. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58318. var _this = this;
  58319. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58320. var engine = scene.getEngine();
  58321. 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);
  58322. 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);
  58323. blurX.onActivateObservable.add(function () {
  58324. var dw = blurX.width / engine.getRenderWidth();
  58325. blurX.kernel = _this[blurWidthKey] * dw;
  58326. });
  58327. blurY.onActivateObservable.add(function () {
  58328. var dw = blurY.height / engine.getRenderHeight();
  58329. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58330. });
  58331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58332. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58333. this.blurHPostProcesses.push(blurX);
  58334. this.blurVPostProcesses.push(blurY);
  58335. };
  58336. // Create texture adder post-process
  58337. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58338. var _this = this;
  58339. 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);
  58340. this.textureAdderPostProcess.onApply = function (effect) {
  58341. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58342. effect.setTexture("lensSampler", _this.lensTexture);
  58343. effect.setFloat("exposure", _this.exposure);
  58344. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58345. };
  58346. // Add to pipeline
  58347. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58348. };
  58349. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58350. var _this = this;
  58351. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58352. geometryRenderer.enablePosition = true;
  58353. var geometry = geometryRenderer.getGBuffer();
  58354. // Base post-process
  58355. 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));
  58356. var depthValues = BABYLON.Vector2.Zero();
  58357. this.volumetricLightPostProcess.onApply = function (effect) {
  58358. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58359. var generator = _this.sourceLight.getShadowGenerator();
  58360. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58361. effect.setTexture("positionSampler", geometry.textures[2]);
  58362. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58363. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58364. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58365. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58366. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58367. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58368. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58369. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58370. effect.setVector2("depthValues", depthValues);
  58371. }
  58372. };
  58373. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58374. // Smooth
  58375. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58376. // Merge
  58377. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58378. this.volumetricLightMergePostProces.onApply = function (effect) {
  58379. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58380. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58381. };
  58382. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58383. };
  58384. // Create luminance
  58385. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58386. var _this = this;
  58387. // Create luminance
  58388. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58389. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58390. var offsets = [];
  58391. this.luminancePostProcess.onApply = function (effect) {
  58392. var sU = (1.0 / _this.luminancePostProcess.width);
  58393. var sV = (1.0 / _this.luminancePostProcess.height);
  58394. offsets[0] = -0.5 * sU;
  58395. offsets[1] = 0.5 * sV;
  58396. offsets[2] = 0.5 * sU;
  58397. offsets[3] = 0.5 * sV;
  58398. offsets[4] = -0.5 * sU;
  58399. offsets[5] = -0.5 * sV;
  58400. offsets[6] = 0.5 * sU;
  58401. offsets[7] = -0.5 * sV;
  58402. effect.setArray2("lumOffsets", offsets);
  58403. };
  58404. // Add to pipeline
  58405. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58406. // Create down sample luminance
  58407. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58408. var size = Math.pow(3, i);
  58409. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58410. if (i === 0) {
  58411. defines += "#define FINAL_DOWN_SAMPLER";
  58412. }
  58413. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58414. this.luminanceDownSamplePostProcesses.push(postProcess);
  58415. }
  58416. // Create callbacks and add effects
  58417. var lastLuminance = this.luminancePostProcess;
  58418. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58419. var downSampleOffsets = new Array(18);
  58420. pp.onApply = function (effect) {
  58421. if (!lastLuminance) {
  58422. return;
  58423. }
  58424. var id = 0;
  58425. for (var x = -1; x < 2; x++) {
  58426. for (var y = -1; y < 2; y++) {
  58427. downSampleOffsets[id] = x / lastLuminance.width;
  58428. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58429. id += 2;
  58430. }
  58431. }
  58432. effect.setArray2("dsOffsets", downSampleOffsets);
  58433. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58434. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58435. lastLuminance = _this.luminancePostProcess;
  58436. }
  58437. else {
  58438. lastLuminance = pp;
  58439. }
  58440. };
  58441. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58442. pp.onAfterRender = function (effect) {
  58443. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58444. 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);
  58445. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58446. };
  58447. }
  58448. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58449. });
  58450. };
  58451. // Create HDR post-process
  58452. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58453. var _this = this;
  58454. 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);
  58455. var outputLiminance = 1;
  58456. var time = 0;
  58457. var lastTime = 0;
  58458. this.hdrPostProcess.onApply = function (effect) {
  58459. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58460. time += scene.getEngine().getDeltaTime();
  58461. if (outputLiminance < 0) {
  58462. outputLiminance = _this._hdrCurrentLuminance;
  58463. }
  58464. else {
  58465. var dt = (lastTime - time) / 1000.0;
  58466. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58467. outputLiminance += _this.hdrDecreaseRate * dt;
  58468. }
  58469. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58470. outputLiminance -= _this.hdrIncreaseRate * dt;
  58471. }
  58472. else {
  58473. outputLiminance = _this._hdrCurrentLuminance;
  58474. }
  58475. }
  58476. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58477. effect.setFloat("averageLuminance", outputLiminance);
  58478. lastTime = time;
  58479. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58480. };
  58481. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58482. };
  58483. // Create lens flare post-process
  58484. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58485. var _this = this;
  58486. 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);
  58487. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58488. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58489. 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);
  58490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58491. var resolution = new BABYLON.Vector2(0, 0);
  58492. // Lens flare
  58493. this.lensFlarePostProcess.onApply = function (effect) {
  58494. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58495. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58496. effect.setFloat("strength", _this.lensFlareStrength);
  58497. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58498. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58499. // Shift
  58500. resolution.x = _this.lensFlarePostProcess.width;
  58501. resolution.y = _this.lensFlarePostProcess.height;
  58502. effect.setVector2("resolution", resolution);
  58503. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58504. };
  58505. // Compose
  58506. 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);
  58507. 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);
  58508. this.lensFlareComposePostProcess.onApply = function (effect) {
  58509. if (!_this._scene.activeCamera) {
  58510. return;
  58511. }
  58512. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58513. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58514. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58515. // Lens start rotation matrix
  58516. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58517. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58518. 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));
  58519. camRot *= 4.0;
  58520. 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);
  58521. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58522. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58523. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58524. };
  58525. };
  58526. // Create depth-of-field post-process
  58527. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58528. var _this = this;
  58529. 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);
  58530. this.depthOfFieldPostProcess.onApply = function (effect) {
  58531. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58532. effect.setTexture("depthSampler", _this._getDepthTexture());
  58533. effect.setFloat("distance", _this.depthOfFieldDistance);
  58534. };
  58535. // Add to pipeline
  58536. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58537. };
  58538. // Create motion blur post-process
  58539. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58540. var _this = this;
  58541. 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);
  58542. var motionScale = 0;
  58543. var prevViewProjection = BABYLON.Matrix.Identity();
  58544. var invViewProjection = BABYLON.Matrix.Identity();
  58545. var viewProjection = BABYLON.Matrix.Identity();
  58546. var screenSize = BABYLON.Vector2.Zero();
  58547. this.motionBlurPostProcess.onApply = function (effect) {
  58548. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58549. viewProjection.invertToRef(invViewProjection);
  58550. effect.setMatrix("inverseViewProjection", invViewProjection);
  58551. effect.setMatrix("prevViewProjection", prevViewProjection);
  58552. prevViewProjection = viewProjection;
  58553. screenSize.x = _this.motionBlurPostProcess.width;
  58554. screenSize.y = _this.motionBlurPostProcess.height;
  58555. effect.setVector2("screenSize", screenSize);
  58556. motionScale = scene.getEngine().getFps() / 60.0;
  58557. effect.setFloat("motionScale", motionScale);
  58558. effect.setFloat("motionStrength", _this.motionStrength);
  58559. effect.setTexture("depthSampler", _this._getDepthTexture());
  58560. };
  58561. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58562. };
  58563. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58564. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58565. var renderer = this._scene.enableGeometryBufferRenderer();
  58566. return renderer.getGBuffer().textures[0];
  58567. }
  58568. return this._scene.enableDepthRenderer().getDepthMap();
  58569. };
  58570. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58571. for (var i = 0; i < this._cameras.length; i++) {
  58572. var camera = this._cameras[i];
  58573. if (this.originalPostProcess) {
  58574. this.originalPostProcess.dispose(camera);
  58575. }
  58576. if (this.downSampleX4PostProcess) {
  58577. this.downSampleX4PostProcess.dispose(camera);
  58578. }
  58579. if (this.brightPassPostProcess) {
  58580. this.brightPassPostProcess.dispose(camera);
  58581. }
  58582. if (this.textureAdderPostProcess) {
  58583. this.textureAdderPostProcess.dispose(camera);
  58584. }
  58585. if (this.textureAdderFinalPostProcess) {
  58586. this.textureAdderFinalPostProcess.dispose(camera);
  58587. }
  58588. if (this.volumetricLightPostProcess) {
  58589. this.volumetricLightPostProcess.dispose(camera);
  58590. }
  58591. if (this.volumetricLightSmoothXPostProcess) {
  58592. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58593. }
  58594. if (this.volumetricLightSmoothYPostProcess) {
  58595. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58596. }
  58597. if (this.volumetricLightMergePostProces) {
  58598. this.volumetricLightMergePostProces.dispose(camera);
  58599. }
  58600. if (this.volumetricLightFinalPostProcess) {
  58601. this.volumetricLightFinalPostProcess.dispose(camera);
  58602. }
  58603. if (this.lensFlarePostProcess) {
  58604. this.lensFlarePostProcess.dispose(camera);
  58605. }
  58606. if (this.lensFlareComposePostProcess) {
  58607. this.lensFlareComposePostProcess.dispose(camera);
  58608. }
  58609. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58610. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58611. }
  58612. if (this.luminancePostProcess) {
  58613. this.luminancePostProcess.dispose(camera);
  58614. }
  58615. if (this.hdrPostProcess) {
  58616. this.hdrPostProcess.dispose(camera);
  58617. }
  58618. if (this.hdrFinalPostProcess) {
  58619. this.hdrFinalPostProcess.dispose(camera);
  58620. }
  58621. if (this.depthOfFieldPostProcess) {
  58622. this.depthOfFieldPostProcess.dispose(camera);
  58623. }
  58624. if (this.motionBlurPostProcess) {
  58625. this.motionBlurPostProcess.dispose(camera);
  58626. }
  58627. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58628. this.blurHPostProcesses[j].dispose(camera);
  58629. }
  58630. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58631. this.blurVPostProcesses[j].dispose(camera);
  58632. }
  58633. }
  58634. this.originalPostProcess = null;
  58635. this.downSampleX4PostProcess = null;
  58636. this.brightPassPostProcess = null;
  58637. this.textureAdderPostProcess = null;
  58638. this.textureAdderFinalPostProcess = null;
  58639. this.volumetricLightPostProcess = null;
  58640. this.volumetricLightSmoothXPostProcess = null;
  58641. this.volumetricLightSmoothYPostProcess = null;
  58642. this.volumetricLightMergePostProces = null;
  58643. this.volumetricLightFinalPostProcess = null;
  58644. this.lensFlarePostProcess = null;
  58645. this.lensFlareComposePostProcess = null;
  58646. this.luminancePostProcess = null;
  58647. this.hdrPostProcess = null;
  58648. this.hdrFinalPostProcess = null;
  58649. this.depthOfFieldPostProcess = null;
  58650. this.motionBlurPostProcess = null;
  58651. this.luminanceDownSamplePostProcesses = [];
  58652. this.blurHPostProcesses = [];
  58653. this.blurVPostProcesses = [];
  58654. };
  58655. // Dispose
  58656. StandardRenderingPipeline.prototype.dispose = function () {
  58657. this._disposePostProcesses();
  58658. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58659. _super.prototype.dispose.call(this);
  58660. };
  58661. // Serialize rendering pipeline
  58662. StandardRenderingPipeline.prototype.serialize = function () {
  58663. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58664. serializationObject.customType = "StandardRenderingPipeline";
  58665. return serializationObject;
  58666. };
  58667. /**
  58668. * Static members
  58669. */
  58670. // Parse serialized pipeline
  58671. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58672. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58673. };
  58674. // Luminance steps
  58675. StandardRenderingPipeline.LuminanceSteps = 6;
  58676. __decorate([
  58677. BABYLON.serialize()
  58678. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58679. __decorate([
  58680. BABYLON.serialize()
  58681. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58682. __decorate([
  58683. BABYLON.serialize()
  58684. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58685. __decorate([
  58686. BABYLON.serialize()
  58687. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58688. __decorate([
  58689. BABYLON.serializeAsTexture("lensTexture")
  58690. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58691. __decorate([
  58692. BABYLON.serialize()
  58693. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58694. __decorate([
  58695. BABYLON.serialize()
  58696. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58697. __decorate([
  58698. BABYLON.serialize()
  58699. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58700. __decorate([
  58701. BABYLON.serialize()
  58702. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58703. __decorate([
  58704. BABYLON.serialize()
  58705. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58706. __decorate([
  58707. BABYLON.serialize()
  58708. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58709. __decorate([
  58710. BABYLON.serializeAsTexture("lensColorTexture")
  58711. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58712. __decorate([
  58713. BABYLON.serialize()
  58714. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58715. __decorate([
  58716. BABYLON.serialize()
  58717. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58718. __decorate([
  58719. BABYLON.serialize()
  58720. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58721. __decorate([
  58722. BABYLON.serialize()
  58723. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58724. __decorate([
  58725. BABYLON.serializeAsTexture("lensStarTexture")
  58726. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58727. __decorate([
  58728. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58729. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58730. __decorate([
  58731. BABYLON.serialize()
  58732. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58733. __decorate([
  58734. BABYLON.serialize()
  58735. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58736. __decorate([
  58737. BABYLON.serialize()
  58738. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58739. __decorate([
  58740. BABYLON.serialize()
  58741. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58742. __decorate([
  58743. BABYLON.serialize()
  58744. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58745. __decorate([
  58746. BABYLON.serialize()
  58747. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58748. __decorate([
  58749. BABYLON.serialize()
  58750. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58751. __decorate([
  58752. BABYLON.serialize()
  58753. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58754. __decorate([
  58755. BABYLON.serialize()
  58756. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58757. __decorate([
  58758. BABYLON.serialize()
  58759. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58760. __decorate([
  58761. BABYLON.serialize()
  58762. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58763. return StandardRenderingPipeline;
  58764. }(BABYLON.PostProcessRenderPipeline));
  58765. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58766. })(BABYLON || (BABYLON = {}));
  58767. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58768. var BABYLON;
  58769. (function (BABYLON) {
  58770. var FxaaPostProcess = /** @class */ (function (_super) {
  58771. __extends(FxaaPostProcess, _super);
  58772. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58773. if (camera === void 0) { camera = null; }
  58774. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58775. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58776. _this.onApplyObservable.add(function (effect) {
  58777. var texelSize = _this.texelSize;
  58778. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58779. });
  58780. return _this;
  58781. }
  58782. return FxaaPostProcess;
  58783. }(BABYLON.PostProcess));
  58784. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58785. })(BABYLON || (BABYLON = {}));
  58786. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58787. var BABYLON;
  58788. (function (BABYLON) {
  58789. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58790. __extends(DefaultRenderingPipeline, _super);
  58791. /**
  58792. * @constructor
  58793. * @param {string} name - The rendering pipeline name
  58794. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58795. * @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)
  58796. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58797. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58798. */
  58799. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58800. if (automaticBuild === void 0) { automaticBuild = true; }
  58801. var _this = _super.call(this, scene.getEngine(), name) || this;
  58802. _this.PassPostProcessId = "PassPostProcessEffect";
  58803. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58804. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58805. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58806. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58807. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58808. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58809. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58810. // IAnimatable
  58811. _this.animations = [];
  58812. // Values
  58813. _this._bloomEnabled = false;
  58814. _this._fxaaEnabled = false;
  58815. _this._imageProcessingEnabled = true;
  58816. _this._bloomScale = 0.6;
  58817. _this._buildAllowed = true;
  58818. /**
  58819. * Specifies the size of the bloom blur kernel, relative to the final output size
  58820. */
  58821. _this.bloomKernel = 64;
  58822. /**
  58823. * Specifies the weight of the bloom in the final rendering
  58824. */
  58825. _this._bloomWeight = 0.15;
  58826. _this._cameras = cameras || [];
  58827. _this._buildAllowed = automaticBuild;
  58828. // Initialize
  58829. _this._scene = scene;
  58830. var caps = _this._scene.getEngine().getCaps();
  58831. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58832. // Misc
  58833. if (_this._hdr) {
  58834. if (caps.textureHalfFloatRender) {
  58835. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58836. }
  58837. else if (caps.textureFloatRender) {
  58838. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58839. }
  58840. }
  58841. else {
  58842. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58843. }
  58844. // Attach
  58845. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58846. _this._buildPipeline();
  58847. return _this;
  58848. }
  58849. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  58850. get: function () {
  58851. return this._bloomWeight;
  58852. },
  58853. set: function (value) {
  58854. if (this._bloomWeight === value) {
  58855. return;
  58856. }
  58857. this._bloomWeight = value;
  58858. if (this._hdr && this.copyBack) {
  58859. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  58860. }
  58861. },
  58862. enumerable: true,
  58863. configurable: true
  58864. });
  58865. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  58866. get: function () {
  58867. return this._bloomScale;
  58868. },
  58869. set: function (value) {
  58870. if (this._bloomScale === value) {
  58871. return;
  58872. }
  58873. this._bloomScale = value;
  58874. this._buildPipeline();
  58875. },
  58876. enumerable: true,
  58877. configurable: true
  58878. });
  58879. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  58880. get: function () {
  58881. return this._bloomEnabled;
  58882. },
  58883. set: function (enabled) {
  58884. if (this._bloomEnabled === enabled) {
  58885. return;
  58886. }
  58887. this._bloomEnabled = enabled;
  58888. this._buildPipeline();
  58889. },
  58890. enumerable: true,
  58891. configurable: true
  58892. });
  58893. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  58894. get: function () {
  58895. return this._fxaaEnabled;
  58896. },
  58897. set: function (enabled) {
  58898. if (this._fxaaEnabled === enabled) {
  58899. return;
  58900. }
  58901. this._fxaaEnabled = enabled;
  58902. this._buildPipeline();
  58903. },
  58904. enumerable: true,
  58905. configurable: true
  58906. });
  58907. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  58908. get: function () {
  58909. return this._imageProcessingEnabled;
  58910. },
  58911. set: function (enabled) {
  58912. if (this._imageProcessingEnabled === enabled) {
  58913. return;
  58914. }
  58915. this._imageProcessingEnabled = enabled;
  58916. this._buildPipeline();
  58917. },
  58918. enumerable: true,
  58919. configurable: true
  58920. });
  58921. /**
  58922. * Force the compilation of the entire pipeline.
  58923. */
  58924. DefaultRenderingPipeline.prototype.prepare = function () {
  58925. var previousState = this._buildAllowed;
  58926. this._buildAllowed = true;
  58927. this._buildPipeline();
  58928. this._buildAllowed = previousState;
  58929. };
  58930. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  58931. var _this = this;
  58932. if (!this._buildAllowed) {
  58933. return;
  58934. }
  58935. var engine = this._scene.getEngine();
  58936. this._disposePostProcesses();
  58937. this._reset();
  58938. if (this.bloomEnabled) {
  58939. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58940. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  58941. if (!this._hdr) {
  58942. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58943. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  58944. this.highlights.autoClear = false;
  58945. this.highlights.alwaysForcePOT = true;
  58946. }
  58947. 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);
  58948. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  58949. this.blurX.alwaysForcePOT = true;
  58950. this.blurX.autoClear = false;
  58951. this.blurX.onActivateObservable.add(function () {
  58952. var dw = _this.blurX.width / engine.getRenderWidth(true);
  58953. _this.blurX.kernel = _this.bloomKernel * dw;
  58954. });
  58955. 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);
  58956. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  58957. this.blurY.alwaysForcePOT = true;
  58958. this.blurY.autoClear = false;
  58959. this.blurY.onActivateObservable.add(function () {
  58960. var dh = _this.blurY.height / engine.getRenderHeight(true);
  58961. _this.blurY.kernel = _this.bloomKernel * dh;
  58962. });
  58963. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58964. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  58965. this.copyBack.alwaysForcePOT = true;
  58966. if (this._hdr) {
  58967. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  58968. var w = this.bloomWeight;
  58969. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  58970. }
  58971. else {
  58972. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  58973. }
  58974. this.copyBack.autoClear = false;
  58975. }
  58976. if (this._imageProcessingEnabled) {
  58977. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58978. if (this._hdr) {
  58979. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  58980. }
  58981. else {
  58982. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  58983. }
  58984. }
  58985. if (this.fxaaEnabled) {
  58986. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58987. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  58988. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58989. }
  58990. else {
  58991. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58992. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  58993. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58994. }
  58995. if (this.bloomEnabled) {
  58996. if (this._hdr) {
  58997. this.copyBack.shareOutputWith(this.blurX);
  58998. if (this.imageProcessing) {
  58999. this.imageProcessing.shareOutputWith(this.pass);
  59000. this.imageProcessing.autoClear = false;
  59001. }
  59002. else if (this.fxaa) {
  59003. this.fxaa.shareOutputWith(this.pass);
  59004. }
  59005. else {
  59006. this.finalMerge.shareOutputWith(this.pass);
  59007. }
  59008. }
  59009. else {
  59010. if (this.fxaa) {
  59011. this.fxaa.shareOutputWith(this.pass);
  59012. }
  59013. else {
  59014. this.finalMerge.shareOutputWith(this.pass);
  59015. }
  59016. }
  59017. }
  59018. if (this._cameras !== null) {
  59019. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59020. }
  59021. };
  59022. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  59023. for (var i = 0; i < this._cameras.length; i++) {
  59024. var camera = this._cameras[i];
  59025. if (this.pass) {
  59026. this.pass.dispose(camera);
  59027. }
  59028. if (this.highlights) {
  59029. this.highlights.dispose(camera);
  59030. }
  59031. if (this.blurX) {
  59032. this.blurX.dispose(camera);
  59033. }
  59034. if (this.blurY) {
  59035. this.blurY.dispose(camera);
  59036. }
  59037. if (this.copyBack) {
  59038. this.copyBack.dispose(camera);
  59039. }
  59040. if (this.imageProcessing) {
  59041. this.imageProcessing.dispose(camera);
  59042. }
  59043. if (this.fxaa) {
  59044. this.fxaa.dispose(camera);
  59045. }
  59046. if (this.finalMerge) {
  59047. this.finalMerge.dispose(camera);
  59048. }
  59049. }
  59050. this.pass = null;
  59051. this.highlights = null;
  59052. this.blurX = null;
  59053. this.blurY = null;
  59054. this.copyBack = null;
  59055. this.imageProcessing = null;
  59056. this.fxaa = null;
  59057. this.finalMerge = null;
  59058. };
  59059. // Dispose
  59060. DefaultRenderingPipeline.prototype.dispose = function () {
  59061. this._disposePostProcesses();
  59062. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59063. _super.prototype.dispose.call(this);
  59064. };
  59065. // Serialize rendering pipeline
  59066. DefaultRenderingPipeline.prototype.serialize = function () {
  59067. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59068. serializationObject.customType = "DefaultRenderingPipeline";
  59069. return serializationObject;
  59070. };
  59071. // Parse serialized pipeline
  59072. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59073. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  59074. };
  59075. __decorate([
  59076. BABYLON.serialize()
  59077. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  59078. __decorate([
  59079. BABYLON.serialize()
  59080. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  59081. __decorate([
  59082. BABYLON.serialize()
  59083. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  59084. __decorate([
  59085. BABYLON.serialize()
  59086. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  59087. __decorate([
  59088. BABYLON.serialize()
  59089. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  59090. __decorate([
  59091. BABYLON.serialize()
  59092. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  59093. __decorate([
  59094. BABYLON.serialize()
  59095. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  59096. __decorate([
  59097. BABYLON.serialize()
  59098. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  59099. return DefaultRenderingPipeline;
  59100. }(BABYLON.PostProcessRenderPipeline));
  59101. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  59102. })(BABYLON || (BABYLON = {}));
  59103. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  59104. var BABYLON;
  59105. (function (BABYLON) {
  59106. var GeometryBufferRenderer = /** @class */ (function () {
  59107. function GeometryBufferRenderer(scene, ratio) {
  59108. if (ratio === void 0) { ratio = 1; }
  59109. this._enablePosition = false;
  59110. this._scene = scene;
  59111. this._ratio = ratio;
  59112. // Render target
  59113. this._createRenderTargets();
  59114. }
  59115. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  59116. set: function (meshes) {
  59117. this._multiRenderTarget.renderList = meshes;
  59118. },
  59119. enumerable: true,
  59120. configurable: true
  59121. });
  59122. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59123. get: function () {
  59124. return this._multiRenderTarget.isSupported;
  59125. },
  59126. enumerable: true,
  59127. configurable: true
  59128. });
  59129. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59130. get: function () {
  59131. return this._enablePosition;
  59132. },
  59133. set: function (enable) {
  59134. this._enablePosition = enable;
  59135. this.dispose();
  59136. this._createRenderTargets();
  59137. },
  59138. enumerable: true,
  59139. configurable: true
  59140. });
  59141. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59142. var material = subMesh.getMaterial();
  59143. if (material && material.disableDepthWrite) {
  59144. return false;
  59145. }
  59146. var defines = [];
  59147. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59148. var mesh = subMesh.getMesh();
  59149. // Alpha test
  59150. if (material && material.needAlphaTesting()) {
  59151. defines.push("#define ALPHATEST");
  59152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59153. attribs.push(BABYLON.VertexBuffer.UVKind);
  59154. defines.push("#define UV1");
  59155. }
  59156. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59157. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59158. defines.push("#define UV2");
  59159. }
  59160. }
  59161. // Buffers
  59162. if (this._enablePosition) {
  59163. defines.push("#define POSITION");
  59164. }
  59165. // Bones
  59166. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59167. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59168. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59169. if (mesh.numBoneInfluencers > 4) {
  59170. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59171. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59172. }
  59173. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59174. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59175. }
  59176. else {
  59177. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59178. }
  59179. // Instances
  59180. if (useInstances) {
  59181. defines.push("#define INSTANCES");
  59182. attribs.push("world0");
  59183. attribs.push("world1");
  59184. attribs.push("world2");
  59185. attribs.push("world3");
  59186. }
  59187. // Get correct effect
  59188. var join = defines.join("\n");
  59189. if (this._cachedDefines !== join) {
  59190. this._cachedDefines = join;
  59191. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  59192. }
  59193. return this._effect.isReady();
  59194. };
  59195. GeometryBufferRenderer.prototype.getGBuffer = function () {
  59196. return this._multiRenderTarget;
  59197. };
  59198. // Methods
  59199. GeometryBufferRenderer.prototype.dispose = function () {
  59200. this.getGBuffer().dispose();
  59201. };
  59202. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  59203. var _this = this;
  59204. var engine = this._scene.getEngine();
  59205. var count = this._enablePosition ? 3 : 2;
  59206. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  59207. if (!this.isSupported) {
  59208. return;
  59209. }
  59210. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59211. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59212. this._multiRenderTarget.refreshRate = 1;
  59213. this._multiRenderTarget.renderParticles = false;
  59214. this._multiRenderTarget.renderList = null;
  59215. // set default depth value to 1.0 (far away)
  59216. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59217. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59218. });
  59219. // Custom render function
  59220. var renderSubMesh = function (subMesh) {
  59221. var mesh = subMesh.getRenderingMesh();
  59222. var scene = _this._scene;
  59223. var engine = scene.getEngine();
  59224. var material = subMesh.getMaterial();
  59225. if (!material) {
  59226. return;
  59227. }
  59228. // Culling
  59229. engine.setState(material.backFaceCulling);
  59230. // Managing instances
  59231. var batch = mesh._getInstancesRenderList(subMesh._id);
  59232. if (batch.mustReturn) {
  59233. return;
  59234. }
  59235. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59236. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59237. engine.enableEffect(_this._effect);
  59238. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59239. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59240. _this._effect.setMatrix("view", scene.getViewMatrix());
  59241. // Alpha test
  59242. if (material && material.needAlphaTesting()) {
  59243. var alphaTexture = material.getAlphaTestTexture();
  59244. if (alphaTexture) {
  59245. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59246. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59247. }
  59248. }
  59249. // Bones
  59250. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59251. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59252. }
  59253. // Draw
  59254. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59255. }
  59256. };
  59257. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59258. var index;
  59259. if (depthOnlySubMeshes.length) {
  59260. engine.setColorWrite(false);
  59261. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59262. renderSubMesh(depthOnlySubMeshes.data[index]);
  59263. }
  59264. engine.setColorWrite(true);
  59265. }
  59266. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59267. renderSubMesh(opaqueSubMeshes.data[index]);
  59268. }
  59269. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59270. renderSubMesh(alphaTestSubMeshes.data[index]);
  59271. }
  59272. };
  59273. };
  59274. return GeometryBufferRenderer;
  59275. }());
  59276. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59277. })(BABYLON || (BABYLON = {}));
  59278. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59279. var BABYLON;
  59280. (function (BABYLON) {
  59281. var RefractionPostProcess = /** @class */ (function (_super) {
  59282. __extends(RefractionPostProcess, _super);
  59283. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59284. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59285. _this.color = color;
  59286. _this.depth = depth;
  59287. _this.colorLevel = colorLevel;
  59288. _this.onActivateObservable.add(function (cam) {
  59289. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59290. });
  59291. _this.onApplyObservable.add(function (effect) {
  59292. effect.setColor3("baseColor", _this.color);
  59293. effect.setFloat("depth", _this.depth);
  59294. effect.setFloat("colorLevel", _this.colorLevel);
  59295. effect.setTexture("refractionSampler", _this._refRexture);
  59296. });
  59297. return _this;
  59298. }
  59299. // Methods
  59300. RefractionPostProcess.prototype.dispose = function (camera) {
  59301. if (this._refRexture) {
  59302. this._refRexture.dispose();
  59303. }
  59304. _super.prototype.dispose.call(this, camera);
  59305. };
  59306. return RefractionPostProcess;
  59307. }(BABYLON.PostProcess));
  59308. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59309. })(BABYLON || (BABYLON = {}));
  59310. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59311. var BABYLON;
  59312. (function (BABYLON) {
  59313. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59314. __extends(BlackAndWhitePostProcess, _super);
  59315. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59316. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59317. _this.degree = 1;
  59318. _this.onApplyObservable.add(function (effect) {
  59319. effect.setFloat("degree", _this.degree);
  59320. });
  59321. return _this;
  59322. }
  59323. return BlackAndWhitePostProcess;
  59324. }(BABYLON.PostProcess));
  59325. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59326. })(BABYLON || (BABYLON = {}));
  59327. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59328. var BABYLON;
  59329. (function (BABYLON) {
  59330. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59331. __extends(ConvolutionPostProcess, _super);
  59332. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59333. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59334. _this.kernel = kernel;
  59335. _this.onApply = function (effect) {
  59336. effect.setFloat2("screenSize", _this.width, _this.height);
  59337. effect.setArray("kernel", _this.kernel);
  59338. };
  59339. return _this;
  59340. }
  59341. // Statics
  59342. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59343. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59344. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59345. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59346. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59347. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59348. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59349. return ConvolutionPostProcess;
  59350. }(BABYLON.PostProcess));
  59351. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59352. })(BABYLON || (BABYLON = {}));
  59353. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59354. var BABYLON;
  59355. (function (BABYLON) {
  59356. var FilterPostProcess = /** @class */ (function (_super) {
  59357. __extends(FilterPostProcess, _super);
  59358. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59359. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59360. _this.kernelMatrix = kernelMatrix;
  59361. _this.onApply = function (effect) {
  59362. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59363. };
  59364. return _this;
  59365. }
  59366. return FilterPostProcess;
  59367. }(BABYLON.PostProcess));
  59368. BABYLON.FilterPostProcess = FilterPostProcess;
  59369. })(BABYLON || (BABYLON = {}));
  59370. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59371. var BABYLON;
  59372. (function (BABYLON) {
  59373. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59374. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59375. __extends(VolumetricLightScatteringPostProcess, _super);
  59376. /**
  59377. * @constructor
  59378. * @param {string} name - The post-process name
  59379. * @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)
  59380. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59381. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59382. * @param {number} samples - The post-process quality, default 100
  59383. * @param {number} samplingMode - The post-process filtering mode
  59384. * @param {BABYLON.Engine} engine - The babylon engine
  59385. * @param {boolean} reusable - If the post-process is reusable
  59386. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59387. */
  59388. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59389. if (samples === void 0) { samples = 100; }
  59390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59391. 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;
  59392. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59393. /**
  59394. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59395. * @type {Vector3}
  59396. */
  59397. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59398. /**
  59399. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59400. * @type {boolean}
  59401. */
  59402. _this.useCustomMeshPosition = false;
  59403. /**
  59404. * If the post-process should inverse the light scattering direction
  59405. * @type {boolean}
  59406. */
  59407. _this.invert = true;
  59408. /**
  59409. * Array containing the excluded meshes not rendered in the internal pass
  59410. */
  59411. _this.excludedMeshes = new Array();
  59412. /**
  59413. * Controls the overall intensity of the post-process
  59414. * @type {number}
  59415. */
  59416. _this.exposure = 0.3;
  59417. /**
  59418. * Dissipates each sample's contribution in range [0, 1]
  59419. * @type {number}
  59420. */
  59421. _this.decay = 0.96815;
  59422. /**
  59423. * Controls the overall intensity of each sample
  59424. * @type {number}
  59425. */
  59426. _this.weight = 0.58767;
  59427. /**
  59428. * Controls the density of each sample
  59429. * @type {number}
  59430. */
  59431. _this.density = 0.926;
  59432. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59433. engine = scene.getEngine();
  59434. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59435. // Configure mesh
  59436. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59437. // Configure
  59438. _this._createPass(scene, ratio.passRatio || ratio);
  59439. _this.onActivate = function (camera) {
  59440. if (!_this.isSupported) {
  59441. _this.dispose(camera);
  59442. }
  59443. _this.onActivate = null;
  59444. };
  59445. _this.onApplyObservable.add(function (effect) {
  59446. _this._updateMeshScreenCoordinates(scene);
  59447. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59448. effect.setFloat("exposure", _this.exposure);
  59449. effect.setFloat("decay", _this.decay);
  59450. effect.setFloat("weight", _this.weight);
  59451. effect.setFloat("density", _this.density);
  59452. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59453. });
  59454. return _this;
  59455. }
  59456. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59457. get: function () {
  59458. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59459. return false;
  59460. },
  59461. set: function (useDiffuseColor) {
  59462. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59463. },
  59464. enumerable: true,
  59465. configurable: true
  59466. });
  59467. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59468. return "VolumetricLightScatteringPostProcess";
  59469. };
  59470. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59471. var mesh = subMesh.getMesh();
  59472. // Render this.mesh as default
  59473. if (mesh === this.mesh && mesh.material) {
  59474. return mesh.material.isReady(mesh);
  59475. }
  59476. var defines = [];
  59477. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59478. var material = subMesh.getMaterial();
  59479. // Alpha test
  59480. if (material) {
  59481. if (material.needAlphaTesting()) {
  59482. defines.push("#define ALPHATEST");
  59483. }
  59484. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59485. attribs.push(BABYLON.VertexBuffer.UVKind);
  59486. defines.push("#define UV1");
  59487. }
  59488. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59489. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59490. defines.push("#define UV2");
  59491. }
  59492. }
  59493. // Bones
  59494. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59495. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59496. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59497. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59498. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59499. }
  59500. else {
  59501. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59502. }
  59503. // Instances
  59504. if (useInstances) {
  59505. defines.push("#define INSTANCES");
  59506. attribs.push("world0");
  59507. attribs.push("world1");
  59508. attribs.push("world2");
  59509. attribs.push("world3");
  59510. }
  59511. // Get correct effect
  59512. var join = defines.join("\n");
  59513. if (this._cachedDefines !== join) {
  59514. this._cachedDefines = join;
  59515. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59516. }
  59517. return this._volumetricLightScatteringPass.isReady();
  59518. };
  59519. /**
  59520. * Sets the new light position for light scattering effect
  59521. * @param {BABYLON.Vector3} The new custom light position
  59522. */
  59523. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59524. this.customMeshPosition = position;
  59525. };
  59526. /**
  59527. * Returns the light position for light scattering effect
  59528. * @return {BABYLON.Vector3} The custom light position
  59529. */
  59530. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59531. return this.customMeshPosition;
  59532. };
  59533. /**
  59534. * Disposes the internal assets and detaches the post-process from the camera
  59535. */
  59536. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59537. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59538. if (rttIndex !== -1) {
  59539. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59540. }
  59541. this._volumetricLightScatteringRTT.dispose();
  59542. _super.prototype.dispose.call(this, camera);
  59543. };
  59544. /**
  59545. * Returns the render target texture used by the post-process
  59546. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59547. */
  59548. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59549. return this._volumetricLightScatteringRTT;
  59550. };
  59551. // Private methods
  59552. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59553. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59554. return true;
  59555. }
  59556. return false;
  59557. };
  59558. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59559. var _this = this;
  59560. var engine = scene.getEngine();
  59561. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59562. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59563. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59564. this._volumetricLightScatteringRTT.renderList = null;
  59565. this._volumetricLightScatteringRTT.renderParticles = false;
  59566. var camera = this.getCamera();
  59567. if (camera) {
  59568. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59569. }
  59570. else {
  59571. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59572. }
  59573. // Custom render function for submeshes
  59574. var renderSubMesh = function (subMesh) {
  59575. var mesh = subMesh.getRenderingMesh();
  59576. if (_this._meshExcluded(mesh)) {
  59577. return;
  59578. }
  59579. var material = subMesh.getMaterial();
  59580. if (!material) {
  59581. return;
  59582. }
  59583. var scene = mesh.getScene();
  59584. var engine = scene.getEngine();
  59585. // Culling
  59586. engine.setState(material.backFaceCulling);
  59587. // Managing instances
  59588. var batch = mesh._getInstancesRenderList(subMesh._id);
  59589. if (batch.mustReturn) {
  59590. return;
  59591. }
  59592. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59593. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59594. var effect = _this._volumetricLightScatteringPass;
  59595. if (mesh === _this.mesh) {
  59596. if (subMesh.effect) {
  59597. effect = subMesh.effect;
  59598. }
  59599. else {
  59600. effect = material.getEffect();
  59601. }
  59602. }
  59603. engine.enableEffect(effect);
  59604. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59605. if (mesh === _this.mesh) {
  59606. material.bind(mesh.getWorldMatrix(), mesh);
  59607. }
  59608. else {
  59609. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59610. // Alpha test
  59611. if (material && material.needAlphaTesting()) {
  59612. var alphaTexture = material.getAlphaTestTexture();
  59613. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59614. if (alphaTexture) {
  59615. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59616. }
  59617. }
  59618. // Bones
  59619. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59620. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59621. }
  59622. }
  59623. // Draw
  59624. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59625. }
  59626. };
  59627. // Render target texture callbacks
  59628. var savedSceneClearColor;
  59629. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59630. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59631. savedSceneClearColor = scene.clearColor;
  59632. scene.clearColor = sceneClearColor;
  59633. });
  59634. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59635. scene.clearColor = savedSceneClearColor;
  59636. });
  59637. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59638. var engine = scene.getEngine();
  59639. var index;
  59640. if (depthOnlySubMeshes.length) {
  59641. engine.setColorWrite(false);
  59642. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59643. renderSubMesh(depthOnlySubMeshes.data[index]);
  59644. }
  59645. engine.setColorWrite(true);
  59646. }
  59647. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59648. renderSubMesh(opaqueSubMeshes.data[index]);
  59649. }
  59650. engine.setAlphaTesting(true);
  59651. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59652. renderSubMesh(alphaTestSubMeshes.data[index]);
  59653. }
  59654. engine.setAlphaTesting(false);
  59655. if (transparentSubMeshes.length) {
  59656. // Sort sub meshes
  59657. for (index = 0; index < transparentSubMeshes.length; index++) {
  59658. var submesh = transparentSubMeshes.data[index];
  59659. var boundingInfo = submesh.getBoundingInfo();
  59660. if (boundingInfo && scene.activeCamera) {
  59661. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59662. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59663. }
  59664. }
  59665. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59666. sortedArray.sort(function (a, b) {
  59667. // Alpha index first
  59668. if (a._alphaIndex > b._alphaIndex) {
  59669. return 1;
  59670. }
  59671. if (a._alphaIndex < b._alphaIndex) {
  59672. return -1;
  59673. }
  59674. // Then distance to camera
  59675. if (a._distanceToCamera < b._distanceToCamera) {
  59676. return 1;
  59677. }
  59678. if (a._distanceToCamera > b._distanceToCamera) {
  59679. return -1;
  59680. }
  59681. return 0;
  59682. });
  59683. // Render sub meshes
  59684. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59685. for (index = 0; index < sortedArray.length; index++) {
  59686. renderSubMesh(sortedArray[index]);
  59687. }
  59688. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59689. }
  59690. };
  59691. };
  59692. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59693. var transform = scene.getTransformMatrix();
  59694. var meshPosition;
  59695. if (this.useCustomMeshPosition) {
  59696. meshPosition = this.customMeshPosition;
  59697. }
  59698. else if (this.attachedNode) {
  59699. meshPosition = this.attachedNode.position;
  59700. }
  59701. else {
  59702. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59703. }
  59704. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59705. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59706. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59707. if (this.invert)
  59708. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59709. };
  59710. // Static methods
  59711. /**
  59712. * Creates a default mesh for the Volumeric Light Scattering post-process
  59713. * @param {string} The mesh name
  59714. * @param {BABYLON.Scene} The scene where to create the mesh
  59715. * @return {BABYLON.Mesh} the default mesh
  59716. */
  59717. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59718. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59719. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59720. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59721. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59722. mesh.material = material;
  59723. return mesh;
  59724. };
  59725. __decorate([
  59726. BABYLON.serializeAsVector3()
  59727. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59728. __decorate([
  59729. BABYLON.serialize()
  59730. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59731. __decorate([
  59732. BABYLON.serialize()
  59733. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59734. __decorate([
  59735. BABYLON.serializeAsMeshReference()
  59736. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59737. __decorate([
  59738. BABYLON.serialize()
  59739. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59740. __decorate([
  59741. BABYLON.serialize()
  59742. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59743. __decorate([
  59744. BABYLON.serialize()
  59745. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59746. __decorate([
  59747. BABYLON.serialize()
  59748. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59749. __decorate([
  59750. BABYLON.serialize()
  59751. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59752. return VolumetricLightScatteringPostProcess;
  59753. }(BABYLON.PostProcess));
  59754. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59755. })(BABYLON || (BABYLON = {}));
  59756. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59757. //
  59758. // This post-process allows the modification of rendered colors by using
  59759. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59760. //
  59761. // The object needs to be provided an url to a texture containing the color
  59762. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59763. // Use an image editing software to tweak the LUT to match your needs.
  59764. //
  59765. // For an example of a color LUT, see here:
  59766. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59767. // For explanations on color grading, see here:
  59768. // http://udn.epicgames.com/Three/ColorGrading.html
  59769. //
  59770. var BABYLON;
  59771. (function (BABYLON) {
  59772. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59773. __extends(ColorCorrectionPostProcess, _super);
  59774. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59775. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59776. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59777. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59778. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59779. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59780. _this.onApply = function (effect) {
  59781. effect.setTexture("colorTable", _this._colorTableTexture);
  59782. };
  59783. return _this;
  59784. }
  59785. return ColorCorrectionPostProcess;
  59786. }(BABYLON.PostProcess));
  59787. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59788. })(BABYLON || (BABYLON = {}));
  59789. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59790. var BABYLON;
  59791. (function (BABYLON) {
  59792. var TonemappingOperator;
  59793. (function (TonemappingOperator) {
  59794. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59795. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59796. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59797. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59798. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59799. ;
  59800. var TonemapPostProcess = /** @class */ (function (_super) {
  59801. __extends(TonemapPostProcess, _super);
  59802. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59804. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59805. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59806. _this._operator = _operator;
  59807. _this.exposureAdjustment = exposureAdjustment;
  59808. var defines = "#define ";
  59809. if (_this._operator === TonemappingOperator.Hable)
  59810. defines += "HABLE_TONEMAPPING";
  59811. else if (_this._operator === TonemappingOperator.Reinhard)
  59812. defines += "REINHARD_TONEMAPPING";
  59813. else if (_this._operator === TonemappingOperator.HejiDawson)
  59814. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59815. else if (_this._operator === TonemappingOperator.Photographic)
  59816. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59817. //sadly a second call to create the effect.
  59818. _this.updateEffect(defines);
  59819. _this.onApply = function (effect) {
  59820. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59821. };
  59822. return _this;
  59823. }
  59824. return TonemapPostProcess;
  59825. }(BABYLON.PostProcess));
  59826. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59827. })(BABYLON || (BABYLON = {}));
  59828. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59829. var BABYLON;
  59830. (function (BABYLON) {
  59831. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59832. __extends(DisplayPassPostProcess, _super);
  59833. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59834. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59835. }
  59836. return DisplayPassPostProcess;
  59837. }(BABYLON.PostProcess));
  59838. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59839. })(BABYLON || (BABYLON = {}));
  59840. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59841. var BABYLON;
  59842. (function (BABYLON) {
  59843. var HighlightsPostProcess = /** @class */ (function (_super) {
  59844. __extends(HighlightsPostProcess, _super);
  59845. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59846. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59847. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  59848. }
  59849. return HighlightsPostProcess;
  59850. }(BABYLON.PostProcess));
  59851. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  59852. })(BABYLON || (BABYLON = {}));
  59853. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  59854. var BABYLON;
  59855. (function (BABYLON) {
  59856. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  59857. __extends(ImageProcessingPostProcess, _super);
  59858. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59859. if (camera === void 0) { camera = null; }
  59860. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59861. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  59862. _this._fromLinearSpace = true;
  59863. /**
  59864. * Defines cache preventing GC.
  59865. */
  59866. _this._defines = {
  59867. IMAGEPROCESSING: false,
  59868. VIGNETTE: false,
  59869. VIGNETTEBLENDMODEMULTIPLY: false,
  59870. VIGNETTEBLENDMODEOPAQUE: false,
  59871. TONEMAPPING: false,
  59872. CONTRAST: false,
  59873. COLORCURVES: false,
  59874. COLORGRADING: false,
  59875. COLORGRADING3D: false,
  59876. FROMLINEARSPACE: false,
  59877. SAMPLER3DGREENDEPTH: false,
  59878. SAMPLER3DBGRMAP: false,
  59879. IMAGEPROCESSINGPOSTPROCESS: false,
  59880. EXPOSURE: false,
  59881. };
  59882. // Setup the default processing configuration to the scene.
  59883. _this._attachImageProcessingConfiguration(null, true);
  59884. _this.imageProcessingConfiguration.applyByPostProcess = true;
  59885. _this.onApply = function (effect) {
  59886. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  59887. };
  59888. return _this;
  59889. }
  59890. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  59891. /**
  59892. * Gets the image processing configuration used either in this material.
  59893. */
  59894. get: function () {
  59895. return this._imageProcessingConfiguration;
  59896. },
  59897. /**
  59898. * Sets the Default image processing configuration used either in the this material.
  59899. *
  59900. * If sets to null, the scene one is in use.
  59901. */
  59902. set: function (value) {
  59903. this._attachImageProcessingConfiguration(value);
  59904. },
  59905. enumerable: true,
  59906. configurable: true
  59907. });
  59908. /**
  59909. * Attaches a new image processing configuration to the PBR Material.
  59910. * @param configuration
  59911. */
  59912. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  59913. var _this = this;
  59914. if (doNotBuild === void 0) { doNotBuild = false; }
  59915. if (configuration === this._imageProcessingConfiguration) {
  59916. return;
  59917. }
  59918. // Detaches observer.
  59919. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59920. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59921. }
  59922. // Pick the scene configuration if needed.
  59923. if (!configuration) {
  59924. var scene = null;
  59925. var engine = this.getEngine();
  59926. var camera = this.getCamera();
  59927. if (camera) {
  59928. scene = camera.getScene();
  59929. }
  59930. else if (engine && engine.scenes) {
  59931. var scenes = engine.scenes;
  59932. scene = scenes[scenes.length - 1];
  59933. }
  59934. else {
  59935. scene = BABYLON.Engine.LastCreatedScene;
  59936. }
  59937. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  59938. }
  59939. else {
  59940. this._imageProcessingConfiguration = configuration;
  59941. }
  59942. // Attaches observer.
  59943. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  59944. _this._updateParameters();
  59945. });
  59946. // Ensure the effect will be rebuilt.
  59947. if (!doNotBuild) {
  59948. this._updateParameters();
  59949. }
  59950. };
  59951. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  59952. /**
  59953. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59954. */
  59955. get: function () {
  59956. return this.imageProcessingConfiguration.colorCurves;
  59957. },
  59958. /**
  59959. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59960. */
  59961. set: function (value) {
  59962. this.imageProcessingConfiguration.colorCurves = value;
  59963. },
  59964. enumerable: true,
  59965. configurable: true
  59966. });
  59967. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  59968. /**
  59969. * Gets wether the color curves effect is enabled.
  59970. */
  59971. get: function () {
  59972. return this.imageProcessingConfiguration.colorCurvesEnabled;
  59973. },
  59974. /**
  59975. * Sets wether the color curves effect is enabled.
  59976. */
  59977. set: function (value) {
  59978. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  59979. },
  59980. enumerable: true,
  59981. configurable: true
  59982. });
  59983. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  59984. /**
  59985. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59986. */
  59987. get: function () {
  59988. return this.imageProcessingConfiguration.colorGradingTexture;
  59989. },
  59990. /**
  59991. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59992. */
  59993. set: function (value) {
  59994. this.imageProcessingConfiguration.colorGradingTexture = value;
  59995. },
  59996. enumerable: true,
  59997. configurable: true
  59998. });
  59999. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  60000. /**
  60001. * Gets wether the color grading effect is enabled.
  60002. */
  60003. get: function () {
  60004. return this.imageProcessingConfiguration.colorGradingEnabled;
  60005. },
  60006. /**
  60007. * Gets wether the color grading effect is enabled.
  60008. */
  60009. set: function (value) {
  60010. this.imageProcessingConfiguration.colorGradingEnabled = value;
  60011. },
  60012. enumerable: true,
  60013. configurable: true
  60014. });
  60015. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  60016. /**
  60017. * Gets exposure used in the effect.
  60018. */
  60019. get: function () {
  60020. return this.imageProcessingConfiguration.exposure;
  60021. },
  60022. /**
  60023. * Sets exposure used in the effect.
  60024. */
  60025. set: function (value) {
  60026. this.imageProcessingConfiguration.exposure = value;
  60027. },
  60028. enumerable: true,
  60029. configurable: true
  60030. });
  60031. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  60032. /**
  60033. * Gets wether tonemapping is enabled or not.
  60034. */
  60035. get: function () {
  60036. return this._imageProcessingConfiguration.toneMappingEnabled;
  60037. },
  60038. /**
  60039. * Sets wether tonemapping is enabled or not
  60040. */
  60041. set: function (value) {
  60042. this._imageProcessingConfiguration.toneMappingEnabled = value;
  60043. },
  60044. enumerable: true,
  60045. configurable: true
  60046. });
  60047. ;
  60048. ;
  60049. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  60050. /**
  60051. * Gets contrast used in the effect.
  60052. */
  60053. get: function () {
  60054. return this.imageProcessingConfiguration.contrast;
  60055. },
  60056. /**
  60057. * Sets contrast used in the effect.
  60058. */
  60059. set: function (value) {
  60060. this.imageProcessingConfiguration.contrast = value;
  60061. },
  60062. enumerable: true,
  60063. configurable: true
  60064. });
  60065. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  60066. /**
  60067. * Gets Vignette stretch size.
  60068. */
  60069. get: function () {
  60070. return this.imageProcessingConfiguration.vignetteStretch;
  60071. },
  60072. /**
  60073. * Sets Vignette stretch size.
  60074. */
  60075. set: function (value) {
  60076. this.imageProcessingConfiguration.vignetteStretch = value;
  60077. },
  60078. enumerable: true,
  60079. configurable: true
  60080. });
  60081. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  60082. /**
  60083. * Gets Vignette centre X Offset.
  60084. */
  60085. get: function () {
  60086. return this.imageProcessingConfiguration.vignetteCentreX;
  60087. },
  60088. /**
  60089. * Sets Vignette centre X Offset.
  60090. */
  60091. set: function (value) {
  60092. this.imageProcessingConfiguration.vignetteCentreX = value;
  60093. },
  60094. enumerable: true,
  60095. configurable: true
  60096. });
  60097. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  60098. /**
  60099. * Gets Vignette centre Y Offset.
  60100. */
  60101. get: function () {
  60102. return this.imageProcessingConfiguration.vignetteCentreY;
  60103. },
  60104. /**
  60105. * Sets Vignette centre Y Offset.
  60106. */
  60107. set: function (value) {
  60108. this.imageProcessingConfiguration.vignetteCentreY = value;
  60109. },
  60110. enumerable: true,
  60111. configurable: true
  60112. });
  60113. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  60114. /**
  60115. * Gets Vignette weight or intensity of the vignette effect.
  60116. */
  60117. get: function () {
  60118. return this.imageProcessingConfiguration.vignetteWeight;
  60119. },
  60120. /**
  60121. * Sets Vignette weight or intensity of the vignette effect.
  60122. */
  60123. set: function (value) {
  60124. this.imageProcessingConfiguration.vignetteWeight = value;
  60125. },
  60126. enumerable: true,
  60127. configurable: true
  60128. });
  60129. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60130. /**
  60131. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60132. * if vignetteEnabled is set to true.
  60133. */
  60134. get: function () {
  60135. return this.imageProcessingConfiguration.vignetteColor;
  60136. },
  60137. /**
  60138. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60139. * if vignetteEnabled is set to true.
  60140. */
  60141. set: function (value) {
  60142. this.imageProcessingConfiguration.vignetteColor = value;
  60143. },
  60144. enumerable: true,
  60145. configurable: true
  60146. });
  60147. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  60148. /**
  60149. * Gets Camera field of view used by the Vignette effect.
  60150. */
  60151. get: function () {
  60152. return this.imageProcessingConfiguration.vignetteCameraFov;
  60153. },
  60154. /**
  60155. * Sets Camera field of view used by the Vignette effect.
  60156. */
  60157. set: function (value) {
  60158. this.imageProcessingConfiguration.vignetteCameraFov = value;
  60159. },
  60160. enumerable: true,
  60161. configurable: true
  60162. });
  60163. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  60164. /**
  60165. * Gets the vignette blend mode allowing different kind of effect.
  60166. */
  60167. get: function () {
  60168. return this.imageProcessingConfiguration.vignetteBlendMode;
  60169. },
  60170. /**
  60171. * Sets the vignette blend mode allowing different kind of effect.
  60172. */
  60173. set: function (value) {
  60174. this.imageProcessingConfiguration.vignetteBlendMode = value;
  60175. },
  60176. enumerable: true,
  60177. configurable: true
  60178. });
  60179. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  60180. /**
  60181. * Gets wether the vignette effect is enabled.
  60182. */
  60183. get: function () {
  60184. return this.imageProcessingConfiguration.vignetteEnabled;
  60185. },
  60186. /**
  60187. * Sets wether the vignette effect is enabled.
  60188. */
  60189. set: function (value) {
  60190. this.imageProcessingConfiguration.vignetteEnabled = value;
  60191. },
  60192. enumerable: true,
  60193. configurable: true
  60194. });
  60195. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  60196. /**
  60197. * Gets wether the input of the processing is in Gamma or Linear Space.
  60198. */
  60199. get: function () {
  60200. return this._fromLinearSpace;
  60201. },
  60202. /**
  60203. * Sets wether the input of the processing is in Gamma or Linear Space.
  60204. */
  60205. set: function (value) {
  60206. if (this._fromLinearSpace === value) {
  60207. return;
  60208. }
  60209. this._fromLinearSpace = value;
  60210. this._updateParameters();
  60211. },
  60212. enumerable: true,
  60213. configurable: true
  60214. });
  60215. ImageProcessingPostProcess.prototype.getClassName = function () {
  60216. return "ImageProcessingPostProcess";
  60217. };
  60218. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60219. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60220. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60221. var defines = "";
  60222. for (var define in this._defines) {
  60223. if (this._defines[define]) {
  60224. defines += "#define " + define + ";\r\n";
  60225. }
  60226. }
  60227. var samplers = ["textureSampler"];
  60228. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60229. var uniforms = ["scale"];
  60230. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60231. this.updateEffect(defines, uniforms, samplers);
  60232. };
  60233. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60234. _super.prototype.dispose.call(this, camera);
  60235. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60236. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60237. }
  60238. this.imageProcessingConfiguration.applyByPostProcess = false;
  60239. };
  60240. __decorate([
  60241. BABYLON.serialize()
  60242. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60243. return ImageProcessingPostProcess;
  60244. }(BABYLON.PostProcess));
  60245. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60246. })(BABYLON || (BABYLON = {}));
  60247. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60248. var BABYLON;
  60249. (function (BABYLON) {
  60250. var BlurPostProcess = /** @class */ (function (_super) {
  60251. __extends(BlurPostProcess, _super);
  60252. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60253. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60254. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60255. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60256. _this.direction = direction;
  60257. _this._packedFloat = false;
  60258. _this.onApplyObservable.add(function (effect) {
  60259. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60260. });
  60261. _this.kernel = kernel;
  60262. return _this;
  60263. }
  60264. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60265. /**
  60266. * Gets the length in pixels of the blur sample region
  60267. */
  60268. get: function () {
  60269. return this._idealKernel;
  60270. },
  60271. /**
  60272. * Sets the length in pixels of the blur sample region
  60273. */
  60274. set: function (v) {
  60275. if (this._idealKernel === v) {
  60276. return;
  60277. }
  60278. v = Math.max(v, 1);
  60279. this._idealKernel = v;
  60280. this._kernel = this._nearestBestKernel(v);
  60281. this._updateParameters();
  60282. },
  60283. enumerable: true,
  60284. configurable: true
  60285. });
  60286. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60287. /**
  60288. * Gets wether or not the blur is unpacking/repacking floats
  60289. */
  60290. get: function () {
  60291. return this._packedFloat;
  60292. },
  60293. /**
  60294. * Sets wether or not the blur needs to unpack/repack floats
  60295. */
  60296. set: function (v) {
  60297. if (this._packedFloat === v) {
  60298. return;
  60299. }
  60300. this._packedFloat = v;
  60301. this._updateParameters();
  60302. },
  60303. enumerable: true,
  60304. configurable: true
  60305. });
  60306. BlurPostProcess.prototype._updateParameters = function () {
  60307. // Generate sampling offsets and weights
  60308. var N = this._kernel;
  60309. var centerIndex = (N - 1) / 2;
  60310. // Generate Gaussian sampling weights over kernel
  60311. var offsets = [];
  60312. var weights = [];
  60313. var totalWeight = 0;
  60314. for (var i = 0; i < N; i++) {
  60315. var u = i / (N - 1);
  60316. var w = this._gaussianWeight(u * 2.0 - 1);
  60317. offsets[i] = (i - centerIndex);
  60318. weights[i] = w;
  60319. totalWeight += w;
  60320. }
  60321. // Normalize weights
  60322. for (var i = 0; i < weights.length; i++) {
  60323. weights[i] /= totalWeight;
  60324. }
  60325. // Optimize: combine samples to take advantage of hardware linear sampling
  60326. // Walk from left to center, combining pairs (symmetrically)
  60327. var linearSamplingWeights = [];
  60328. var linearSamplingOffsets = [];
  60329. var linearSamplingMap = [];
  60330. for (var i = 0; i <= centerIndex; i += 2) {
  60331. var j = Math.min(i + 1, Math.floor(centerIndex));
  60332. var singleCenterSample = i === j;
  60333. if (singleCenterSample) {
  60334. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60335. }
  60336. else {
  60337. var sharedCell = j === centerIndex;
  60338. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60339. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60340. if (offsetLinear === 0) {
  60341. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60342. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60343. }
  60344. else {
  60345. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60346. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60347. }
  60348. }
  60349. }
  60350. for (var i = 0; i < linearSamplingMap.length; i++) {
  60351. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60352. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60353. }
  60354. // Replace with optimized
  60355. offsets = linearSamplingOffsets;
  60356. weights = linearSamplingWeights;
  60357. // Generate shaders
  60358. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60359. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60360. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60361. var defines = "";
  60362. for (var i = 0; i < varyingCount; i++) {
  60363. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60364. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60365. }
  60366. var depCount = 0;
  60367. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60368. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60369. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60370. depCount++;
  60371. }
  60372. if (this.packedFloat) {
  60373. defines += "#define PACKEDFLOAT 1";
  60374. }
  60375. this.updateEffect(defines, null, null, {
  60376. varyingCount: varyingCount,
  60377. depCount: depCount
  60378. });
  60379. };
  60380. /**
  60381. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60382. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60383. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60384. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60385. * The gaps between physical kernels are compensated for in the weighting of the samples
  60386. * @param idealKernel Ideal blur kernel.
  60387. * @return Nearest best kernel.
  60388. */
  60389. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60390. var v = Math.round(idealKernel);
  60391. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60392. var k = _a[_i];
  60393. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60394. return Math.max(k, 3);
  60395. }
  60396. }
  60397. return Math.max(v, 3);
  60398. };
  60399. /**
  60400. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60401. * @param x The point on the Gaussian distribution to sample.
  60402. * @return the value of the Gaussian function at x.
  60403. */
  60404. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60405. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60406. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60407. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60408. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60409. // truncated at around 1.3% of peak strength.
  60410. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60411. var sigma = (1 / 3);
  60412. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60413. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60414. var weight = (1.0 / denominator) * Math.exp(exponent);
  60415. return weight;
  60416. };
  60417. /**
  60418. * Generates a string that can be used as a floating point number in GLSL.
  60419. * @param x Value to print.
  60420. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60421. * @return GLSL float string.
  60422. */
  60423. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60424. if (decimalFigures === void 0) { decimalFigures = 8; }
  60425. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60426. };
  60427. return BlurPostProcess;
  60428. }(BABYLON.PostProcess));
  60429. BABYLON.BlurPostProcess = BlurPostProcess;
  60430. })(BABYLON || (BABYLON = {}));
  60431. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60432. var BABYLON;
  60433. (function (BABYLON) {
  60434. var Bone = /** @class */ (function (_super) {
  60435. __extends(Bone, _super);
  60436. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60437. if (parentBone === void 0) { parentBone = null; }
  60438. if (localMatrix === void 0) { localMatrix = null; }
  60439. if (restPose === void 0) { restPose = null; }
  60440. if (baseMatrix === void 0) { baseMatrix = null; }
  60441. if (index === void 0) { index = null; }
  60442. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60443. _this.name = name;
  60444. _this.children = new Array();
  60445. _this.animations = new Array();
  60446. // Set this value to map this bone to a different index in the transform matrices.
  60447. // Set this value to -1 to exclude the bone from the transform matrices.
  60448. _this._index = null;
  60449. _this._worldTransform = new BABYLON.Matrix();
  60450. _this._absoluteTransform = new BABYLON.Matrix();
  60451. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60452. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60453. _this._scaleVector = BABYLON.Vector3.One();
  60454. _this._negateScaleChildren = BABYLON.Vector3.One();
  60455. _this._scalingDeterminant = 1;
  60456. _this._skeleton = skeleton;
  60457. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60458. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60459. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60460. _this._index = index;
  60461. skeleton.bones.push(_this);
  60462. _this.setParent(parentBone, false);
  60463. _this._updateDifferenceMatrix();
  60464. return _this;
  60465. }
  60466. Object.defineProperty(Bone.prototype, "_matrix", {
  60467. get: function () {
  60468. return this._localMatrix;
  60469. },
  60470. set: function (val) {
  60471. if (this._localMatrix) {
  60472. this._localMatrix.copyFrom(val);
  60473. }
  60474. else {
  60475. this._localMatrix = val;
  60476. }
  60477. },
  60478. enumerable: true,
  60479. configurable: true
  60480. });
  60481. // Members
  60482. Bone.prototype.getSkeleton = function () {
  60483. return this._skeleton;
  60484. };
  60485. Bone.prototype.getParent = function () {
  60486. return this._parent;
  60487. };
  60488. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60489. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60490. if (this._parent === parent) {
  60491. return;
  60492. }
  60493. if (this._parent) {
  60494. var index = this._parent.children.indexOf(this);
  60495. if (index !== -1) {
  60496. this._parent.children.splice(index, 1);
  60497. }
  60498. }
  60499. this._parent = parent;
  60500. if (this._parent) {
  60501. this._parent.children.push(this);
  60502. }
  60503. if (updateDifferenceMatrix) {
  60504. this._updateDifferenceMatrix();
  60505. }
  60506. };
  60507. Bone.prototype.getLocalMatrix = function () {
  60508. return this._localMatrix;
  60509. };
  60510. Bone.prototype.getBaseMatrix = function () {
  60511. return this._baseMatrix;
  60512. };
  60513. Bone.prototype.getRestPose = function () {
  60514. return this._restPose;
  60515. };
  60516. Bone.prototype.returnToRest = function () {
  60517. this.updateMatrix(this._restPose.clone());
  60518. };
  60519. Bone.prototype.getWorldMatrix = function () {
  60520. return this._worldTransform;
  60521. };
  60522. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60523. return this._invertedAbsoluteTransform;
  60524. };
  60525. Bone.prototype.getAbsoluteTransform = function () {
  60526. return this._absoluteTransform;
  60527. };
  60528. Object.defineProperty(Bone.prototype, "position", {
  60529. // Properties (matches AbstractMesh properties)
  60530. get: function () {
  60531. return this.getPosition();
  60532. },
  60533. set: function (newPosition) {
  60534. this.setPosition(newPosition);
  60535. },
  60536. enumerable: true,
  60537. configurable: true
  60538. });
  60539. Object.defineProperty(Bone.prototype, "rotation", {
  60540. get: function () {
  60541. return this.getRotation();
  60542. },
  60543. set: function (newRotation) {
  60544. this.setRotation(newRotation);
  60545. },
  60546. enumerable: true,
  60547. configurable: true
  60548. });
  60549. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60550. get: function () {
  60551. return this.getRotationQuaternion();
  60552. },
  60553. set: function (newRotation) {
  60554. this.setRotationQuaternion(newRotation);
  60555. },
  60556. enumerable: true,
  60557. configurable: true
  60558. });
  60559. Object.defineProperty(Bone.prototype, "scaling", {
  60560. get: function () {
  60561. return this.getScale();
  60562. },
  60563. set: function (newScaling) {
  60564. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60565. },
  60566. enumerable: true,
  60567. configurable: true
  60568. });
  60569. // Methods
  60570. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60571. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60572. this._baseMatrix = matrix.clone();
  60573. this._localMatrix = matrix.clone();
  60574. this._skeleton._markAsDirty();
  60575. if (updateDifferenceMatrix) {
  60576. this._updateDifferenceMatrix();
  60577. }
  60578. };
  60579. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60580. if (!rootMatrix) {
  60581. rootMatrix = this._baseMatrix;
  60582. }
  60583. if (this._parent) {
  60584. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60585. }
  60586. else {
  60587. this._absoluteTransform.copyFrom(rootMatrix);
  60588. }
  60589. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60590. for (var index = 0; index < this.children.length; index++) {
  60591. this.children[index]._updateDifferenceMatrix();
  60592. }
  60593. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60594. };
  60595. Bone.prototype.markAsDirty = function () {
  60596. this._currentRenderId++;
  60597. this._skeleton._markAsDirty();
  60598. };
  60599. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60600. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60601. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60602. // all animation may be coming from a library skeleton, so may need to create animation
  60603. if (this.animations.length === 0) {
  60604. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60605. this.animations[0].setKeys([]);
  60606. }
  60607. // get animation info / verify there is such a range from the source bone
  60608. var sourceRange = source.animations[0].getRange(rangeName);
  60609. if (!sourceRange) {
  60610. return false;
  60611. }
  60612. var from = sourceRange.from;
  60613. var to = sourceRange.to;
  60614. var sourceKeys = source.animations[0].getKeys();
  60615. // rescaling prep
  60616. var sourceBoneLength = source.length;
  60617. var sourceParent = source.getParent();
  60618. var parent = this.getParent();
  60619. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60620. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60621. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60622. var destKeys = this.animations[0].getKeys();
  60623. // loop vars declaration
  60624. var orig;
  60625. var origTranslation;
  60626. var mat;
  60627. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60628. orig = sourceKeys[key];
  60629. if (orig.frame >= from && orig.frame <= to) {
  60630. if (rescaleAsRequired) {
  60631. mat = orig.value.clone();
  60632. // scale based on parent ratio, when bone has parent
  60633. if (parentScalingReqd) {
  60634. origTranslation = mat.getTranslation();
  60635. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60636. // scale based on skeleton dimension ratio when root bone, and value is passed
  60637. }
  60638. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60639. origTranslation = mat.getTranslation();
  60640. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60641. // use original when root bone, and no data for skelDimensionsRatio
  60642. }
  60643. else {
  60644. mat = orig.value;
  60645. }
  60646. }
  60647. else {
  60648. mat = orig.value;
  60649. }
  60650. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60651. }
  60652. }
  60653. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60654. return true;
  60655. };
  60656. /**
  60657. * Translate the bone in local or world space.
  60658. * @param vec The amount to translate the bone.
  60659. * @param space The space that the translation is in.
  60660. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60661. */
  60662. Bone.prototype.translate = function (vec, space, mesh) {
  60663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60664. var lm = this.getLocalMatrix();
  60665. if (space == BABYLON.Space.LOCAL) {
  60666. lm.m[12] += vec.x;
  60667. lm.m[13] += vec.y;
  60668. lm.m[14] += vec.z;
  60669. }
  60670. else {
  60671. var wm = null;
  60672. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60673. if (mesh) {
  60674. wm = mesh.getWorldMatrix();
  60675. }
  60676. this._skeleton.computeAbsoluteTransforms();
  60677. var tmat = Bone._tmpMats[0];
  60678. var tvec = Bone._tmpVecs[0];
  60679. if (this._parent) {
  60680. if (mesh && wm) {
  60681. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60682. tmat.multiplyToRef(wm, tmat);
  60683. }
  60684. else {
  60685. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60686. }
  60687. }
  60688. tmat.m[12] = 0;
  60689. tmat.m[13] = 0;
  60690. tmat.m[14] = 0;
  60691. tmat.invert();
  60692. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60693. lm.m[12] += tvec.x;
  60694. lm.m[13] += tvec.y;
  60695. lm.m[14] += tvec.z;
  60696. }
  60697. this.markAsDirty();
  60698. };
  60699. /**
  60700. * Set the postion of the bone in local or world space.
  60701. * @param position The position to set the bone.
  60702. * @param space The space that the position is in.
  60703. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60704. */
  60705. Bone.prototype.setPosition = function (position, space, mesh) {
  60706. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60707. var lm = this.getLocalMatrix();
  60708. if (space == BABYLON.Space.LOCAL) {
  60709. lm.m[12] = position.x;
  60710. lm.m[13] = position.y;
  60711. lm.m[14] = position.z;
  60712. }
  60713. else {
  60714. var wm = null;
  60715. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60716. if (mesh) {
  60717. wm = mesh.getWorldMatrix();
  60718. }
  60719. this._skeleton.computeAbsoluteTransforms();
  60720. var tmat = Bone._tmpMats[0];
  60721. var vec = Bone._tmpVecs[0];
  60722. if (this._parent) {
  60723. if (mesh && wm) {
  60724. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60725. tmat.multiplyToRef(wm, tmat);
  60726. }
  60727. else {
  60728. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60729. }
  60730. }
  60731. tmat.invert();
  60732. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60733. lm.m[12] = vec.x;
  60734. lm.m[13] = vec.y;
  60735. lm.m[14] = vec.z;
  60736. }
  60737. this.markAsDirty();
  60738. };
  60739. /**
  60740. * Set the absolute postion of the bone (world space).
  60741. * @param position The position to set the bone.
  60742. * @param mesh The mesh that this bone is attached to.
  60743. */
  60744. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60745. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60746. };
  60747. /**
  60748. * Set the scale of the bone on the x, y and z axes.
  60749. * @param x The scale of the bone on the x axis.
  60750. * @param x The scale of the bone on the y axis.
  60751. * @param z The scale of the bone on the z axis.
  60752. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60753. */
  60754. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60755. if (scaleChildren === void 0) { scaleChildren = false; }
  60756. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60757. if (!scaleChildren) {
  60758. this._negateScaleChildren.x = 1 / x;
  60759. this._negateScaleChildren.y = 1 / y;
  60760. this._negateScaleChildren.z = 1 / z;
  60761. }
  60762. this._syncScaleVector();
  60763. }
  60764. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60765. };
  60766. /**
  60767. * Scale the bone on the x, y and z axes.
  60768. * @param x The amount to scale the bone on the x axis.
  60769. * @param x The amount to scale the bone on the y axis.
  60770. * @param z The amount to scale the bone on the z axis.
  60771. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60772. */
  60773. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60774. if (scaleChildren === void 0) { scaleChildren = false; }
  60775. var locMat = this.getLocalMatrix();
  60776. var origLocMat = Bone._tmpMats[0];
  60777. origLocMat.copyFrom(locMat);
  60778. var origLocMatInv = Bone._tmpMats[1];
  60779. origLocMatInv.copyFrom(origLocMat);
  60780. origLocMatInv.invert();
  60781. var scaleMat = Bone._tmpMats[2];
  60782. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60783. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60784. this._scaleVector.x *= x;
  60785. this._scaleVector.y *= y;
  60786. this._scaleVector.z *= z;
  60787. locMat.multiplyToRef(origLocMatInv, locMat);
  60788. locMat.multiplyToRef(scaleMat, locMat);
  60789. locMat.multiplyToRef(origLocMat, locMat);
  60790. var parent = this.getParent();
  60791. if (parent) {
  60792. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60793. }
  60794. else {
  60795. this.getAbsoluteTransform().copyFrom(locMat);
  60796. }
  60797. var len = this.children.length;
  60798. scaleMat.invert();
  60799. for (var i = 0; i < len; i++) {
  60800. var child = this.children[i];
  60801. var cm = child.getLocalMatrix();
  60802. cm.multiplyToRef(scaleMat, cm);
  60803. var lm = child.getLocalMatrix();
  60804. lm.m[12] *= x;
  60805. lm.m[13] *= y;
  60806. lm.m[14] *= z;
  60807. }
  60808. this.computeAbsoluteTransforms();
  60809. if (scaleChildren) {
  60810. for (var i = 0; i < len; i++) {
  60811. this.children[i].scale(x, y, z, scaleChildren);
  60812. }
  60813. }
  60814. this.markAsDirty();
  60815. };
  60816. /**
  60817. * Set the yaw, pitch, and roll of the bone in local or world space.
  60818. * @param yaw The rotation of the bone on the y axis.
  60819. * @param pitch The rotation of the bone on the x axis.
  60820. * @param roll The rotation of the bone on the z axis.
  60821. * @param space The space that the axes of rotation are in.
  60822. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60823. */
  60824. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60825. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60826. var rotMat = Bone._tmpMats[0];
  60827. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60828. var rotMatInv = Bone._tmpMats[1];
  60829. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60830. rotMatInv.multiplyToRef(rotMat, rotMat);
  60831. this._rotateWithMatrix(rotMat, space, mesh);
  60832. };
  60833. /**
  60834. * Rotate the bone on an axis in local or world space.
  60835. * @param axis The axis to rotate the bone on.
  60836. * @param amount The amount to rotate the bone.
  60837. * @param space The space that the axis is in.
  60838. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60839. */
  60840. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60841. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60842. var rmat = Bone._tmpMats[0];
  60843. rmat.m[12] = 0;
  60844. rmat.m[13] = 0;
  60845. rmat.m[14] = 0;
  60846. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60847. this._rotateWithMatrix(rmat, space, mesh);
  60848. };
  60849. /**
  60850. * Set the rotation of the bone to a particular axis angle in local or world space.
  60851. * @param axis The axis to rotate the bone on.
  60852. * @param angle The angle that the bone should be rotated to.
  60853. * @param space The space that the axis is in.
  60854. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60855. */
  60856. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  60857. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60858. var rotMat = Bone._tmpMats[0];
  60859. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  60860. var rotMatInv = Bone._tmpMats[1];
  60861. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60862. rotMatInv.multiplyToRef(rotMat, rotMat);
  60863. this._rotateWithMatrix(rotMat, space, mesh);
  60864. };
  60865. /**
  60866. * Set the euler rotation of the bone in local of world space.
  60867. * @param rotation The euler rotation that the bone should be set to.
  60868. * @param space The space that the rotation is in.
  60869. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60870. */
  60871. Bone.prototype.setRotation = function (rotation, space, mesh) {
  60872. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60873. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  60874. };
  60875. /**
  60876. * Set the quaternion rotation of the bone in local of world space.
  60877. * @param quat The quaternion rotation that the bone should be set to.
  60878. * @param space The space that the rotation is in.
  60879. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60880. */
  60881. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  60882. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60883. var rotMatInv = Bone._tmpMats[0];
  60884. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60885. var rotMat = Bone._tmpMats[1];
  60886. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  60887. rotMatInv.multiplyToRef(rotMat, rotMat);
  60888. this._rotateWithMatrix(rotMat, space, mesh);
  60889. };
  60890. /**
  60891. * Set the rotation matrix of the bone in local of world space.
  60892. * @param rotMat The rotation matrix that the bone should be set to.
  60893. * @param space The space that the rotation is in.
  60894. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60895. */
  60896. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  60897. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60898. var rotMatInv = Bone._tmpMats[0];
  60899. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60900. var rotMat2 = Bone._tmpMats[1];
  60901. rotMat2.copyFrom(rotMat);
  60902. rotMatInv.multiplyToRef(rotMat, rotMat2);
  60903. this._rotateWithMatrix(rotMat2, space, mesh);
  60904. };
  60905. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  60906. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60907. var lmat = this.getLocalMatrix();
  60908. var lx = lmat.m[12];
  60909. var ly = lmat.m[13];
  60910. var lz = lmat.m[14];
  60911. var parent = this.getParent();
  60912. var parentScale = Bone._tmpMats[3];
  60913. var parentScaleInv = Bone._tmpMats[4];
  60914. if (parent) {
  60915. if (space == BABYLON.Space.WORLD) {
  60916. if (mesh) {
  60917. parentScale.copyFrom(mesh.getWorldMatrix());
  60918. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  60919. }
  60920. else {
  60921. parentScale.copyFrom(parent.getAbsoluteTransform());
  60922. }
  60923. }
  60924. else {
  60925. parentScale = parent._scaleMatrix;
  60926. }
  60927. parentScaleInv.copyFrom(parentScale);
  60928. parentScaleInv.invert();
  60929. lmat.multiplyToRef(parentScale, lmat);
  60930. lmat.multiplyToRef(rmat, lmat);
  60931. lmat.multiplyToRef(parentScaleInv, lmat);
  60932. }
  60933. else {
  60934. if (space == BABYLON.Space.WORLD && mesh) {
  60935. parentScale.copyFrom(mesh.getWorldMatrix());
  60936. parentScaleInv.copyFrom(parentScale);
  60937. parentScaleInv.invert();
  60938. lmat.multiplyToRef(parentScale, lmat);
  60939. lmat.multiplyToRef(rmat, lmat);
  60940. lmat.multiplyToRef(parentScaleInv, lmat);
  60941. }
  60942. else {
  60943. lmat.multiplyToRef(rmat, lmat);
  60944. }
  60945. }
  60946. lmat.m[12] = lx;
  60947. lmat.m[13] = ly;
  60948. lmat.m[14] = lz;
  60949. this.computeAbsoluteTransforms();
  60950. this.markAsDirty();
  60951. };
  60952. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  60953. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60954. if (space == BABYLON.Space.WORLD) {
  60955. var scaleMatrix = Bone._tmpMats[2];
  60956. scaleMatrix.copyFrom(this._scaleMatrix);
  60957. rotMatInv.copyFrom(this.getAbsoluteTransform());
  60958. if (mesh) {
  60959. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  60960. var meshScale = Bone._tmpMats[3];
  60961. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  60962. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  60963. }
  60964. rotMatInv.invert();
  60965. scaleMatrix.m[0] *= this._scalingDeterminant;
  60966. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60967. }
  60968. else {
  60969. rotMatInv.copyFrom(this.getLocalMatrix());
  60970. rotMatInv.invert();
  60971. var scaleMatrix = Bone._tmpMats[2];
  60972. scaleMatrix.copyFrom(this._scaleMatrix);
  60973. if (this._parent) {
  60974. var pscaleMatrix = Bone._tmpMats[3];
  60975. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  60976. pscaleMatrix.invert();
  60977. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  60978. }
  60979. else {
  60980. scaleMatrix.m[0] *= this._scalingDeterminant;
  60981. }
  60982. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60983. }
  60984. };
  60985. /**
  60986. * Get the scale of the bone
  60987. * @returns the scale of the bone
  60988. */
  60989. Bone.prototype.getScale = function () {
  60990. return this._scaleVector.clone();
  60991. };
  60992. /**
  60993. * Copy the scale of the bone to a vector3.
  60994. * @param result The vector3 to copy the scale to
  60995. */
  60996. Bone.prototype.getScaleToRef = function (result) {
  60997. result.copyFrom(this._scaleVector);
  60998. };
  60999. /**
  61000. * Get the position of the bone in local or world space.
  61001. * @param space The space that the returned position is in.
  61002. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61003. * @returns The position of the bone
  61004. */
  61005. Bone.prototype.getPosition = function (space, mesh) {
  61006. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61007. if (mesh === void 0) { mesh = null; }
  61008. var pos = BABYLON.Vector3.Zero();
  61009. this.getPositionToRef(space, mesh, pos);
  61010. return pos;
  61011. };
  61012. /**
  61013. * Copy the position of the bone to a vector3 in local or world space.
  61014. * @param space The space that the returned position is in.
  61015. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61016. * @param result The vector3 to copy the position to.
  61017. */
  61018. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  61019. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61020. if (space == BABYLON.Space.LOCAL) {
  61021. var lm = this.getLocalMatrix();
  61022. result.x = lm.m[12];
  61023. result.y = lm.m[13];
  61024. result.z = lm.m[14];
  61025. }
  61026. else {
  61027. var wm = null;
  61028. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61029. if (mesh) {
  61030. wm = mesh.getWorldMatrix();
  61031. }
  61032. this._skeleton.computeAbsoluteTransforms();
  61033. var tmat = Bone._tmpMats[0];
  61034. if (mesh && wm) {
  61035. tmat.copyFrom(this.getAbsoluteTransform());
  61036. tmat.multiplyToRef(wm, tmat);
  61037. }
  61038. else {
  61039. tmat = this.getAbsoluteTransform();
  61040. }
  61041. result.x = tmat.m[12];
  61042. result.y = tmat.m[13];
  61043. result.z = tmat.m[14];
  61044. }
  61045. };
  61046. /**
  61047. * Get the absolute position of the bone (world space).
  61048. * @param mesh The mesh that this bone is attached to.
  61049. * @returns The absolute position of the bone
  61050. */
  61051. Bone.prototype.getAbsolutePosition = function (mesh) {
  61052. if (mesh === void 0) { mesh = null; }
  61053. var pos = BABYLON.Vector3.Zero();
  61054. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  61055. return pos;
  61056. };
  61057. /**
  61058. * Copy the absolute position of the bone (world space) to the result param.
  61059. * @param mesh The mesh that this bone is attached to.
  61060. * @param result The vector3 to copy the absolute position to.
  61061. */
  61062. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  61063. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  61064. };
  61065. /**
  61066. * Compute the absolute transforms of this bone and its children.
  61067. */
  61068. Bone.prototype.computeAbsoluteTransforms = function () {
  61069. if (this._parent) {
  61070. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61071. }
  61072. else {
  61073. this._absoluteTransform.copyFrom(this._localMatrix);
  61074. var poseMatrix = this._skeleton.getPoseMatrix();
  61075. if (poseMatrix) {
  61076. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  61077. }
  61078. }
  61079. var children = this.children;
  61080. var len = children.length;
  61081. for (var i = 0; i < len; i++) {
  61082. children[i].computeAbsoluteTransforms();
  61083. }
  61084. };
  61085. Bone.prototype._syncScaleVector = function () {
  61086. var lm = this.getLocalMatrix();
  61087. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  61088. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  61089. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  61090. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  61091. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  61092. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  61093. this._scaleVector.x = xs * Math.sqrt(xsq);
  61094. this._scaleVector.y = ys * Math.sqrt(ysq);
  61095. this._scaleVector.z = zs * Math.sqrt(zsq);
  61096. if (this._parent) {
  61097. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  61098. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  61099. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  61100. }
  61101. 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);
  61102. };
  61103. /**
  61104. * Get the world direction from an axis that is in the local space of the bone.
  61105. * @param localAxis The local direction that is used to compute the world direction.
  61106. * @param mesh The mesh that this bone is attached to.
  61107. * @returns The world direction
  61108. */
  61109. Bone.prototype.getDirection = function (localAxis, mesh) {
  61110. if (mesh === void 0) { mesh = null; }
  61111. var result = BABYLON.Vector3.Zero();
  61112. this.getDirectionToRef(localAxis, mesh, result);
  61113. return result;
  61114. };
  61115. /**
  61116. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  61117. * @param localAxis The local direction that is used to compute the world direction.
  61118. * @param mesh The mesh that this bone is attached to.
  61119. * @param result The vector3 that the world direction will be copied to.
  61120. */
  61121. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61122. if (mesh === void 0) { mesh = null; }
  61123. var wm = null;
  61124. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61125. if (mesh) {
  61126. wm = mesh.getWorldMatrix();
  61127. }
  61128. this._skeleton.computeAbsoluteTransforms();
  61129. var mat = Bone._tmpMats[0];
  61130. mat.copyFrom(this.getAbsoluteTransform());
  61131. if (mesh && wm) {
  61132. mat.multiplyToRef(wm, mat);
  61133. }
  61134. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61135. result.normalize();
  61136. };
  61137. /**
  61138. * Get the euler rotation of the bone in local or world space.
  61139. * @param space The space that the rotation should be in.
  61140. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61141. * @returns The euler rotation
  61142. */
  61143. Bone.prototype.getRotation = function (space, mesh) {
  61144. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61145. if (mesh === void 0) { mesh = null; }
  61146. var result = BABYLON.Vector3.Zero();
  61147. this.getRotationToRef(space, mesh, result);
  61148. return result;
  61149. };
  61150. /**
  61151. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  61152. * @param space The space that the rotation should be in.
  61153. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61154. * @param result The vector3 that the rotation should be copied to.
  61155. */
  61156. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  61157. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61158. if (mesh === void 0) { mesh = null; }
  61159. var quat = Bone._tmpQuat;
  61160. this.getRotationQuaternionToRef(space, mesh, quat);
  61161. quat.toEulerAnglesToRef(result);
  61162. };
  61163. /**
  61164. * Get the quaternion rotation of the bone in either local or world space.
  61165. * @param space The space that the rotation should be in.
  61166. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61167. * @returns The quaternion rotation
  61168. */
  61169. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  61170. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61171. if (mesh === void 0) { mesh = null; }
  61172. var result = BABYLON.Quaternion.Identity();
  61173. this.getRotationQuaternionToRef(space, mesh, result);
  61174. return result;
  61175. };
  61176. /**
  61177. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  61178. * @param space The space that the rotation should be in.
  61179. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61180. * @param result The quaternion that the rotation should be copied to.
  61181. */
  61182. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  61183. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61184. if (mesh === void 0) { mesh = null; }
  61185. if (space == BABYLON.Space.LOCAL) {
  61186. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61187. }
  61188. else {
  61189. var mat = Bone._tmpMats[0];
  61190. var amat = this.getAbsoluteTransform();
  61191. if (mesh) {
  61192. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61193. }
  61194. else {
  61195. mat.copyFrom(amat);
  61196. }
  61197. mat.m[0] *= this._scalingDeterminant;
  61198. mat.m[1] *= this._scalingDeterminant;
  61199. mat.m[2] *= this._scalingDeterminant;
  61200. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61201. }
  61202. };
  61203. /**
  61204. * Get the rotation matrix of the bone in local or world space.
  61205. * @param space The space that the rotation should be in.
  61206. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61207. * @returns The rotation matrix
  61208. */
  61209. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61210. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61211. var result = BABYLON.Matrix.Identity();
  61212. this.getRotationMatrixToRef(space, mesh, result);
  61213. return result;
  61214. };
  61215. /**
  61216. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61217. * @param space The space that the rotation should be in.
  61218. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61219. * @param result The quaternion that the rotation should be copied to.
  61220. */
  61221. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61222. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61223. if (space == BABYLON.Space.LOCAL) {
  61224. this.getLocalMatrix().getRotationMatrixToRef(result);
  61225. }
  61226. else {
  61227. var mat = Bone._tmpMats[0];
  61228. var amat = this.getAbsoluteTransform();
  61229. if (mesh) {
  61230. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61231. }
  61232. else {
  61233. mat.copyFrom(amat);
  61234. }
  61235. mat.m[0] *= this._scalingDeterminant;
  61236. mat.m[1] *= this._scalingDeterminant;
  61237. mat.m[2] *= this._scalingDeterminant;
  61238. mat.getRotationMatrixToRef(result);
  61239. }
  61240. };
  61241. /**
  61242. * Get the world position of a point that is in the local space of the bone.
  61243. * @param position The local position
  61244. * @param mesh The mesh that this bone is attached to.
  61245. * @returns The world position
  61246. */
  61247. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61248. if (mesh === void 0) { mesh = null; }
  61249. var result = BABYLON.Vector3.Zero();
  61250. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61251. return result;
  61252. };
  61253. /**
  61254. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61255. * @param position The local position
  61256. * @param mesh The mesh that this bone is attached to.
  61257. * @param result The vector3 that the world position should be copied to.
  61258. */
  61259. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61260. if (mesh === void 0) { mesh = null; }
  61261. var wm = null;
  61262. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61263. if (mesh) {
  61264. wm = mesh.getWorldMatrix();
  61265. }
  61266. this._skeleton.computeAbsoluteTransforms();
  61267. var tmat = Bone._tmpMats[0];
  61268. if (mesh && wm) {
  61269. tmat.copyFrom(this.getAbsoluteTransform());
  61270. tmat.multiplyToRef(wm, tmat);
  61271. }
  61272. else {
  61273. tmat = this.getAbsoluteTransform();
  61274. }
  61275. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61276. };
  61277. /**
  61278. * Get the local position of a point that is in world space.
  61279. * @param position The world position
  61280. * @param mesh The mesh that this bone is attached to.
  61281. * @returns The local position
  61282. */
  61283. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61284. if (mesh === void 0) { mesh = null; }
  61285. var result = BABYLON.Vector3.Zero();
  61286. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61287. return result;
  61288. };
  61289. /**
  61290. * Get the local position of a point that is in world space and copy it to the result param.
  61291. * @param position The world position
  61292. * @param mesh The mesh that this bone is attached to.
  61293. * @param result The vector3 that the local position should be copied to.
  61294. */
  61295. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61296. if (mesh === void 0) { mesh = null; }
  61297. var wm = null;
  61298. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61299. if (mesh) {
  61300. wm = mesh.getWorldMatrix();
  61301. }
  61302. this._skeleton.computeAbsoluteTransforms();
  61303. var tmat = Bone._tmpMats[0];
  61304. tmat.copyFrom(this.getAbsoluteTransform());
  61305. if (mesh && wm) {
  61306. tmat.multiplyToRef(wm, tmat);
  61307. }
  61308. tmat.invert();
  61309. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61310. };
  61311. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61312. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61313. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61314. return Bone;
  61315. }(BABYLON.Node));
  61316. BABYLON.Bone = Bone;
  61317. })(BABYLON || (BABYLON = {}));
  61318. //# sourceMappingURL=babylon.bone.js.map
  61319. var BABYLON;
  61320. (function (BABYLON) {
  61321. var BoneIKController = /** @class */ (function () {
  61322. function BoneIKController(mesh, bone, options) {
  61323. this.targetPosition = BABYLON.Vector3.Zero();
  61324. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61325. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61326. this.poleAngle = 0;
  61327. this.slerpAmount = 1;
  61328. this._bone1Quat = BABYLON.Quaternion.Identity();
  61329. this._bone1Mat = BABYLON.Matrix.Identity();
  61330. this._bone2Ang = Math.PI;
  61331. this._maxAngle = Math.PI;
  61332. this._rightHandedSystem = false;
  61333. this._bendAxis = BABYLON.Vector3.Right();
  61334. this._slerping = false;
  61335. this._adjustRoll = 0;
  61336. this._bone2 = bone;
  61337. this._bone1 = bone.getParent();
  61338. if (!this._bone1) {
  61339. return;
  61340. }
  61341. this.mesh = mesh;
  61342. var bonePos = bone.getPosition();
  61343. if (bone.getAbsoluteTransform().determinant() > 0) {
  61344. this._rightHandedSystem = true;
  61345. this._bendAxis.x = 0;
  61346. this._bendAxis.y = 0;
  61347. this._bendAxis.z = -1;
  61348. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61349. this._adjustRoll = Math.PI * .5;
  61350. this._bendAxis.z = 1;
  61351. }
  61352. }
  61353. if (this._bone1.length) {
  61354. var boneScale1 = this._bone1.getScale();
  61355. var boneScale2 = this._bone2.getScale();
  61356. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61357. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61358. }
  61359. else if (this._bone1.children[0]) {
  61360. mesh.computeWorldMatrix(true);
  61361. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61362. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61363. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61364. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61365. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61366. }
  61367. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61368. this.maxAngle = Math.PI;
  61369. if (options) {
  61370. if (options.targetMesh) {
  61371. this.targetMesh = options.targetMesh;
  61372. this.targetMesh.computeWorldMatrix(true);
  61373. }
  61374. if (options.poleTargetMesh) {
  61375. this.poleTargetMesh = options.poleTargetMesh;
  61376. this.poleTargetMesh.computeWorldMatrix(true);
  61377. }
  61378. else if (options.poleTargetBone) {
  61379. this.poleTargetBone = options.poleTargetBone;
  61380. }
  61381. else if (this._bone1.getParent()) {
  61382. this.poleTargetBone = this._bone1.getParent();
  61383. }
  61384. if (options.poleTargetLocalOffset) {
  61385. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61386. }
  61387. if (options.poleAngle) {
  61388. this.poleAngle = options.poleAngle;
  61389. }
  61390. if (options.bendAxis) {
  61391. this._bendAxis.copyFrom(options.bendAxis);
  61392. }
  61393. if (options.maxAngle) {
  61394. this.maxAngle = options.maxAngle;
  61395. }
  61396. if (options.slerpAmount) {
  61397. this.slerpAmount = options.slerpAmount;
  61398. }
  61399. }
  61400. }
  61401. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61402. get: function () {
  61403. return this._maxAngle;
  61404. },
  61405. set: function (value) {
  61406. this._setMaxAngle(value);
  61407. },
  61408. enumerable: true,
  61409. configurable: true
  61410. });
  61411. BoneIKController.prototype._setMaxAngle = function (ang) {
  61412. if (ang < 0) {
  61413. ang = 0;
  61414. }
  61415. if (ang > Math.PI || ang == undefined) {
  61416. ang = Math.PI;
  61417. }
  61418. this._maxAngle = ang;
  61419. var a = this._bone1Length;
  61420. var b = this._bone2Length;
  61421. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61422. };
  61423. BoneIKController.prototype.update = function () {
  61424. var bone1 = this._bone1;
  61425. if (!bone1) {
  61426. return;
  61427. }
  61428. var target = this.targetPosition;
  61429. var poleTarget = this.poleTargetPosition;
  61430. var mat1 = BoneIKController._tmpMats[0];
  61431. var mat2 = BoneIKController._tmpMats[1];
  61432. if (this.targetMesh) {
  61433. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61434. }
  61435. if (this.poleTargetBone) {
  61436. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61437. }
  61438. else if (this.poleTargetMesh) {
  61439. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61440. }
  61441. var bonePos = BoneIKController._tmpVecs[0];
  61442. var zaxis = BoneIKController._tmpVecs[1];
  61443. var xaxis = BoneIKController._tmpVecs[2];
  61444. var yaxis = BoneIKController._tmpVecs[3];
  61445. var upAxis = BoneIKController._tmpVecs[4];
  61446. var _tmpQuat = BoneIKController._tmpQuat;
  61447. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61448. poleTarget.subtractToRef(bonePos, upAxis);
  61449. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61450. upAxis.y = 1;
  61451. }
  61452. else {
  61453. upAxis.normalize();
  61454. }
  61455. target.subtractToRef(bonePos, yaxis);
  61456. yaxis.normalize();
  61457. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61458. zaxis.normalize();
  61459. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61460. xaxis.normalize();
  61461. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61462. var a = this._bone1Length;
  61463. var b = this._bone2Length;
  61464. var c = BABYLON.Vector3.Distance(bonePos, target);
  61465. if (this._maxReach > 0) {
  61466. c = Math.min(this._maxReach, c);
  61467. }
  61468. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61469. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61470. if (acosa > 1) {
  61471. acosa = 1;
  61472. }
  61473. if (acosb > 1) {
  61474. acosb = 1;
  61475. }
  61476. if (acosa < -1) {
  61477. acosa = -1;
  61478. }
  61479. if (acosb < -1) {
  61480. acosb = -1;
  61481. }
  61482. var angA = Math.acos(acosa);
  61483. var angB = Math.acos(acosb);
  61484. var angC = -angA - angB;
  61485. if (this._rightHandedSystem) {
  61486. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61487. mat2.multiplyToRef(mat1, mat1);
  61488. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61489. mat2.multiplyToRef(mat1, mat1);
  61490. }
  61491. else {
  61492. var _tmpVec = BoneIKController._tmpVecs[5];
  61493. _tmpVec.copyFrom(this._bendAxis);
  61494. _tmpVec.x *= -1;
  61495. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61496. mat2.multiplyToRef(mat1, mat1);
  61497. }
  61498. if (this.poleAngle) {
  61499. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61500. mat1.multiplyToRef(mat2, mat1);
  61501. }
  61502. if (this._bone1) {
  61503. if (this.slerpAmount < 1) {
  61504. if (!this._slerping) {
  61505. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61506. }
  61507. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61508. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61509. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61510. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61511. this._slerping = true;
  61512. }
  61513. else {
  61514. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61515. this._bone1Mat.copyFrom(mat1);
  61516. this._slerping = false;
  61517. }
  61518. }
  61519. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61520. this._bone2Ang = angC;
  61521. };
  61522. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61523. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61524. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61525. return BoneIKController;
  61526. }());
  61527. BABYLON.BoneIKController = BoneIKController;
  61528. })(BABYLON || (BABYLON = {}));
  61529. //# sourceMappingURL=babylon.boneIKController.js.map
  61530. var BABYLON;
  61531. (function (BABYLON) {
  61532. var BoneLookController = /** @class */ (function () {
  61533. /**
  61534. * Create a BoneLookController
  61535. * @param mesh the mesh that the bone belongs to
  61536. * @param bone the bone that will be looking to the target
  61537. * @param target the target Vector3 to look at
  61538. * @param settings optional settings:
  61539. * - maxYaw: the maximum angle the bone will yaw to
  61540. * - minYaw: the minimum angle the bone will yaw to
  61541. * - maxPitch: the maximum angle the bone will pitch to
  61542. * - minPitch: the minimum angle the bone will yaw to
  61543. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61544. * - upAxis: the up axis of the coordinate system
  61545. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61546. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61547. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61548. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61549. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61550. * - adjustRoll: used to make an adjustment to the roll of the bone
  61551. **/
  61552. function BoneLookController(mesh, bone, target, options) {
  61553. /**
  61554. * The up axis of the coordinate system that is used when the bone is rotated.
  61555. */
  61556. this.upAxis = BABYLON.Vector3.Up();
  61557. /**
  61558. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61559. */
  61560. this.upAxisSpace = BABYLON.Space.LOCAL;
  61561. /**
  61562. * Used to make an adjustment to the yaw of the bone.
  61563. */
  61564. this.adjustYaw = 0;
  61565. /**
  61566. * Used to make an adjustment to the pitch of the bone.
  61567. */
  61568. this.adjustPitch = 0;
  61569. /**
  61570. * Used to make an adjustment to the roll of the bone.
  61571. */
  61572. this.adjustRoll = 0;
  61573. /**
  61574. * 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).
  61575. */
  61576. this.slerpAmount = 1;
  61577. this._boneQuat = BABYLON.Quaternion.Identity();
  61578. this._slerping = false;
  61579. this._firstFrameSkipped = false;
  61580. this._fowardAxis = BABYLON.Vector3.Forward();
  61581. this.mesh = mesh;
  61582. this.bone = bone;
  61583. this.target = target;
  61584. if (options) {
  61585. if (options.adjustYaw) {
  61586. this.adjustYaw = options.adjustYaw;
  61587. }
  61588. if (options.adjustPitch) {
  61589. this.adjustPitch = options.adjustPitch;
  61590. }
  61591. if (options.adjustRoll) {
  61592. this.adjustRoll = options.adjustRoll;
  61593. }
  61594. if (options.maxYaw != null) {
  61595. this.maxYaw = options.maxYaw;
  61596. }
  61597. else {
  61598. this.maxYaw = Math.PI;
  61599. }
  61600. if (options.minYaw != null) {
  61601. this.minYaw = options.minYaw;
  61602. }
  61603. else {
  61604. this.minYaw = -Math.PI;
  61605. }
  61606. if (options.maxPitch != null) {
  61607. this.maxPitch = options.maxPitch;
  61608. }
  61609. else {
  61610. this.maxPitch = Math.PI;
  61611. }
  61612. if (options.minPitch != null) {
  61613. this.minPitch = options.minPitch;
  61614. }
  61615. else {
  61616. this.minPitch = -Math.PI;
  61617. }
  61618. if (options.slerpAmount != null) {
  61619. this.slerpAmount = options.slerpAmount;
  61620. }
  61621. if (options.upAxis != null) {
  61622. this.upAxis = options.upAxis;
  61623. }
  61624. if (options.upAxisSpace != null) {
  61625. this.upAxisSpace = options.upAxisSpace;
  61626. }
  61627. if (options.yawAxis != null || options.pitchAxis != null) {
  61628. var newYawAxis = BABYLON.Axis.Y;
  61629. var newPitchAxis = BABYLON.Axis.X;
  61630. if (options.yawAxis != null) {
  61631. newYawAxis = options.yawAxis.clone();
  61632. newYawAxis.normalize();
  61633. }
  61634. if (options.pitchAxis != null) {
  61635. newPitchAxis = options.pitchAxis.clone();
  61636. newPitchAxis.normalize();
  61637. }
  61638. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61639. this._transformYawPitch = BABYLON.Matrix.Identity();
  61640. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61641. this._transformYawPitchInv = this._transformYawPitch.clone();
  61642. this._transformYawPitch.invert();
  61643. }
  61644. }
  61645. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61646. this.upAxisSpace = BABYLON.Space.LOCAL;
  61647. }
  61648. }
  61649. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61650. /**
  61651. * Get/set the minimum yaw angle that the bone can look to.
  61652. */
  61653. get: function () {
  61654. return this._minYaw;
  61655. },
  61656. set: function (value) {
  61657. this._minYaw = value;
  61658. this._minYawSin = Math.sin(value);
  61659. this._minYawCos = Math.cos(value);
  61660. if (this._maxYaw != null) {
  61661. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61662. this._yawRange = this._maxYaw - this._minYaw;
  61663. }
  61664. },
  61665. enumerable: true,
  61666. configurable: true
  61667. });
  61668. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61669. /**
  61670. * Get/set the maximum yaw angle that the bone can look to.
  61671. */
  61672. get: function () {
  61673. return this._maxYaw;
  61674. },
  61675. set: function (value) {
  61676. this._maxYaw = value;
  61677. this._maxYawSin = Math.sin(value);
  61678. this._maxYawCos = Math.cos(value);
  61679. if (this._minYaw != null) {
  61680. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61681. this._yawRange = this._maxYaw - this._minYaw;
  61682. }
  61683. },
  61684. enumerable: true,
  61685. configurable: true
  61686. });
  61687. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61688. /**
  61689. * Get/set the minimum pitch angle that the bone can look to.
  61690. */
  61691. get: function () {
  61692. return this._minPitch;
  61693. },
  61694. set: function (value) {
  61695. this._minPitch = value;
  61696. this._minPitchTan = Math.tan(value);
  61697. },
  61698. enumerable: true,
  61699. configurable: true
  61700. });
  61701. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61702. /**
  61703. * Get/set the maximum pitch angle that the bone can look to.
  61704. */
  61705. get: function () {
  61706. return this._maxPitch;
  61707. },
  61708. set: function (value) {
  61709. this._maxPitch = value;
  61710. this._maxPitchTan = Math.tan(value);
  61711. },
  61712. enumerable: true,
  61713. configurable: true
  61714. });
  61715. /**
  61716. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61717. */
  61718. BoneLookController.prototype.update = function () {
  61719. //skip the first frame when slerping so that the mesh rotation is correct
  61720. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61721. this._firstFrameSkipped = true;
  61722. return;
  61723. }
  61724. var bone = this.bone;
  61725. var bonePos = BoneLookController._tmpVecs[0];
  61726. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61727. var target = this.target;
  61728. var _tmpMat1 = BoneLookController._tmpMats[0];
  61729. var _tmpMat2 = BoneLookController._tmpMats[1];
  61730. var mesh = this.mesh;
  61731. var parentBone = bone.getParent();
  61732. var upAxis = BoneLookController._tmpVecs[1];
  61733. upAxis.copyFrom(this.upAxis);
  61734. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61735. if (this._transformYawPitch) {
  61736. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61737. }
  61738. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61739. }
  61740. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61741. mesh.getDirectionToRef(upAxis, upAxis);
  61742. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61743. upAxis.normalize();
  61744. }
  61745. }
  61746. var checkYaw = false;
  61747. var checkPitch = false;
  61748. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61749. checkYaw = true;
  61750. }
  61751. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61752. checkPitch = true;
  61753. }
  61754. if (checkYaw || checkPitch) {
  61755. var spaceMat = BoneLookController._tmpMats[2];
  61756. var spaceMatInv = BoneLookController._tmpMats[3];
  61757. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61758. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61759. }
  61760. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61761. spaceMat.copyFrom(mesh.getWorldMatrix());
  61762. }
  61763. else {
  61764. var forwardAxis = BoneLookController._tmpVecs[2];
  61765. forwardAxis.copyFrom(this._fowardAxis);
  61766. if (this._transformYawPitch) {
  61767. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61768. }
  61769. if (parentBone) {
  61770. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61771. }
  61772. else {
  61773. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61774. }
  61775. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61776. rightAxis.normalize();
  61777. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61778. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61779. }
  61780. spaceMat.invertToRef(spaceMatInv);
  61781. var xzlen = null;
  61782. if (checkPitch) {
  61783. var localTarget = BoneLookController._tmpVecs[3];
  61784. target.subtractToRef(bonePos, localTarget);
  61785. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61786. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61787. var pitch = Math.atan2(localTarget.y, xzlen);
  61788. var newPitch = pitch;
  61789. if (pitch > this._maxPitch) {
  61790. localTarget.y = this._maxPitchTan * xzlen;
  61791. newPitch = this._maxPitch;
  61792. }
  61793. else if (pitch < this._minPitch) {
  61794. localTarget.y = this._minPitchTan * xzlen;
  61795. newPitch = this._minPitch;
  61796. }
  61797. if (pitch != newPitch) {
  61798. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61799. localTarget.addInPlace(bonePos);
  61800. target = localTarget;
  61801. }
  61802. }
  61803. if (checkYaw) {
  61804. var localTarget = BoneLookController._tmpVecs[4];
  61805. target.subtractToRef(bonePos, localTarget);
  61806. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61807. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61808. var newYaw = yaw;
  61809. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61810. if (xzlen == null) {
  61811. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61812. }
  61813. if (this._yawRange > Math.PI) {
  61814. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61815. localTarget.z = this._maxYawCos * xzlen;
  61816. localTarget.x = this._maxYawSin * xzlen;
  61817. newYaw = this._maxYaw;
  61818. }
  61819. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61820. localTarget.z = this._minYawCos * xzlen;
  61821. localTarget.x = this._minYawSin * xzlen;
  61822. newYaw = this._minYaw;
  61823. }
  61824. }
  61825. else {
  61826. if (yaw > this._maxYaw) {
  61827. localTarget.z = this._maxYawCos * xzlen;
  61828. localTarget.x = this._maxYawSin * xzlen;
  61829. newYaw = this._maxYaw;
  61830. }
  61831. else if (yaw < this._minYaw) {
  61832. localTarget.z = this._minYawCos * xzlen;
  61833. localTarget.x = this._minYawSin * xzlen;
  61834. newYaw = this._minYaw;
  61835. }
  61836. }
  61837. }
  61838. if (this._slerping && this._yawRange > Math.PI) {
  61839. //are we going to be crossing into the min/max region?
  61840. var boneFwd = BoneLookController._tmpVecs[8];
  61841. boneFwd.copyFrom(BABYLON.Axis.Z);
  61842. if (this._transformYawPitch) {
  61843. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61844. }
  61845. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61846. this._boneQuat.toRotationMatrix(boneRotMat);
  61847. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  61848. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  61849. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  61850. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  61851. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  61852. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  61853. if (angBtwTar > angBtwMidYaw) {
  61854. if (xzlen == null) {
  61855. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61856. }
  61857. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  61858. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  61859. if (angBtwMin < angBtwMax) {
  61860. newYaw = boneYaw + Math.PI * .75;
  61861. localTarget.z = Math.cos(newYaw) * xzlen;
  61862. localTarget.x = Math.sin(newYaw) * xzlen;
  61863. }
  61864. else {
  61865. newYaw = boneYaw - Math.PI * .75;
  61866. localTarget.z = Math.cos(newYaw) * xzlen;
  61867. localTarget.x = Math.sin(newYaw) * xzlen;
  61868. }
  61869. }
  61870. }
  61871. if (yaw != newYaw) {
  61872. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61873. localTarget.addInPlace(bonePos);
  61874. target = localTarget;
  61875. }
  61876. }
  61877. }
  61878. var zaxis = BoneLookController._tmpVecs[5];
  61879. var xaxis = BoneLookController._tmpVecs[6];
  61880. var yaxis = BoneLookController._tmpVecs[7];
  61881. var _tmpQuat = BoneLookController._tmpQuat;
  61882. target.subtractToRef(bonePos, zaxis);
  61883. zaxis.normalize();
  61884. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  61885. xaxis.normalize();
  61886. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  61887. yaxis.normalize();
  61888. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  61889. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  61890. return;
  61891. }
  61892. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  61893. return;
  61894. }
  61895. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  61896. return;
  61897. }
  61898. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  61899. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  61900. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  61901. }
  61902. if (this.slerpAmount < 1) {
  61903. if (!this._slerping) {
  61904. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  61905. }
  61906. if (this._transformYawPitch) {
  61907. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61908. }
  61909. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  61910. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  61911. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  61912. this._slerping = true;
  61913. }
  61914. else {
  61915. if (this._transformYawPitch) {
  61916. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61917. }
  61918. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  61919. this._slerping = false;
  61920. }
  61921. };
  61922. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  61923. var angDiff = ang2 - ang1;
  61924. angDiff %= Math.PI * 2;
  61925. if (angDiff > Math.PI) {
  61926. angDiff -= Math.PI * 2;
  61927. }
  61928. else if (angDiff < -Math.PI) {
  61929. angDiff += Math.PI * 2;
  61930. }
  61931. return angDiff;
  61932. };
  61933. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  61934. ang1 %= (2 * Math.PI);
  61935. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61936. ang2 %= (2 * Math.PI);
  61937. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61938. var ab = 0;
  61939. if (ang1 < ang2) {
  61940. ab = ang2 - ang1;
  61941. }
  61942. else {
  61943. ab = ang1 - ang2;
  61944. }
  61945. if (ab > Math.PI) {
  61946. ab = Math.PI * 2 - ab;
  61947. }
  61948. return ab;
  61949. };
  61950. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  61951. ang %= (2 * Math.PI);
  61952. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  61953. ang1 %= (2 * Math.PI);
  61954. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61955. ang2 %= (2 * Math.PI);
  61956. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61957. if (ang1 < ang2) {
  61958. if (ang > ang1 && ang < ang2) {
  61959. return true;
  61960. }
  61961. }
  61962. else {
  61963. if (ang > ang2 && ang < ang1) {
  61964. return true;
  61965. }
  61966. }
  61967. return false;
  61968. };
  61969. 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()];
  61970. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  61971. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61972. return BoneLookController;
  61973. }());
  61974. BABYLON.BoneLookController = BoneLookController;
  61975. })(BABYLON || (BABYLON = {}));
  61976. //# sourceMappingURL=babylon.boneLookController.js.map
  61977. var BABYLON;
  61978. (function (BABYLON) {
  61979. var Skeleton = /** @class */ (function () {
  61980. function Skeleton(name, id, scene) {
  61981. this.name = name;
  61982. this.id = id;
  61983. this.bones = new Array();
  61984. this.needInitialSkinMatrix = false;
  61985. this._isDirty = true;
  61986. this._meshesWithPoseMatrix = new Array();
  61987. this._identity = BABYLON.Matrix.Identity();
  61988. this._ranges = {};
  61989. this._lastAbsoluteTransformsUpdateId = -1;
  61990. // Events
  61991. /**
  61992. * An event triggered before computing the skeleton's matrices
  61993. * @type {BABYLON.Observable}
  61994. */
  61995. this.onBeforeComputeObservable = new BABYLON.Observable();
  61996. this.bones = [];
  61997. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61998. scene.skeletons.push(this);
  61999. //make sure it will recalculate the matrix next time prepare is called.
  62000. this._isDirty = true;
  62001. }
  62002. // Members
  62003. Skeleton.prototype.getTransformMatrices = function (mesh) {
  62004. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  62005. return mesh._bonesTransformMatrices;
  62006. }
  62007. if (!this._transformMatrices) {
  62008. this.prepare();
  62009. }
  62010. return this._transformMatrices;
  62011. };
  62012. Skeleton.prototype.getScene = function () {
  62013. return this._scene;
  62014. };
  62015. // Methods
  62016. /**
  62017. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  62018. */
  62019. Skeleton.prototype.toString = function (fullDetails) {
  62020. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  62021. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  62022. if (fullDetails) {
  62023. ret += ", Ranges: {";
  62024. var first = true;
  62025. for (var name_1 in this._ranges) {
  62026. if (first) {
  62027. ret += ", ";
  62028. first = false;
  62029. }
  62030. ret += name_1;
  62031. }
  62032. ret += "}";
  62033. }
  62034. return ret;
  62035. };
  62036. /**
  62037. * Get bone's index searching by name
  62038. * @param {string} name is bone's name to search for
  62039. * @return {number} Indice of the bone. Returns -1 if not found
  62040. */
  62041. Skeleton.prototype.getBoneIndexByName = function (name) {
  62042. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  62043. if (this.bones[boneIndex].name === name) {
  62044. return boneIndex;
  62045. }
  62046. }
  62047. return -1;
  62048. };
  62049. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  62050. // check name not already in use
  62051. if (!this._ranges[name]) {
  62052. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  62053. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62054. if (this.bones[i].animations[0]) {
  62055. this.bones[i].animations[0].createRange(name, from, to);
  62056. }
  62057. }
  62058. }
  62059. };
  62060. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  62061. if (deleteFrames === void 0) { deleteFrames = true; }
  62062. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62063. if (this.bones[i].animations[0]) {
  62064. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  62065. }
  62066. }
  62067. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  62068. };
  62069. Skeleton.prototype.getAnimationRange = function (name) {
  62070. return this._ranges[name];
  62071. };
  62072. /**
  62073. * Returns as an Array, all AnimationRanges defined on this skeleton
  62074. */
  62075. Skeleton.prototype.getAnimationRanges = function () {
  62076. var animationRanges = [];
  62077. var name;
  62078. var i = 0;
  62079. for (name in this._ranges) {
  62080. animationRanges[i] = this._ranges[name];
  62081. i++;
  62082. }
  62083. return animationRanges;
  62084. };
  62085. /**
  62086. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  62087. */
  62088. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  62089. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62090. if (this._ranges[name] || !source.getAnimationRange(name)) {
  62091. return false;
  62092. }
  62093. var ret = true;
  62094. var frameOffset = this._getHighestAnimationFrame() + 1;
  62095. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  62096. var boneDict = {};
  62097. var sourceBones = source.bones;
  62098. var nBones;
  62099. var i;
  62100. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  62101. boneDict[sourceBones[i].name] = sourceBones[i];
  62102. }
  62103. if (this.bones.length !== sourceBones.length) {
  62104. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  62105. ret = false;
  62106. }
  62107. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  62108. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  62109. var boneName = this.bones[i].name;
  62110. var sourceBone = boneDict[boneName];
  62111. if (sourceBone) {
  62112. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  62113. }
  62114. else {
  62115. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  62116. ret = false;
  62117. }
  62118. }
  62119. // do not call createAnimationRange(), since it also is done to bones, which was already done
  62120. var range = source.getAnimationRange(name);
  62121. if (range) {
  62122. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62123. }
  62124. return ret;
  62125. };
  62126. Skeleton.prototype.returnToRest = function () {
  62127. for (var index = 0; index < this.bones.length; index++) {
  62128. this.bones[index].returnToRest();
  62129. }
  62130. };
  62131. Skeleton.prototype._getHighestAnimationFrame = function () {
  62132. var ret = 0;
  62133. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62134. if (this.bones[i].animations[0]) {
  62135. var highest = this.bones[i].animations[0].getHighestFrame();
  62136. if (ret < highest) {
  62137. ret = highest;
  62138. }
  62139. }
  62140. }
  62141. return ret;
  62142. };
  62143. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62144. var range = this.getAnimationRange(name);
  62145. if (!range) {
  62146. return null;
  62147. }
  62148. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  62149. };
  62150. Skeleton.prototype._markAsDirty = function () {
  62151. this._isDirty = true;
  62152. };
  62153. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  62154. this._meshesWithPoseMatrix.push(mesh);
  62155. };
  62156. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  62157. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  62158. if (index > -1) {
  62159. this._meshesWithPoseMatrix.splice(index, 1);
  62160. }
  62161. };
  62162. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  62163. this.onBeforeComputeObservable.notifyObservers(this);
  62164. for (var index = 0; index < this.bones.length; index++) {
  62165. var bone = this.bones[index];
  62166. var parentBone = bone.getParent();
  62167. if (parentBone) {
  62168. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  62169. }
  62170. else {
  62171. if (initialSkinMatrix) {
  62172. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  62173. }
  62174. else {
  62175. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  62176. }
  62177. }
  62178. if (bone._index !== -1) {
  62179. var mappedIndex = bone._index === null ? index : bone._index;
  62180. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  62181. }
  62182. }
  62183. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  62184. };
  62185. Skeleton.prototype.prepare = function () {
  62186. if (!this._isDirty) {
  62187. return;
  62188. }
  62189. if (this.needInitialSkinMatrix) {
  62190. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  62191. var mesh = this._meshesWithPoseMatrix[index];
  62192. var poseMatrix = mesh.getPoseMatrix();
  62193. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  62194. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62195. }
  62196. if (this._synchronizedWithMesh !== mesh) {
  62197. this._synchronizedWithMesh = mesh;
  62198. // Prepare bones
  62199. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  62200. var bone = this.bones[boneIndex];
  62201. if (!bone.getParent()) {
  62202. var matrix = bone.getBaseMatrix();
  62203. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  62204. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  62205. }
  62206. }
  62207. }
  62208. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62209. }
  62210. }
  62211. else {
  62212. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62213. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62214. }
  62215. this._computeTransformMatrices(this._transformMatrices, null);
  62216. }
  62217. this._isDirty = false;
  62218. this._scene._activeBones.addCount(this.bones.length, false);
  62219. };
  62220. Skeleton.prototype.getAnimatables = function () {
  62221. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62222. this._animatables = [];
  62223. for (var index = 0; index < this.bones.length; index++) {
  62224. this._animatables.push(this.bones[index]);
  62225. }
  62226. }
  62227. return this._animatables;
  62228. };
  62229. Skeleton.prototype.clone = function (name, id) {
  62230. var result = new Skeleton(name, id || name, this._scene);
  62231. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62232. for (var index = 0; index < this.bones.length; index++) {
  62233. var source = this.bones[index];
  62234. var parentBone = null;
  62235. var parent_1 = source.getParent();
  62236. if (parent_1) {
  62237. var parentIndex = this.bones.indexOf(parent_1);
  62238. parentBone = result.bones[parentIndex];
  62239. }
  62240. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62241. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62242. }
  62243. if (this._ranges) {
  62244. result._ranges = {};
  62245. for (var rangeName in this._ranges) {
  62246. var range = this._ranges[rangeName];
  62247. if (range) {
  62248. result._ranges[rangeName] = range.clone();
  62249. }
  62250. }
  62251. }
  62252. this._isDirty = true;
  62253. return result;
  62254. };
  62255. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62256. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62257. this.bones.forEach(function (bone) {
  62258. bone.animations.forEach(function (animation) {
  62259. animation.enableBlending = true;
  62260. animation.blendingSpeed = blendingSpeed;
  62261. });
  62262. });
  62263. };
  62264. Skeleton.prototype.dispose = function () {
  62265. this._meshesWithPoseMatrix = [];
  62266. // Animations
  62267. this.getScene().stopAnimation(this);
  62268. // Remove from scene
  62269. this.getScene().removeSkeleton(this);
  62270. };
  62271. Skeleton.prototype.serialize = function () {
  62272. var serializationObject = {};
  62273. serializationObject.name = this.name;
  62274. serializationObject.id = this.id;
  62275. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62276. serializationObject.bones = [];
  62277. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62278. for (var index = 0; index < this.bones.length; index++) {
  62279. var bone = this.bones[index];
  62280. var parent_2 = bone.getParent();
  62281. var serializedBone = {
  62282. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62283. name: bone.name,
  62284. matrix: bone.getBaseMatrix().toArray(),
  62285. rest: bone.getRestPose().toArray()
  62286. };
  62287. serializationObject.bones.push(serializedBone);
  62288. if (bone.length) {
  62289. serializedBone.length = bone.length;
  62290. }
  62291. if (bone.animations && bone.animations.length > 0) {
  62292. serializedBone.animation = bone.animations[0].serialize();
  62293. }
  62294. serializationObject.ranges = [];
  62295. for (var name in this._ranges) {
  62296. var source = this._ranges[name];
  62297. if (!source) {
  62298. continue;
  62299. }
  62300. var range = {};
  62301. range.name = name;
  62302. range.from = source.from;
  62303. range.to = source.to;
  62304. serializationObject.ranges.push(range);
  62305. }
  62306. }
  62307. return serializationObject;
  62308. };
  62309. Skeleton.Parse = function (parsedSkeleton, scene) {
  62310. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62311. if (parsedSkeleton.dimensionsAtRest) {
  62312. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62313. }
  62314. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62315. var index;
  62316. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62317. var parsedBone = parsedSkeleton.bones[index];
  62318. var parentBone = null;
  62319. if (parsedBone.parentBoneIndex > -1) {
  62320. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62321. }
  62322. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62323. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62324. if (parsedBone.length) {
  62325. bone.length = parsedBone.length;
  62326. }
  62327. if (parsedBone.animation) {
  62328. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62329. }
  62330. }
  62331. // placed after bones, so createAnimationRange can cascade down
  62332. if (parsedSkeleton.ranges) {
  62333. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62334. var data = parsedSkeleton.ranges[index];
  62335. skeleton.createAnimationRange(data.name, data.from, data.to);
  62336. }
  62337. }
  62338. return skeleton;
  62339. };
  62340. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62341. if (forceUpdate === void 0) { forceUpdate = false; }
  62342. var renderId = this._scene.getRenderId();
  62343. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62344. this.bones[0].computeAbsoluteTransforms();
  62345. this._lastAbsoluteTransformsUpdateId = renderId;
  62346. }
  62347. };
  62348. Skeleton.prototype.getPoseMatrix = function () {
  62349. var poseMatrix = null;
  62350. if (this._meshesWithPoseMatrix.length > 0) {
  62351. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62352. }
  62353. return poseMatrix;
  62354. };
  62355. Skeleton.prototype.sortBones = function () {
  62356. var bones = new Array();
  62357. var visited = new Array(this.bones.length);
  62358. for (var index = 0; index < this.bones.length; index++) {
  62359. this._sortBones(index, bones, visited);
  62360. }
  62361. this.bones = bones;
  62362. };
  62363. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62364. if (visited[index]) {
  62365. return;
  62366. }
  62367. visited[index] = true;
  62368. var bone = this.bones[index];
  62369. if (bone._index === undefined) {
  62370. bone._index = index;
  62371. }
  62372. var parentBone = bone.getParent();
  62373. if (parentBone) {
  62374. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62375. }
  62376. bones.push(bone);
  62377. };
  62378. return Skeleton;
  62379. }());
  62380. BABYLON.Skeleton = Skeleton;
  62381. })(BABYLON || (BABYLON = {}));
  62382. //# sourceMappingURL=babylon.skeleton.js.map
  62383. var BABYLON;
  62384. (function (BABYLON) {
  62385. var SphericalPolynomial = /** @class */ (function () {
  62386. function SphericalPolynomial() {
  62387. this.x = BABYLON.Vector3.Zero();
  62388. this.y = BABYLON.Vector3.Zero();
  62389. this.z = BABYLON.Vector3.Zero();
  62390. this.xx = BABYLON.Vector3.Zero();
  62391. this.yy = BABYLON.Vector3.Zero();
  62392. this.zz = BABYLON.Vector3.Zero();
  62393. this.xy = BABYLON.Vector3.Zero();
  62394. this.yz = BABYLON.Vector3.Zero();
  62395. this.zx = BABYLON.Vector3.Zero();
  62396. }
  62397. SphericalPolynomial.prototype.addAmbient = function (color) {
  62398. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62399. this.xx = this.xx.add(colorVector);
  62400. this.yy = this.yy.add(colorVector);
  62401. this.zz = this.zz.add(colorVector);
  62402. };
  62403. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62404. var result = new SphericalPolynomial();
  62405. result.x = harmonics.L11.scale(1.02333);
  62406. result.y = harmonics.L1_1.scale(1.02333);
  62407. result.z = harmonics.L10.scale(1.02333);
  62408. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62409. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62410. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62411. result.yz = harmonics.L2_1.scale(0.858086);
  62412. result.zx = harmonics.L21.scale(0.858086);
  62413. result.xy = harmonics.L2_2.scale(0.858086);
  62414. result.scale(1.0 / Math.PI);
  62415. return result;
  62416. };
  62417. SphericalPolynomial.prototype.scale = function (scale) {
  62418. this.x = this.x.scale(scale);
  62419. this.y = this.y.scale(scale);
  62420. this.z = this.z.scale(scale);
  62421. this.xx = this.xx.scale(scale);
  62422. this.yy = this.yy.scale(scale);
  62423. this.zz = this.zz.scale(scale);
  62424. this.yz = this.yz.scale(scale);
  62425. this.zx = this.zx.scale(scale);
  62426. this.xy = this.xy.scale(scale);
  62427. };
  62428. return SphericalPolynomial;
  62429. }());
  62430. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62431. var SphericalHarmonics = /** @class */ (function () {
  62432. function SphericalHarmonics() {
  62433. this.L00 = BABYLON.Vector3.Zero();
  62434. this.L1_1 = BABYLON.Vector3.Zero();
  62435. this.L10 = BABYLON.Vector3.Zero();
  62436. this.L11 = BABYLON.Vector3.Zero();
  62437. this.L2_2 = BABYLON.Vector3.Zero();
  62438. this.L2_1 = BABYLON.Vector3.Zero();
  62439. this.L20 = BABYLON.Vector3.Zero();
  62440. this.L21 = BABYLON.Vector3.Zero();
  62441. this.L22 = BABYLON.Vector3.Zero();
  62442. }
  62443. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62444. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62445. var c = colorVector.scale(deltaSolidAngle);
  62446. this.L00 = this.L00.add(c.scale(0.282095));
  62447. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62448. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62449. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62450. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62451. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62452. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62453. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62454. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62455. };
  62456. SphericalHarmonics.prototype.scale = function (scale) {
  62457. this.L00 = this.L00.scale(scale);
  62458. this.L1_1 = this.L1_1.scale(scale);
  62459. this.L10 = this.L10.scale(scale);
  62460. this.L11 = this.L11.scale(scale);
  62461. this.L2_2 = this.L2_2.scale(scale);
  62462. this.L2_1 = this.L2_1.scale(scale);
  62463. this.L20 = this.L20.scale(scale);
  62464. this.L21 = this.L21.scale(scale);
  62465. this.L22 = this.L22.scale(scale);
  62466. };
  62467. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62468. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62469. //
  62470. // E_lm = A_l * L_lm
  62471. //
  62472. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62473. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62474. // the scaling factors are given in equation 9.
  62475. // Constant (Band 0)
  62476. this.L00 = this.L00.scale(3.141593);
  62477. // Linear (Band 1)
  62478. this.L1_1 = this.L1_1.scale(2.094395);
  62479. this.L10 = this.L10.scale(2.094395);
  62480. this.L11 = this.L11.scale(2.094395);
  62481. // Quadratic (Band 2)
  62482. this.L2_2 = this.L2_2.scale(0.785398);
  62483. this.L2_1 = this.L2_1.scale(0.785398);
  62484. this.L20 = this.L20.scale(0.785398);
  62485. this.L21 = this.L21.scale(0.785398);
  62486. this.L22 = this.L22.scale(0.785398);
  62487. };
  62488. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62489. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62490. // L = (1/pi) * E * rho
  62491. //
  62492. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62493. this.scale(1.0 / Math.PI);
  62494. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62495. // (The pixel shader must apply albedo after texture fetches, etc).
  62496. };
  62497. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62498. var result = new SphericalHarmonics();
  62499. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62500. result.L1_1 = polynomial.y.scale(0.977204);
  62501. result.L10 = polynomial.z.scale(0.977204);
  62502. result.L11 = polynomial.x.scale(0.977204);
  62503. result.L2_2 = polynomial.xy.scale(1.16538);
  62504. result.L2_1 = polynomial.yz.scale(1.16538);
  62505. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62506. result.L21 = polynomial.zx.scale(1.16538);
  62507. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62508. result.scale(Math.PI);
  62509. return result;
  62510. };
  62511. return SphericalHarmonics;
  62512. }());
  62513. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62514. })(BABYLON || (BABYLON = {}));
  62515. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62516. var BABYLON;
  62517. (function (BABYLON) {
  62518. var Internals;
  62519. (function (Internals) {
  62520. var FileFaceOrientation = /** @class */ (function () {
  62521. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62522. this.name = name;
  62523. this.worldAxisForNormal = worldAxisForNormal;
  62524. this.worldAxisForFileX = worldAxisForFileX;
  62525. this.worldAxisForFileY = worldAxisForFileY;
  62526. }
  62527. return FileFaceOrientation;
  62528. }());
  62529. ;
  62530. /**
  62531. * Helper class dealing with the extraction of spherical polynomial dataArray
  62532. * from a cube map.
  62533. */
  62534. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62535. function CubeMapToSphericalPolynomialTools() {
  62536. }
  62537. /**
  62538. * Converts a texture to the according Spherical Polynomial data.
  62539. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62540. *
  62541. * @param texture The texture to extract the information from.
  62542. * @return The Spherical Polynomial data.
  62543. */
  62544. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62545. if (!texture.isCube) {
  62546. // Only supports cube Textures currently.
  62547. return null;
  62548. }
  62549. var size = texture.getSize().width;
  62550. var right = texture.readPixels(0);
  62551. var left = texture.readPixels(1);
  62552. var up;
  62553. var down;
  62554. if (texture.isRenderTarget) {
  62555. up = texture.readPixels(3);
  62556. down = texture.readPixels(2);
  62557. }
  62558. else {
  62559. up = texture.readPixels(2);
  62560. down = texture.readPixels(3);
  62561. }
  62562. var front = texture.readPixels(4);
  62563. var back = texture.readPixels(5);
  62564. var gammaSpace = texture.gammaSpace;
  62565. // Always read as RGBA.
  62566. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62567. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62568. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62569. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62570. }
  62571. var cubeInfo = {
  62572. size: size,
  62573. right: right,
  62574. left: left,
  62575. up: up,
  62576. down: down,
  62577. front: front,
  62578. back: back,
  62579. format: format,
  62580. type: type,
  62581. gammaSpace: gammaSpace,
  62582. };
  62583. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62584. };
  62585. /**
  62586. * Converts a cubemap to the according Spherical Polynomial data.
  62587. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62588. *
  62589. * @param cubeInfo The Cube map to extract the information from.
  62590. * @return The Spherical Polynomial data.
  62591. */
  62592. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62593. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62594. var totalSolidAngle = 0.0;
  62595. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62596. var du = 2.0 / cubeInfo.size;
  62597. var dv = du;
  62598. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62599. var minUV = du * 0.5 - 1.0;
  62600. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62601. var fileFace = this.FileFaces[faceIndex];
  62602. var dataArray = cubeInfo[fileFace.name];
  62603. var v = minUV;
  62604. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62605. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62606. // Because SP is still linear, so summation is fine in that basis.
  62607. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62608. for (var y = 0; y < cubeInfo.size; y++) {
  62609. var u = minUV;
  62610. for (var x = 0; x < cubeInfo.size; x++) {
  62611. // World direction (not normalised)
  62612. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62613. worldDirection.normalize();
  62614. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62615. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62616. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62617. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62618. // Handle Integer types.
  62619. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62620. r /= 255;
  62621. g /= 255;
  62622. b /= 255;
  62623. }
  62624. // Handle Gamma space textures.
  62625. if (cubeInfo.gammaSpace) {
  62626. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62627. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62628. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62629. }
  62630. var color = new BABYLON.Color3(r, g, b);
  62631. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62632. totalSolidAngle += deltaSolidAngle;
  62633. u += du;
  62634. }
  62635. v += dv;
  62636. }
  62637. }
  62638. // Solid angle for entire sphere is 4*pi
  62639. var sphereSolidAngle = 4.0 * Math.PI;
  62640. // Adjust the solid angle to allow for how many faces we processed.
  62641. var facesProcessed = 6.0;
  62642. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62643. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62644. // This is needed because the numerical integration over the cube uses a
  62645. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62646. // and also to compensate for accumulative error due to float precision in the summation.
  62647. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62648. sphericalHarmonics.scale(correctionFactor);
  62649. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62650. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62651. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62652. };
  62653. CubeMapToSphericalPolynomialTools.FileFaces = [
  62654. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62655. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62656. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62657. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62658. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62659. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62660. ];
  62661. return CubeMapToSphericalPolynomialTools;
  62662. }());
  62663. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62664. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62665. })(BABYLON || (BABYLON = {}));
  62666. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62667. var BABYLON;
  62668. (function (BABYLON) {
  62669. var Internals;
  62670. (function (Internals) {
  62671. /**
  62672. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62673. */
  62674. var PanoramaToCubeMapTools = /** @class */ (function () {
  62675. function PanoramaToCubeMapTools() {
  62676. }
  62677. /**
  62678. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62679. *
  62680. * @param float32Array The source data.
  62681. * @param inputWidth The width of the input panorama.
  62682. * @param inputhHeight The height of the input panorama.
  62683. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62684. * @return The cubemap data
  62685. */
  62686. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62687. if (!float32Array) {
  62688. throw "ConvertPanoramaToCubemap: input cannot be null";
  62689. }
  62690. if (float32Array.length != inputWidth * inputHeight * 3) {
  62691. throw "ConvertPanoramaToCubemap: input size is wrong";
  62692. }
  62693. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62694. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62695. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62696. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62697. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62698. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62699. return {
  62700. front: textureFront,
  62701. back: textureBack,
  62702. left: textureLeft,
  62703. right: textureRight,
  62704. up: textureUp,
  62705. down: textureDown,
  62706. size: size,
  62707. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62708. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62709. gammaSpace: false,
  62710. };
  62711. };
  62712. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62713. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62714. var textureArray = new Float32Array(buffer);
  62715. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62716. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62717. var dy = 1 / texSize;
  62718. var fy = 0;
  62719. for (var y = 0; y < texSize; y++) {
  62720. var xv1 = faceData[0];
  62721. var xv2 = faceData[2];
  62722. for (var x = 0; x < texSize; x++) {
  62723. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62724. v.normalize();
  62725. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62726. // 3 channels per pixels
  62727. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62728. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62729. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62730. xv1 = xv1.add(rotDX1);
  62731. xv2 = xv2.add(rotDX2);
  62732. }
  62733. fy += dy;
  62734. }
  62735. return textureArray;
  62736. };
  62737. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62738. var theta = Math.atan2(vDir.z, vDir.x);
  62739. var phi = Math.acos(vDir.y);
  62740. while (theta < -Math.PI)
  62741. theta += 2 * Math.PI;
  62742. while (theta > Math.PI)
  62743. theta -= 2 * Math.PI;
  62744. var dx = theta / Math.PI;
  62745. var dy = phi / Math.PI;
  62746. // recenter.
  62747. dx = dx * 0.5 + 0.5;
  62748. var px = Math.round(dx * inputWidth);
  62749. if (px < 0)
  62750. px = 0;
  62751. else if (px >= inputWidth)
  62752. px = inputWidth - 1;
  62753. var py = Math.round(dy * inputHeight);
  62754. if (py < 0)
  62755. py = 0;
  62756. else if (py >= inputHeight)
  62757. py = inputHeight - 1;
  62758. var inputY = (inputHeight - py - 1);
  62759. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62760. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62761. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62762. return {
  62763. r: r,
  62764. g: g,
  62765. b: b
  62766. };
  62767. };
  62768. PanoramaToCubeMapTools.FACE_FRONT = [
  62769. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62770. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62771. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62772. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62773. ];
  62774. PanoramaToCubeMapTools.FACE_BACK = [
  62775. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62776. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62777. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62778. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62779. ];
  62780. PanoramaToCubeMapTools.FACE_RIGHT = [
  62781. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62782. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62783. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62784. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62785. ];
  62786. PanoramaToCubeMapTools.FACE_LEFT = [
  62787. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62788. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62789. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62790. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62791. ];
  62792. PanoramaToCubeMapTools.FACE_DOWN = [
  62793. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62794. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62795. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62796. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62797. ];
  62798. PanoramaToCubeMapTools.FACE_UP = [
  62799. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62800. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62801. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62802. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62803. ];
  62804. return PanoramaToCubeMapTools;
  62805. }());
  62806. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62807. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62808. })(BABYLON || (BABYLON = {}));
  62809. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62810. var BABYLON;
  62811. (function (BABYLON) {
  62812. var Internals;
  62813. (function (Internals) {
  62814. ;
  62815. /**
  62816. * This groups tools to convert HDR texture to native colors array.
  62817. */
  62818. var HDRTools = /** @class */ (function () {
  62819. function HDRTools() {
  62820. }
  62821. HDRTools.Ldexp = function (mantissa, exponent) {
  62822. if (exponent > 1023) {
  62823. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62824. }
  62825. if (exponent < -1074) {
  62826. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62827. }
  62828. return mantissa * Math.pow(2, exponent);
  62829. };
  62830. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62831. if (exponent > 0) {
  62832. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62833. float32array[index + 0] = red * exponent;
  62834. float32array[index + 1] = green * exponent;
  62835. float32array[index + 2] = blue * exponent;
  62836. }
  62837. else {
  62838. float32array[index + 0] = 0;
  62839. float32array[index + 1] = 0;
  62840. float32array[index + 2] = 0;
  62841. }
  62842. };
  62843. HDRTools.readStringLine = function (uint8array, startIndex) {
  62844. var line = "";
  62845. var character = "";
  62846. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62847. character = String.fromCharCode(uint8array[i]);
  62848. if (character == "\n") {
  62849. break;
  62850. }
  62851. line += character;
  62852. }
  62853. return line;
  62854. };
  62855. /**
  62856. * Reads header information from an RGBE texture stored in a native array.
  62857. * More information on this format are available here:
  62858. * https://en.wikipedia.org/wiki/RGBE_image_format
  62859. *
  62860. * @param uint8array The binary file stored in native array.
  62861. * @return The header information.
  62862. */
  62863. HDRTools.RGBE_ReadHeader = function (uint8array) {
  62864. var height = 0;
  62865. var width = 0;
  62866. var line = this.readStringLine(uint8array, 0);
  62867. if (line[0] != '#' || line[1] != '?') {
  62868. throw "Bad HDR Format.";
  62869. }
  62870. var endOfHeader = false;
  62871. var findFormat = false;
  62872. var lineIndex = 0;
  62873. do {
  62874. lineIndex += (line.length + 1);
  62875. line = this.readStringLine(uint8array, lineIndex);
  62876. if (line == "FORMAT=32-bit_rle_rgbe") {
  62877. findFormat = true;
  62878. }
  62879. else if (line.length == 0) {
  62880. endOfHeader = true;
  62881. }
  62882. } while (!endOfHeader);
  62883. if (!findFormat) {
  62884. throw "HDR Bad header format, unsupported FORMAT";
  62885. }
  62886. lineIndex += (line.length + 1);
  62887. line = this.readStringLine(uint8array, lineIndex);
  62888. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  62889. var match = sizeRegexp.exec(line);
  62890. // TODO. Support +Y and -X if needed.
  62891. if (!match || match.length < 3) {
  62892. throw "HDR Bad header format, no size";
  62893. }
  62894. width = parseInt(match[2]);
  62895. height = parseInt(match[1]);
  62896. if (width < 8 || width > 0x7fff) {
  62897. throw "HDR Bad header format, unsupported size";
  62898. }
  62899. lineIndex += (line.length + 1);
  62900. return {
  62901. height: height,
  62902. width: width,
  62903. dataPosition: lineIndex
  62904. };
  62905. };
  62906. /**
  62907. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  62908. * This RGBE texture needs to store the information as a panorama.
  62909. *
  62910. * More information on this format are available here:
  62911. * https://en.wikipedia.org/wiki/RGBE_image_format
  62912. *
  62913. * @param buffer The binary file stored in an array buffer.
  62914. * @param size The expected size of the extracted cubemap.
  62915. * @return The Cube Map information.
  62916. */
  62917. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  62918. var uint8array = new Uint8Array(buffer);
  62919. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  62920. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62921. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  62922. return cubeMapData;
  62923. };
  62924. /**
  62925. * Returns the pixels data extracted from an RGBE texture.
  62926. * This pixels will be stored left to right up to down in the R G B order in one array.
  62927. *
  62928. * More information on this format are available here:
  62929. * https://en.wikipedia.org/wiki/RGBE_image_format
  62930. *
  62931. * @param uint8array The binary file stored in an array buffer.
  62932. * @param hdrInfo The header information of the file.
  62933. * @return The pixels data in RGB right to left up to down order.
  62934. */
  62935. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  62936. // Keep for multi format supports.
  62937. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62938. };
  62939. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  62940. var num_scanlines = hdrInfo.height;
  62941. var scanline_width = hdrInfo.width;
  62942. var a, b, c, d, count;
  62943. var dataIndex = hdrInfo.dataPosition;
  62944. var index = 0, endIndex = 0, i = 0;
  62945. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  62946. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  62947. // 3 channels of 4 bytes per pixel in float.
  62948. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  62949. var resultArray = new Float32Array(resultBuffer);
  62950. // read in each successive scanline
  62951. while (num_scanlines > 0) {
  62952. a = uint8array[dataIndex++];
  62953. b = uint8array[dataIndex++];
  62954. c = uint8array[dataIndex++];
  62955. d = uint8array[dataIndex++];
  62956. if (a != 2 || b != 2 || (c & 0x80)) {
  62957. // this file is not run length encoded
  62958. throw "HDR Bad header format, not RLE";
  62959. }
  62960. if (((c << 8) | d) != scanline_width) {
  62961. throw "HDR Bad header format, wrong scan line width";
  62962. }
  62963. index = 0;
  62964. // read each of the four channels for the scanline into the buffer
  62965. for (i = 0; i < 4; i++) {
  62966. endIndex = (i + 1) * scanline_width;
  62967. while (index < endIndex) {
  62968. a = uint8array[dataIndex++];
  62969. b = uint8array[dataIndex++];
  62970. if (a > 128) {
  62971. // a run of the same value
  62972. count = a - 128;
  62973. if ((count == 0) || (count > endIndex - index)) {
  62974. throw "HDR Bad Format, bad scanline data (run)";
  62975. }
  62976. while (count-- > 0) {
  62977. scanLineArray[index++] = b;
  62978. }
  62979. }
  62980. else {
  62981. // a non-run
  62982. count = a;
  62983. if ((count == 0) || (count > endIndex - index)) {
  62984. throw "HDR Bad Format, bad scanline data (non-run)";
  62985. }
  62986. scanLineArray[index++] = b;
  62987. if (--count > 0) {
  62988. for (var j = 0; j < count; j++) {
  62989. scanLineArray[index++] = uint8array[dataIndex++];
  62990. }
  62991. }
  62992. }
  62993. }
  62994. }
  62995. // now convert data from buffer into floats
  62996. for (i = 0; i < scanline_width; i++) {
  62997. a = scanLineArray[i];
  62998. b = scanLineArray[i + scanline_width];
  62999. c = scanLineArray[i + 2 * scanline_width];
  63000. d = scanLineArray[i + 3 * scanline_width];
  63001. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  63002. }
  63003. num_scanlines--;
  63004. }
  63005. return resultArray;
  63006. };
  63007. return HDRTools;
  63008. }());
  63009. Internals.HDRTools = HDRTools;
  63010. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63011. })(BABYLON || (BABYLON = {}));
  63012. //# sourceMappingURL=babylon.hdr.js.map
  63013. var BABYLON;
  63014. (function (BABYLON) {
  63015. /**
  63016. * This represents a texture coming from an HDR input.
  63017. *
  63018. * The only supported format is currently panorama picture stored in RGBE format.
  63019. * Example of such files can be found on HDRLib: http://hdrlib.com/
  63020. */
  63021. var HDRCubeTexture = /** @class */ (function (_super) {
  63022. __extends(HDRCubeTexture, _super);
  63023. /**
  63024. * Instantiates an HDRTexture from the following parameters.
  63025. *
  63026. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  63027. * @param scene The scene the texture will be used in
  63028. * @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.
  63029. * @param noMipmap Forces to not generate the mipmap if true
  63030. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  63031. * @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)
  63032. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  63033. */
  63034. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  63035. if (noMipmap === void 0) { noMipmap = false; }
  63036. if (generateHarmonics === void 0) { generateHarmonics = true; }
  63037. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  63038. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  63039. if (onLoad === void 0) { onLoad = null; }
  63040. if (onError === void 0) { onError = null; }
  63041. var _this = _super.call(this, scene) || this;
  63042. _this._useInGammaSpace = false;
  63043. _this._generateHarmonics = true;
  63044. _this._isBABYLONPreprocessed = false;
  63045. _this._onLoad = null;
  63046. _this._onError = null;
  63047. /**
  63048. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  63049. */
  63050. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63051. /**
  63052. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  63053. * This is usefull at run time to apply the good shader.
  63054. */
  63055. _this.isPMREM = false;
  63056. _this._isBlocking = true;
  63057. if (!url) {
  63058. return _this;
  63059. }
  63060. _this.name = url;
  63061. _this.url = url;
  63062. _this.hasAlpha = false;
  63063. _this.isCube = true;
  63064. _this._textureMatrix = BABYLON.Matrix.Identity();
  63065. _this._onLoad = onLoad;
  63066. _this._onError = onError;
  63067. _this.gammaSpace = false;
  63068. var caps = scene.getEngine().getCaps();
  63069. if (size) {
  63070. _this._isBABYLONPreprocessed = false;
  63071. _this._noMipmap = noMipmap;
  63072. _this._size = size;
  63073. _this._useInGammaSpace = useInGammaSpace;
  63074. _this._usePMREMGenerator = usePMREMGenerator &&
  63075. caps.textureLOD &&
  63076. caps.textureFloat &&
  63077. !_this._useInGammaSpace;
  63078. }
  63079. else {
  63080. _this._isBABYLONPreprocessed = true;
  63081. _this._noMipmap = false;
  63082. _this._useInGammaSpace = false;
  63083. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  63084. !_this._useInGammaSpace;
  63085. }
  63086. _this.isPMREM = _this._usePMREMGenerator;
  63087. _this._texture = _this._getFromCache(url, _this._noMipmap);
  63088. if (!_this._texture) {
  63089. if (!scene.useDelayedTextureLoading) {
  63090. _this.loadTexture();
  63091. }
  63092. else {
  63093. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63094. }
  63095. }
  63096. return _this;
  63097. }
  63098. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  63099. /**
  63100. * Gets wether or not the texture is blocking during loading.
  63101. */
  63102. get: function () {
  63103. return this._isBlocking;
  63104. },
  63105. /**
  63106. * Sets wether or not the texture is blocking during loading.
  63107. */
  63108. set: function (value) {
  63109. this._isBlocking = value;
  63110. },
  63111. enumerable: true,
  63112. configurable: true
  63113. });
  63114. /**
  63115. * Occurs when the file is a preprocessed .babylon.hdr file.
  63116. */
  63117. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  63118. var _this = this;
  63119. var mipLevels = 0;
  63120. var floatArrayView = null;
  63121. var scene = this.getScene();
  63122. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63123. var mips = new Array();
  63124. if (!floatArrayView) {
  63125. return mips;
  63126. }
  63127. var startIndex = 30;
  63128. for (var level = 0; level < mipLevels; level++) {
  63129. mips.push([]);
  63130. // Fill each pixel of the mip level.
  63131. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63132. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63133. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63134. mips[level].push(faceData);
  63135. startIndex += faceSize;
  63136. }
  63137. }
  63138. return mips;
  63139. } : null;
  63140. var callback = function (buffer) {
  63141. var scene = _this.getScene();
  63142. if (!scene) {
  63143. return null;
  63144. }
  63145. // Create Native Array Views
  63146. var intArrayView = new Int32Array(buffer);
  63147. floatArrayView = new Float32Array(buffer);
  63148. // Fill header.
  63149. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  63150. _this._size = intArrayView[1]; // CubeMap max mip face size.
  63151. // Update Texture Information.
  63152. if (!_this._texture) {
  63153. return null;
  63154. }
  63155. _this._texture.updateSize(_this._size, _this._size);
  63156. // Fill polynomial information.
  63157. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  63158. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  63159. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  63160. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  63161. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  63162. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  63163. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  63164. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  63165. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  63166. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  63167. _this.sphericalPolynomial = sphericalPolynomial;
  63168. // Fill pixel data.
  63169. mipLevels = intArrayView[29]; // Number of mip levels.
  63170. var startIndex = 30;
  63171. var data = [];
  63172. var faceSize = Math.pow(_this._size, 2) * 3;
  63173. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63174. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  63175. startIndex += faceSize;
  63176. }
  63177. var results = [];
  63178. var byteArray = null;
  63179. // Push each faces.
  63180. for (var k = 0; k < 6; k++) {
  63181. var dataFace = null;
  63182. // To be deprecated.
  63183. if (version === 1) {
  63184. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  63185. dataFace = data[j];
  63186. }
  63187. // If special cases.
  63188. if (!mipmapGenerator && dataFace) {
  63189. if (!scene.getEngine().getCaps().textureFloat) {
  63190. // 3 channels of 1 bytes per pixel in bytes.
  63191. var byteBuffer = new ArrayBuffer(faceSize);
  63192. byteArray = new Uint8Array(byteBuffer);
  63193. }
  63194. for (var i = 0; i < _this._size * _this._size; i++) {
  63195. // Put in gamma space if requested.
  63196. if (_this._useInGammaSpace) {
  63197. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63198. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63199. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63200. }
  63201. // Convert to int texture for fallback.
  63202. if (byteArray) {
  63203. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63204. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63205. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63206. // May use luminance instead if the result is not accurate.
  63207. var max = Math.max(Math.max(r, g), b);
  63208. if (max > 255) {
  63209. var scale = 255 / max;
  63210. r *= scale;
  63211. g *= scale;
  63212. b *= scale;
  63213. }
  63214. byteArray[(i * 3) + 0] = r;
  63215. byteArray[(i * 3) + 1] = g;
  63216. byteArray[(i * 3) + 2] = b;
  63217. }
  63218. }
  63219. }
  63220. // Fill the array accordingly.
  63221. if (byteArray) {
  63222. results.push(byteArray);
  63223. }
  63224. else {
  63225. results.push(dataFace);
  63226. }
  63227. }
  63228. return results;
  63229. };
  63230. if (scene) {
  63231. 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);
  63232. }
  63233. };
  63234. /**
  63235. * Occurs when the file is raw .hdr file.
  63236. */
  63237. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63238. var _this = this;
  63239. var callback = function (buffer) {
  63240. var scene = _this.getScene();
  63241. if (!scene) {
  63242. return null;
  63243. }
  63244. // Extract the raw linear data.
  63245. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63246. // Generate harmonics if needed.
  63247. if (_this._generateHarmonics) {
  63248. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63249. _this.sphericalPolynomial = sphericalPolynomial;
  63250. }
  63251. var results = [];
  63252. var byteArray = null;
  63253. // Push each faces.
  63254. for (var j = 0; j < 6; j++) {
  63255. // Create uintarray fallback.
  63256. if (!scene.getEngine().getCaps().textureFloat) {
  63257. // 3 channels of 1 bytes per pixel in bytes.
  63258. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63259. byteArray = new Uint8Array(byteBuffer);
  63260. }
  63261. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63262. // If special cases.
  63263. if (_this._useInGammaSpace || byteArray) {
  63264. for (var i = 0; i < _this._size * _this._size; i++) {
  63265. // Put in gamma space if requested.
  63266. if (_this._useInGammaSpace) {
  63267. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63268. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63269. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63270. }
  63271. // Convert to int texture for fallback.
  63272. if (byteArray) {
  63273. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63274. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63275. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63276. // May use luminance instead if the result is not accurate.
  63277. var max = Math.max(Math.max(r, g), b);
  63278. if (max > 255) {
  63279. var scale = 255 / max;
  63280. r *= scale;
  63281. g *= scale;
  63282. b *= scale;
  63283. }
  63284. byteArray[(i * 3) + 0] = r;
  63285. byteArray[(i * 3) + 1] = g;
  63286. byteArray[(i * 3) + 2] = b;
  63287. }
  63288. }
  63289. }
  63290. if (byteArray) {
  63291. results.push(byteArray);
  63292. }
  63293. else {
  63294. results.push(dataFace);
  63295. }
  63296. }
  63297. return results;
  63298. };
  63299. var mipmapGenerator = null;
  63300. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63301. // if (!this._noMipmap &&
  63302. // this._usePMREMGenerator) {
  63303. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63304. // // Custom setup of the generator matching with the PBR shader values.
  63305. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63306. // this._size,
  63307. // this._size,
  63308. // 0,
  63309. // 3,
  63310. // this.getScene().getEngine().getCaps().textureFloat,
  63311. // 2048,
  63312. // 0.25,
  63313. // false,
  63314. // true);
  63315. // return generator.filterCubeMap();
  63316. // };
  63317. // }
  63318. var scene = this.getScene();
  63319. if (scene) {
  63320. 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);
  63321. }
  63322. };
  63323. /**
  63324. * Starts the loading process of the texture.
  63325. */
  63326. HDRCubeTexture.prototype.loadTexture = function () {
  63327. if (this._isBABYLONPreprocessed) {
  63328. this.loadBabylonTexture();
  63329. }
  63330. else {
  63331. this.loadHDRTexture();
  63332. }
  63333. };
  63334. HDRCubeTexture.prototype.clone = function () {
  63335. var scene = this.getScene();
  63336. if (!scene) {
  63337. return this;
  63338. }
  63339. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63340. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63341. // Base texture
  63342. newTexture.level = this.level;
  63343. newTexture.wrapU = this.wrapU;
  63344. newTexture.wrapV = this.wrapV;
  63345. newTexture.coordinatesIndex = this.coordinatesIndex;
  63346. newTexture.coordinatesMode = this.coordinatesMode;
  63347. return newTexture;
  63348. };
  63349. // Methods
  63350. HDRCubeTexture.prototype.delayLoad = function () {
  63351. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63352. return;
  63353. }
  63354. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63355. this._texture = this._getFromCache(this.url, this._noMipmap);
  63356. if (!this._texture) {
  63357. this.loadTexture();
  63358. }
  63359. };
  63360. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63361. return this._textureMatrix;
  63362. };
  63363. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63364. this._textureMatrix = value;
  63365. };
  63366. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63367. var texture = null;
  63368. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63369. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63370. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63371. texture.name = parsedTexture.name;
  63372. texture.hasAlpha = parsedTexture.hasAlpha;
  63373. texture.level = parsedTexture.level;
  63374. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63375. texture.isBlocking = parsedTexture.isBlocking;
  63376. }
  63377. return texture;
  63378. };
  63379. HDRCubeTexture.prototype.serialize = function () {
  63380. if (!this.name) {
  63381. return null;
  63382. }
  63383. var serializationObject = {};
  63384. serializationObject.name = this.name;
  63385. serializationObject.hasAlpha = this.hasAlpha;
  63386. serializationObject.isCube = true;
  63387. serializationObject.level = this.level;
  63388. serializationObject.size = this._size;
  63389. serializationObject.coordinatesMode = this.coordinatesMode;
  63390. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63391. serializationObject.generateHarmonics = this._generateHarmonics;
  63392. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63393. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63394. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63395. serializationObject.noMipmap = this._noMipmap;
  63396. serializationObject.isBlocking = this._isBlocking;
  63397. return serializationObject;
  63398. };
  63399. /**
  63400. * Saves as a file the data contained in the texture in a binary format.
  63401. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63402. * as the spherical used in the lighting.
  63403. * @param url The HDR file url.
  63404. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63405. * @param onError Method called if any error happens during download.
  63406. * @return The packed binary data.
  63407. */
  63408. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63409. if (onError === void 0) { onError = null; }
  63410. var callback = function (buffer) {
  63411. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63412. // Returns a URL you can use as a href.
  63413. var objUrl = window.URL.createObjectURL(data);
  63414. // Simulates a link to it and click to dowload.
  63415. var a = document.createElement("a");
  63416. document.body.appendChild(a);
  63417. a.style.display = "none";
  63418. a.href = objUrl;
  63419. a.download = "envmap.babylon.hdr";
  63420. a.click();
  63421. };
  63422. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63423. };
  63424. /**
  63425. * Serializes the data contained in the texture in a binary format.
  63426. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63427. * as the spherical used in the lighting.
  63428. * @param url The HDR file url.
  63429. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63430. * @param onError Method called if any error happens during download.
  63431. * @return The packed binary data.
  63432. */
  63433. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63434. if (onError === void 0) { onError = null; }
  63435. // Needs the url tho create the texture.
  63436. if (!url) {
  63437. return;
  63438. }
  63439. // Check Power of two size.
  63440. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63441. return;
  63442. }
  63443. // Coming Back in 3.x.
  63444. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63445. };
  63446. HDRCubeTexture._facesMapping = [
  63447. "right",
  63448. "left",
  63449. "up",
  63450. "down",
  63451. "front",
  63452. "back"
  63453. ];
  63454. return HDRCubeTexture;
  63455. }(BABYLON.BaseTexture));
  63456. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63457. })(BABYLON || (BABYLON = {}));
  63458. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63459. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63460. // Huge respect for a such great lib.
  63461. // Earcut license:
  63462. // Copyright (c) 2016, Mapbox
  63463. //
  63464. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63465. // with or without fee is hereby granted, provided that the above copyright notice
  63466. // and this permission notice appear in all copies.
  63467. //
  63468. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63469. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63470. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63471. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63472. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63473. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63474. // THIS SOFTWARE.
  63475. var Earcut;
  63476. (function (Earcut) {
  63477. /**
  63478. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63479. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63480. * @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).
  63481. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63482. */
  63483. function earcut(data, holeIndices, dim) {
  63484. dim = dim || 2;
  63485. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63486. if (!outerNode)
  63487. return triangles;
  63488. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63489. if (hasHoles)
  63490. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63491. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63492. if (data.length > 80 * dim) {
  63493. minX = maxX = data[0];
  63494. minY = maxY = data[1];
  63495. for (var i = dim; i < outerLen; i += dim) {
  63496. x = data[i];
  63497. y = data[i + 1];
  63498. if (x < minX)
  63499. minX = x;
  63500. if (y < minY)
  63501. minY = y;
  63502. if (x > maxX)
  63503. maxX = x;
  63504. if (y > maxY)
  63505. maxY = y;
  63506. }
  63507. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63508. size = Math.max(maxX - minX, maxY - minY);
  63509. }
  63510. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63511. return triangles;
  63512. }
  63513. Earcut.earcut = earcut;
  63514. var Node = /** @class */ (function () {
  63515. function Node(i, x, y) {
  63516. this.i = i;
  63517. this.x = x;
  63518. this.y = y;
  63519. this.prev = null;
  63520. this.next = null;
  63521. this.z = null;
  63522. this.prevZ = null;
  63523. this.nextZ = null;
  63524. this.steiner = false;
  63525. }
  63526. return Node;
  63527. }());
  63528. // create a circular doubly linked list from polygon points in the specified winding order
  63529. function linkedList(data, start, end, dim, clockwise) {
  63530. var i, last = null;
  63531. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63532. for (i = start; i < end; i += dim)
  63533. last = insertNode(i, data[i], data[i + 1], last);
  63534. }
  63535. else {
  63536. for (i = end - dim; i >= start; i -= dim)
  63537. last = insertNode(i, data[i], data[i + 1], last);
  63538. }
  63539. if (last && equals(last, last.next)) {
  63540. removeNode(last);
  63541. last = last.next;
  63542. }
  63543. return last;
  63544. }
  63545. // eliminate colinear or duplicate points
  63546. function filterPoints(start, end) {
  63547. if (!start)
  63548. return start;
  63549. if (!end)
  63550. end = start;
  63551. var p = start, again;
  63552. do {
  63553. again = false;
  63554. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63555. removeNode(p);
  63556. p = end = p.prev;
  63557. if (p === p.next)
  63558. return undefined;
  63559. again = true;
  63560. }
  63561. else {
  63562. p = p.next;
  63563. }
  63564. } while (again || p !== end);
  63565. return end;
  63566. }
  63567. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63568. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63569. if (!ear)
  63570. return;
  63571. // interlink polygon nodes in z-order
  63572. if (!pass && size)
  63573. indexCurve(ear, minX, minY, size);
  63574. var stop = ear, prev, next;
  63575. // iterate through ears, slicing them one by one
  63576. while (ear.prev !== ear.next) {
  63577. prev = ear.prev;
  63578. next = ear.next;
  63579. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63580. // cut off the triangle
  63581. triangles.push(prev.i / dim);
  63582. triangles.push(ear.i / dim);
  63583. triangles.push(next.i / dim);
  63584. removeNode(ear);
  63585. // skipping the next vertice leads to less sliver triangles
  63586. ear = next.next;
  63587. stop = next.next;
  63588. continue;
  63589. }
  63590. ear = next;
  63591. // if we looped through the whole remaining polygon and can't find any more ears
  63592. if (ear === stop) {
  63593. // try filtering points and slicing again
  63594. if (!pass) {
  63595. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63596. // if this didn't work, try curing all small self-intersections locally
  63597. }
  63598. else if (pass === 1) {
  63599. ear = cureLocalIntersections(ear, triangles, dim);
  63600. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63601. // as a last resort, try splitting the remaining polygon into two
  63602. }
  63603. else if (pass === 2) {
  63604. splitEarcut(ear, triangles, dim, minX, minY, size);
  63605. }
  63606. break;
  63607. }
  63608. }
  63609. }
  63610. // check whether a polygon node forms a valid ear with adjacent nodes
  63611. function isEar(ear) {
  63612. var a = ear.prev, b = ear, c = ear.next;
  63613. if (area(a, b, c) >= 0)
  63614. return false; // reflex, can't be an ear
  63615. // now make sure we don't have other points inside the potential ear
  63616. var p = ear.next.next;
  63617. while (p !== ear.prev) {
  63618. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63619. area(p.prev, p, p.next) >= 0)
  63620. return false;
  63621. p = p.next;
  63622. }
  63623. return true;
  63624. }
  63625. function isEarHashed(ear, minX, minY, size) {
  63626. var a = ear.prev, b = ear, c = ear.next;
  63627. if (area(a, b, c) >= 0)
  63628. return false; // reflex, can't be an ear
  63629. // triangle bbox; min & max are calculated like this for speed
  63630. 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);
  63631. // z-order range for the current triangle bbox;
  63632. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63633. // first look for points inside the triangle in increasing z-order
  63634. var p = ear.nextZ;
  63635. while (p && p.z <= maxZ) {
  63636. if (p !== ear.prev &&
  63637. p !== ear.next &&
  63638. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63639. area(p.prev, p, p.next) >= 0)
  63640. return false;
  63641. p = p.nextZ;
  63642. }
  63643. // then look for points in decreasing z-order
  63644. p = ear.prevZ;
  63645. while (p && p.z >= minZ) {
  63646. if (p !== ear.prev &&
  63647. p !== ear.next &&
  63648. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63649. area(p.prev, p, p.next) >= 0)
  63650. return false;
  63651. p = p.prevZ;
  63652. }
  63653. return true;
  63654. }
  63655. // go through all polygon nodes and cure small local self-intersections
  63656. function cureLocalIntersections(start, triangles, dim) {
  63657. var p = start;
  63658. do {
  63659. var a = p.prev, b = p.next.next;
  63660. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63661. triangles.push(a.i / dim);
  63662. triangles.push(p.i / dim);
  63663. triangles.push(b.i / dim);
  63664. // remove two nodes involved
  63665. removeNode(p);
  63666. removeNode(p.next);
  63667. p = start = b;
  63668. }
  63669. p = p.next;
  63670. } while (p !== start);
  63671. return p;
  63672. }
  63673. // try splitting polygon into two and triangulate them independently
  63674. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63675. // look for a valid diagonal that divides the polygon into two
  63676. var a = start;
  63677. do {
  63678. var b = a.next.next;
  63679. while (b !== a.prev) {
  63680. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63681. // split the polygon in two by the diagonal
  63682. var c = splitPolygon(a, b);
  63683. // filter colinear points around the cuts
  63684. a = filterPoints(a, a.next);
  63685. c = filterPoints(c, c.next);
  63686. // run earcut on each half
  63687. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63688. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63689. return;
  63690. }
  63691. b = b.next;
  63692. }
  63693. a = a.next;
  63694. } while (a !== start);
  63695. }
  63696. // link every hole into the outer loop, producing a single-ring polygon without holes
  63697. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63698. var queue = [], i, len, start, end, list;
  63699. for (i = 0, len = holeIndices.length; i < len; i++) {
  63700. start = holeIndices[i] * dim;
  63701. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63702. list = linkedList(data, start, end, dim, false);
  63703. if (list === list.next)
  63704. list.steiner = true;
  63705. queue.push(getLeftmost(list));
  63706. }
  63707. queue.sort(compareX);
  63708. // process holes from left to right
  63709. for (i = 0; i < queue.length; i++) {
  63710. eliminateHole(queue[i], outerNode);
  63711. outerNode = filterPoints(outerNode, outerNode.next);
  63712. }
  63713. return outerNode;
  63714. }
  63715. function compareX(a, b) {
  63716. return a.x - b.x;
  63717. }
  63718. // find a bridge between vertices that connects hole with an outer ring and and link it
  63719. function eliminateHole(hole, outerNode) {
  63720. outerNode = findHoleBridge(hole, outerNode);
  63721. if (outerNode) {
  63722. var b = splitPolygon(outerNode, hole);
  63723. filterPoints(b, b.next);
  63724. }
  63725. }
  63726. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63727. function findHoleBridge(hole, outerNode) {
  63728. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63729. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63730. // segment's endpoint with lesser x will be potential connection point
  63731. do {
  63732. if (hy <= p.y && hy >= p.next.y) {
  63733. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63734. if (x <= hx && x > qx) {
  63735. qx = x;
  63736. if (x === hx) {
  63737. if (hy === p.y)
  63738. return p;
  63739. if (hy === p.next.y)
  63740. return p.next;
  63741. }
  63742. m = p.x < p.next.x ? p : p.next;
  63743. }
  63744. }
  63745. p = p.next;
  63746. } while (p !== outerNode);
  63747. if (!m)
  63748. return null;
  63749. if (hx === qx)
  63750. return m.prev; // hole touches outer segment; pick lower endpoint
  63751. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63752. // if there are no points found, we have a valid connection;
  63753. // otherwise choose the point of the minimum angle with the ray as connection point
  63754. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63755. p = m.next;
  63756. while (p !== stop) {
  63757. if (hx >= p.x &&
  63758. p.x >= mx &&
  63759. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63760. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63761. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63762. m = p;
  63763. tanMin = tan;
  63764. }
  63765. }
  63766. p = p.next;
  63767. }
  63768. return m;
  63769. }
  63770. // interlink polygon nodes in z-order
  63771. function indexCurve(start, minX, minY, size) {
  63772. var p = start;
  63773. do {
  63774. if (p.z === null)
  63775. p.z = zOrder(p.x, p.y, minX, minY, size);
  63776. p.prevZ = p.prev;
  63777. p.nextZ = p.next;
  63778. p = p.next;
  63779. } while (p !== start);
  63780. p.prevZ.nextZ = null;
  63781. p.prevZ = null;
  63782. sortLinked(p);
  63783. }
  63784. // Simon Tatham's linked list merge sort algorithm
  63785. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63786. function sortLinked(list) {
  63787. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63788. do {
  63789. p = list;
  63790. list = null;
  63791. tail = null;
  63792. numMerges = 0;
  63793. while (p) {
  63794. numMerges++;
  63795. q = p;
  63796. pSize = 0;
  63797. for (i = 0; i < inSize; i++) {
  63798. pSize++;
  63799. q = q.nextZ;
  63800. if (!q)
  63801. break;
  63802. }
  63803. qSize = inSize;
  63804. while (pSize > 0 || (qSize > 0 && q)) {
  63805. if (pSize === 0) {
  63806. e = q;
  63807. q = q.nextZ;
  63808. qSize--;
  63809. }
  63810. else if (qSize === 0 || !q) {
  63811. e = p;
  63812. p = p.nextZ;
  63813. pSize--;
  63814. }
  63815. else if (p.z <= q.z) {
  63816. e = p;
  63817. p = p.nextZ;
  63818. pSize--;
  63819. }
  63820. else {
  63821. e = q;
  63822. q = q.nextZ;
  63823. qSize--;
  63824. }
  63825. if (tail)
  63826. tail.nextZ = e;
  63827. else
  63828. list = e;
  63829. e.prevZ = tail;
  63830. tail = e;
  63831. }
  63832. p = q;
  63833. }
  63834. tail.nextZ = null;
  63835. inSize *= 2;
  63836. } while (numMerges > 1);
  63837. return list;
  63838. }
  63839. // z-order of a point given coords and size of the data bounding box
  63840. function zOrder(x, y, minX, minY, size) {
  63841. // coords are transformed into non-negative 15-bit integer range
  63842. x = 32767 * (x - minX) / size;
  63843. y = 32767 * (y - minY) / size;
  63844. x = (x | (x << 8)) & 0x00FF00FF;
  63845. x = (x | (x << 4)) & 0x0F0F0F0F;
  63846. x = (x | (x << 2)) & 0x33333333;
  63847. x = (x | (x << 1)) & 0x55555555;
  63848. y = (y | (y << 8)) & 0x00FF00FF;
  63849. y = (y | (y << 4)) & 0x0F0F0F0F;
  63850. y = (y | (y << 2)) & 0x33333333;
  63851. y = (y | (y << 1)) & 0x55555555;
  63852. return x | (y << 1);
  63853. }
  63854. // find the leftmost node of a polygon ring
  63855. function getLeftmost(start) {
  63856. var p = start, leftmost = start;
  63857. do {
  63858. if (p.x < leftmost.x)
  63859. leftmost = p;
  63860. p = p.next;
  63861. } while (p !== start);
  63862. return leftmost;
  63863. }
  63864. // check if a point lies within a convex triangle
  63865. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  63866. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  63867. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  63868. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  63869. }
  63870. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  63871. function isValidDiagonal(a, b) {
  63872. return a.next.i !== b.i &&
  63873. a.prev.i !== b.i &&
  63874. !intersectsPolygon(a, b) &&
  63875. locallyInside(a, b) &&
  63876. locallyInside(b, a) &&
  63877. middleInside(a, b);
  63878. }
  63879. // signed area of a triangle
  63880. function area(p, q, r) {
  63881. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  63882. }
  63883. // check if two points are equal
  63884. function equals(p1, p2) {
  63885. return p1.x === p2.x && p1.y === p2.y;
  63886. }
  63887. // check if two segments intersect
  63888. function intersects(p1, q1, p2, q2) {
  63889. if ((equals(p1, q1) && equals(p2, q2)) ||
  63890. (equals(p1, q2) && equals(p2, q1)))
  63891. return true;
  63892. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  63893. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  63894. }
  63895. // check if a polygon diagonal intersects any polygon segments
  63896. function intersectsPolygon(a, b) {
  63897. var p = a;
  63898. do {
  63899. if (p.i !== a.i &&
  63900. p.next.i !== a.i &&
  63901. p.i !== b.i &&
  63902. p.next.i !== b.i &&
  63903. intersects(p, p.next, a, b))
  63904. return true;
  63905. p = p.next;
  63906. } while (p !== a);
  63907. return false;
  63908. }
  63909. // check if a polygon diagonal is locally inside the polygon
  63910. function locallyInside(a, b) {
  63911. return area(a.prev, a, a.next) < 0
  63912. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  63913. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  63914. }
  63915. // check if the middle point of a polygon diagonal is inside the polygon
  63916. function middleInside(a, b) {
  63917. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  63918. do {
  63919. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  63920. inside = !inside;
  63921. p = p.next;
  63922. } while (p !== a);
  63923. return inside;
  63924. }
  63925. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  63926. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  63927. function splitPolygon(a, b) {
  63928. 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;
  63929. a.next = b;
  63930. b.prev = a;
  63931. a2.next = an;
  63932. an.prev = a2;
  63933. b2.next = a2;
  63934. a2.prev = b2;
  63935. bp.next = b2;
  63936. b2.prev = bp;
  63937. return b2;
  63938. }
  63939. // create a node and optionally link it with previous one (in a circular doubly linked list)
  63940. function insertNode(i, x, y, last) {
  63941. var p = new Node(i, x, y);
  63942. if (!last) {
  63943. p.prev = p;
  63944. p.next = p;
  63945. }
  63946. else {
  63947. p.next = last.next;
  63948. p.prev = last;
  63949. last.next.prev = p;
  63950. last.next = p;
  63951. }
  63952. return p;
  63953. }
  63954. function removeNode(p) {
  63955. p.next.prev = p.prev;
  63956. p.prev.next = p.next;
  63957. if (p.prevZ)
  63958. p.prevZ.nextZ = p.nextZ;
  63959. if (p.nextZ)
  63960. p.nextZ.prevZ = p.prevZ;
  63961. }
  63962. /**
  63963. * return a percentage difference between the polygon area and its triangulation area;
  63964. * used to verify correctness of triangulation
  63965. */
  63966. function deviation(data, holeIndices, dim, triangles) {
  63967. var hasHoles = holeIndices && holeIndices.length;
  63968. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  63969. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  63970. if (hasHoles) {
  63971. for (var i = 0, len = holeIndices.length; i < len; i++) {
  63972. var start = holeIndices[i] * dim;
  63973. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63974. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  63975. }
  63976. }
  63977. var trianglesArea = 0;
  63978. for (i = 0; i < triangles.length; i += 3) {
  63979. var a = triangles[i] * dim;
  63980. var b = triangles[i + 1] * dim;
  63981. var c = triangles[i + 2] * dim;
  63982. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  63983. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  63984. }
  63985. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  63986. }
  63987. Earcut.deviation = deviation;
  63988. ;
  63989. function signedArea(data, start, end, dim) {
  63990. var sum = 0;
  63991. for (var i = start, j = end - dim; i < end; i += dim) {
  63992. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  63993. j = i;
  63994. }
  63995. return sum;
  63996. }
  63997. /**
  63998. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  63999. */
  64000. function flatten(data) {
  64001. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  64002. for (var i = 0; i < data.length; i++) {
  64003. for (var j = 0; j < data[i].length; j++) {
  64004. for (var d = 0; d < dim; d++)
  64005. result.vertices.push(data[i][j][d]);
  64006. }
  64007. if (i > 0) {
  64008. holeIndex += data[i - 1].length;
  64009. result.holes.push(holeIndex);
  64010. }
  64011. }
  64012. return result;
  64013. }
  64014. Earcut.flatten = flatten;
  64015. ;
  64016. })(Earcut || (Earcut = {}));
  64017. //# sourceMappingURL=babylon.earcut.js.map
  64018. var BABYLON;
  64019. (function (BABYLON) {
  64020. var IndexedVector2 = /** @class */ (function (_super) {
  64021. __extends(IndexedVector2, _super);
  64022. function IndexedVector2(original, index) {
  64023. var _this = _super.call(this, original.x, original.y) || this;
  64024. _this.index = index;
  64025. return _this;
  64026. }
  64027. return IndexedVector2;
  64028. }(BABYLON.Vector2));
  64029. var PolygonPoints = /** @class */ (function () {
  64030. function PolygonPoints() {
  64031. this.elements = new Array();
  64032. }
  64033. PolygonPoints.prototype.add = function (originalPoints) {
  64034. var _this = this;
  64035. var result = new Array();
  64036. originalPoints.forEach(function (point) {
  64037. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  64038. var newPoint = new IndexedVector2(point, _this.elements.length);
  64039. result.push(newPoint);
  64040. _this.elements.push(newPoint);
  64041. }
  64042. });
  64043. return result;
  64044. };
  64045. PolygonPoints.prototype.computeBounds = function () {
  64046. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64047. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64048. this.elements.forEach(function (point) {
  64049. // x
  64050. if (point.x < lmin.x) {
  64051. lmin.x = point.x;
  64052. }
  64053. else if (point.x > lmax.x) {
  64054. lmax.x = point.x;
  64055. }
  64056. // y
  64057. if (point.y < lmin.y) {
  64058. lmin.y = point.y;
  64059. }
  64060. else if (point.y > lmax.y) {
  64061. lmax.y = point.y;
  64062. }
  64063. });
  64064. return {
  64065. min: lmin,
  64066. max: lmax,
  64067. width: lmax.x - lmin.x,
  64068. height: lmax.y - lmin.y
  64069. };
  64070. };
  64071. return PolygonPoints;
  64072. }());
  64073. var Polygon = /** @class */ (function () {
  64074. function Polygon() {
  64075. }
  64076. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  64077. return [
  64078. new BABYLON.Vector2(xmin, ymin),
  64079. new BABYLON.Vector2(xmax, ymin),
  64080. new BABYLON.Vector2(xmax, ymax),
  64081. new BABYLON.Vector2(xmin, ymax)
  64082. ];
  64083. };
  64084. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  64085. if (cx === void 0) { cx = 0; }
  64086. if (cy === void 0) { cy = 0; }
  64087. if (numberOfSides === void 0) { numberOfSides = 32; }
  64088. var result = new Array();
  64089. var angle = 0;
  64090. var increment = (Math.PI * 2) / numberOfSides;
  64091. for (var i = 0; i < numberOfSides; i++) {
  64092. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  64093. angle -= increment;
  64094. }
  64095. return result;
  64096. };
  64097. Polygon.Parse = function (input) {
  64098. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  64099. var i, result = [];
  64100. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  64101. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  64102. }
  64103. return result;
  64104. };
  64105. Polygon.StartingAt = function (x, y) {
  64106. return BABYLON.Path2.StartingAt(x, y);
  64107. };
  64108. return Polygon;
  64109. }());
  64110. BABYLON.Polygon = Polygon;
  64111. var PolygonMeshBuilder = /** @class */ (function () {
  64112. function PolygonMeshBuilder(name, contours, scene) {
  64113. this._points = new PolygonPoints();
  64114. this._outlinepoints = new PolygonPoints();
  64115. this._holes = new Array();
  64116. this._epoints = new Array();
  64117. this._eholes = new Array();
  64118. this._name = name;
  64119. this._scene = scene;
  64120. var points;
  64121. if (contours instanceof BABYLON.Path2) {
  64122. points = contours.getPoints();
  64123. }
  64124. else {
  64125. points = contours;
  64126. }
  64127. this._addToepoint(points);
  64128. this._points.add(points);
  64129. this._outlinepoints.add(points);
  64130. }
  64131. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64132. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64133. var p = points_1[_i];
  64134. this._epoints.push(p.x, p.y);
  64135. }
  64136. };
  64137. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64138. this._points.add(hole);
  64139. var holepoints = new PolygonPoints();
  64140. holepoints.add(hole);
  64141. this._holes.push(holepoints);
  64142. this._eholes.push(this._epoints.length / 2);
  64143. this._addToepoint(hole);
  64144. return this;
  64145. };
  64146. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  64147. var _this = this;
  64148. if (updatable === void 0) { updatable = false; }
  64149. if (depth === void 0) { depth = 0; }
  64150. var result = new BABYLON.Mesh(this._name, this._scene);
  64151. var normals = new Array();
  64152. var positions = new Array();
  64153. var uvs = new Array();
  64154. var bounds = this._points.computeBounds();
  64155. this._points.elements.forEach(function (p) {
  64156. normals.push(0, 1.0, 0);
  64157. positions.push(p.x, 0, p.y);
  64158. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  64159. });
  64160. var indices = new Array();
  64161. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  64162. for (var i = 0; i < res.length; i++) {
  64163. indices.push(res[i]);
  64164. }
  64165. if (depth > 0) {
  64166. var positionscount = (positions.length / 3); //get the current pointcount
  64167. this._points.elements.forEach(function (p) {
  64168. normals.push(0, -1.0, 0);
  64169. positions.push(p.x, -depth, p.y);
  64170. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  64171. });
  64172. var totalCount = indices.length;
  64173. for (var i = 0; i < totalCount; i += 3) {
  64174. var i0 = indices[i + 0];
  64175. var i1 = indices[i + 1];
  64176. var i2 = indices[i + 2];
  64177. indices.push(i2 + positionscount);
  64178. indices.push(i1 + positionscount);
  64179. indices.push(i0 + positionscount);
  64180. }
  64181. //Add the sides
  64182. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  64183. this._holes.forEach(function (hole) {
  64184. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  64185. });
  64186. }
  64187. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  64188. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  64189. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  64190. result.setIndices(indices);
  64191. return result;
  64192. };
  64193. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  64194. var StartIndex = positions.length / 3;
  64195. var ulength = 0;
  64196. for (var i = 0; i < points.elements.length; i++) {
  64197. var p = points.elements[i];
  64198. var p1;
  64199. if ((i + 1) > points.elements.length - 1) {
  64200. p1 = points.elements[0];
  64201. }
  64202. else {
  64203. p1 = points.elements[i + 1];
  64204. }
  64205. positions.push(p.x, 0, p.y);
  64206. positions.push(p.x, -depth, p.y);
  64207. positions.push(p1.x, 0, p1.y);
  64208. positions.push(p1.x, -depth, p1.y);
  64209. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64210. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64211. var v3 = v2.subtract(v1);
  64212. var v4 = new BABYLON.Vector3(0, 1, 0);
  64213. var vn = BABYLON.Vector3.Cross(v3, v4);
  64214. vn = vn.normalize();
  64215. uvs.push(ulength / bounds.width, 0);
  64216. uvs.push(ulength / bounds.width, 1);
  64217. ulength += v3.length();
  64218. uvs.push((ulength / bounds.width), 0);
  64219. uvs.push((ulength / bounds.width), 1);
  64220. if (!flip) {
  64221. normals.push(-vn.x, -vn.y, -vn.z);
  64222. normals.push(-vn.x, -vn.y, -vn.z);
  64223. normals.push(-vn.x, -vn.y, -vn.z);
  64224. normals.push(-vn.x, -vn.y, -vn.z);
  64225. indices.push(StartIndex);
  64226. indices.push(StartIndex + 1);
  64227. indices.push(StartIndex + 2);
  64228. indices.push(StartIndex + 1);
  64229. indices.push(StartIndex + 3);
  64230. indices.push(StartIndex + 2);
  64231. }
  64232. else {
  64233. normals.push(vn.x, vn.y, vn.z);
  64234. normals.push(vn.x, vn.y, vn.z);
  64235. normals.push(vn.x, vn.y, vn.z);
  64236. normals.push(vn.x, vn.y, vn.z);
  64237. indices.push(StartIndex);
  64238. indices.push(StartIndex + 2);
  64239. indices.push(StartIndex + 1);
  64240. indices.push(StartIndex + 1);
  64241. indices.push(StartIndex + 2);
  64242. indices.push(StartIndex + 3);
  64243. }
  64244. StartIndex += 4;
  64245. }
  64246. ;
  64247. };
  64248. return PolygonMeshBuilder;
  64249. }());
  64250. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64251. })(BABYLON || (BABYLON = {}));
  64252. //# sourceMappingURL=babylon.polygonMesh.js.map
  64253. var BABYLON;
  64254. (function (BABYLON) {
  64255. // Unique ID when we import meshes from Babylon to CSG
  64256. var currentCSGMeshId = 0;
  64257. // # class Vertex
  64258. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64259. // one to provide additional features like texture coordinates and vertex
  64260. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64261. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64262. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64263. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64264. // is not used anywhere else.
  64265. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64266. var Vertex = /** @class */ (function () {
  64267. function Vertex(pos, normal, uv) {
  64268. this.pos = pos;
  64269. this.normal = normal;
  64270. this.uv = uv;
  64271. }
  64272. Vertex.prototype.clone = function () {
  64273. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64274. };
  64275. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64276. // orientation of a polygon is flipped.
  64277. Vertex.prototype.flip = function () {
  64278. this.normal = this.normal.scale(-1);
  64279. };
  64280. // Create a new vertex between this vertex and `other` by linearly
  64281. // interpolating all properties using a parameter of `t`. Subclasses should
  64282. // override this to interpolate additional properties.
  64283. Vertex.prototype.interpolate = function (other, t) {
  64284. 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));
  64285. };
  64286. return Vertex;
  64287. }());
  64288. // # class Plane
  64289. // Represents a plane in 3D space.
  64290. var Plane = /** @class */ (function () {
  64291. function Plane(normal, w) {
  64292. this.normal = normal;
  64293. this.w = w;
  64294. }
  64295. Plane.FromPoints = function (a, b, c) {
  64296. var v0 = c.subtract(a);
  64297. var v1 = b.subtract(a);
  64298. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64299. return null;
  64300. }
  64301. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64302. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64303. };
  64304. Plane.prototype.clone = function () {
  64305. return new Plane(this.normal.clone(), this.w);
  64306. };
  64307. Plane.prototype.flip = function () {
  64308. this.normal.scaleInPlace(-1);
  64309. this.w = -this.w;
  64310. };
  64311. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64312. // fragments in the appropriate lists. Coplanar polygons go into either
  64313. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64314. // respect to this plane. Polygons in front or in back of this plane go into
  64315. // either `front` or `back`.
  64316. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64317. var COPLANAR = 0;
  64318. var FRONT = 1;
  64319. var BACK = 2;
  64320. var SPANNING = 3;
  64321. // Classify each point as well as the entire polygon into one of the above
  64322. // four classes.
  64323. var polygonType = 0;
  64324. var types = [];
  64325. var i;
  64326. var t;
  64327. for (i = 0; i < polygon.vertices.length; i++) {
  64328. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64329. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64330. polygonType |= type;
  64331. types.push(type);
  64332. }
  64333. // Put the polygon in the correct list, splitting it when necessary.
  64334. switch (polygonType) {
  64335. case COPLANAR:
  64336. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64337. break;
  64338. case FRONT:
  64339. front.push(polygon);
  64340. break;
  64341. case BACK:
  64342. back.push(polygon);
  64343. break;
  64344. case SPANNING:
  64345. var f = [], b = [];
  64346. for (i = 0; i < polygon.vertices.length; i++) {
  64347. var j = (i + 1) % polygon.vertices.length;
  64348. var ti = types[i], tj = types[j];
  64349. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64350. if (ti !== BACK)
  64351. f.push(vi);
  64352. if (ti !== FRONT)
  64353. b.push(ti !== BACK ? vi.clone() : vi);
  64354. if ((ti | tj) === SPANNING) {
  64355. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64356. var v = vi.interpolate(vj, t);
  64357. f.push(v);
  64358. b.push(v.clone());
  64359. }
  64360. }
  64361. var poly;
  64362. if (f.length >= 3) {
  64363. poly = new Polygon(f, polygon.shared);
  64364. if (poly.plane)
  64365. front.push(poly);
  64366. }
  64367. if (b.length >= 3) {
  64368. poly = new Polygon(b, polygon.shared);
  64369. if (poly.plane)
  64370. back.push(poly);
  64371. }
  64372. break;
  64373. }
  64374. };
  64375. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64376. // point is on the plane.
  64377. Plane.EPSILON = 1e-5;
  64378. return Plane;
  64379. }());
  64380. // # class Polygon
  64381. // Represents a convex polygon. The vertices used to initialize a polygon must
  64382. // be coplanar and form a convex loop.
  64383. //
  64384. // Each convex polygon has a `shared` property, which is shared between all
  64385. // polygons that are clones of each other or were split from the same polygon.
  64386. // This can be used to define per-polygon properties (such as surface color).
  64387. var Polygon = /** @class */ (function () {
  64388. function Polygon(vertices, shared) {
  64389. this.vertices = vertices;
  64390. this.shared = shared;
  64391. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64392. }
  64393. Polygon.prototype.clone = function () {
  64394. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64395. return new Polygon(vertices, this.shared);
  64396. };
  64397. Polygon.prototype.flip = function () {
  64398. this.vertices.reverse().map(function (v) { v.flip(); });
  64399. this.plane.flip();
  64400. };
  64401. return Polygon;
  64402. }());
  64403. // # class Node
  64404. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64405. // by picking a polygon to split along. That polygon (and all other coplanar
  64406. // polygons) are added directly to that node and the other polygons are added to
  64407. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64408. // no distinction between internal and leaf nodes.
  64409. var Node = /** @class */ (function () {
  64410. function Node(polygons) {
  64411. this.plane = null;
  64412. this.front = null;
  64413. this.back = null;
  64414. this.polygons = new Array();
  64415. if (polygons) {
  64416. this.build(polygons);
  64417. }
  64418. }
  64419. Node.prototype.clone = function () {
  64420. var node = new Node();
  64421. node.plane = this.plane && this.plane.clone();
  64422. node.front = this.front && this.front.clone();
  64423. node.back = this.back && this.back.clone();
  64424. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64425. return node;
  64426. };
  64427. // Convert solid space to empty space and empty space to solid space.
  64428. Node.prototype.invert = function () {
  64429. for (var i = 0; i < this.polygons.length; i++) {
  64430. this.polygons[i].flip();
  64431. }
  64432. if (this.plane) {
  64433. this.plane.flip();
  64434. }
  64435. if (this.front) {
  64436. this.front.invert();
  64437. }
  64438. if (this.back) {
  64439. this.back.invert();
  64440. }
  64441. var temp = this.front;
  64442. this.front = this.back;
  64443. this.back = temp;
  64444. };
  64445. // Recursively remove all polygons in `polygons` that are inside this BSP
  64446. // tree.
  64447. Node.prototype.clipPolygons = function (polygons) {
  64448. if (!this.plane)
  64449. return polygons.slice();
  64450. var front = new Array(), back = new Array();
  64451. for (var i = 0; i < polygons.length; i++) {
  64452. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64453. }
  64454. if (this.front) {
  64455. front = this.front.clipPolygons(front);
  64456. }
  64457. if (this.back) {
  64458. back = this.back.clipPolygons(back);
  64459. }
  64460. else {
  64461. back = [];
  64462. }
  64463. return front.concat(back);
  64464. };
  64465. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64466. // `bsp`.
  64467. Node.prototype.clipTo = function (bsp) {
  64468. this.polygons = bsp.clipPolygons(this.polygons);
  64469. if (this.front)
  64470. this.front.clipTo(bsp);
  64471. if (this.back)
  64472. this.back.clipTo(bsp);
  64473. };
  64474. // Return a list of all polygons in this BSP tree.
  64475. Node.prototype.allPolygons = function () {
  64476. var polygons = this.polygons.slice();
  64477. if (this.front)
  64478. polygons = polygons.concat(this.front.allPolygons());
  64479. if (this.back)
  64480. polygons = polygons.concat(this.back.allPolygons());
  64481. return polygons;
  64482. };
  64483. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64484. // new polygons are filtered down to the bottom of the tree and become new
  64485. // nodes there. Each set of polygons is partitioned using the first polygon
  64486. // (no heuristic is used to pick a good split).
  64487. Node.prototype.build = function (polygons) {
  64488. if (!polygons.length)
  64489. return;
  64490. if (!this.plane)
  64491. this.plane = polygons[0].plane.clone();
  64492. var front = new Array(), back = new Array();
  64493. for (var i = 0; i < polygons.length; i++) {
  64494. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64495. }
  64496. if (front.length) {
  64497. if (!this.front)
  64498. this.front = new Node();
  64499. this.front.build(front);
  64500. }
  64501. if (back.length) {
  64502. if (!this.back)
  64503. this.back = new Node();
  64504. this.back.build(back);
  64505. }
  64506. };
  64507. return Node;
  64508. }());
  64509. var CSG = /** @class */ (function () {
  64510. function CSG() {
  64511. this.polygons = new Array();
  64512. }
  64513. // Convert BABYLON.Mesh to BABYLON.CSG
  64514. CSG.FromMesh = function (mesh) {
  64515. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64516. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64517. if (mesh instanceof BABYLON.Mesh) {
  64518. mesh.computeWorldMatrix(true);
  64519. matrix = mesh.getWorldMatrix();
  64520. meshPosition = mesh.position.clone();
  64521. meshRotation = mesh.rotation.clone();
  64522. if (mesh.rotationQuaternion) {
  64523. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64524. }
  64525. meshScaling = mesh.scaling.clone();
  64526. }
  64527. else {
  64528. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64529. }
  64530. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64531. var subMeshes = mesh.subMeshes;
  64532. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64533. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64534. vertices = [];
  64535. for (var j = 0; j < 3; j++) {
  64536. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64537. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64538. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64539. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64540. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64541. vertex = new Vertex(position, normal, uv);
  64542. vertices.push(vertex);
  64543. }
  64544. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64545. // To handle the case of degenerated triangle
  64546. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64547. if (polygon.plane)
  64548. polygons.push(polygon);
  64549. }
  64550. }
  64551. var csg = CSG.FromPolygons(polygons);
  64552. csg.matrix = matrix;
  64553. csg.position = meshPosition;
  64554. csg.rotation = meshRotation;
  64555. csg.scaling = meshScaling;
  64556. csg.rotationQuaternion = meshRotationQuaternion;
  64557. currentCSGMeshId++;
  64558. return csg;
  64559. };
  64560. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64561. CSG.FromPolygons = function (polygons) {
  64562. var csg = new CSG();
  64563. csg.polygons = polygons;
  64564. return csg;
  64565. };
  64566. CSG.prototype.clone = function () {
  64567. var csg = new CSG();
  64568. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64569. csg.copyTransformAttributes(this);
  64570. return csg;
  64571. };
  64572. CSG.prototype.union = function (csg) {
  64573. var a = new Node(this.clone().polygons);
  64574. var b = new Node(csg.clone().polygons);
  64575. a.clipTo(b);
  64576. b.clipTo(a);
  64577. b.invert();
  64578. b.clipTo(a);
  64579. b.invert();
  64580. a.build(b.allPolygons());
  64581. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64582. };
  64583. CSG.prototype.unionInPlace = function (csg) {
  64584. var a = new Node(this.polygons);
  64585. var b = new Node(csg.polygons);
  64586. a.clipTo(b);
  64587. b.clipTo(a);
  64588. b.invert();
  64589. b.clipTo(a);
  64590. b.invert();
  64591. a.build(b.allPolygons());
  64592. this.polygons = a.allPolygons();
  64593. };
  64594. CSG.prototype.subtract = function (csg) {
  64595. var a = new Node(this.clone().polygons);
  64596. var b = new Node(csg.clone().polygons);
  64597. a.invert();
  64598. a.clipTo(b);
  64599. b.clipTo(a);
  64600. b.invert();
  64601. b.clipTo(a);
  64602. b.invert();
  64603. a.build(b.allPolygons());
  64604. a.invert();
  64605. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64606. };
  64607. CSG.prototype.subtractInPlace = function (csg) {
  64608. var a = new Node(this.polygons);
  64609. var b = new Node(csg.polygons);
  64610. a.invert();
  64611. a.clipTo(b);
  64612. b.clipTo(a);
  64613. b.invert();
  64614. b.clipTo(a);
  64615. b.invert();
  64616. a.build(b.allPolygons());
  64617. a.invert();
  64618. this.polygons = a.allPolygons();
  64619. };
  64620. CSG.prototype.intersect = function (csg) {
  64621. var a = new Node(this.clone().polygons);
  64622. var b = new Node(csg.clone().polygons);
  64623. a.invert();
  64624. b.clipTo(a);
  64625. b.invert();
  64626. a.clipTo(b);
  64627. b.clipTo(a);
  64628. a.build(b.allPolygons());
  64629. a.invert();
  64630. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64631. };
  64632. CSG.prototype.intersectInPlace = function (csg) {
  64633. var a = new Node(this.polygons);
  64634. var b = new Node(csg.polygons);
  64635. a.invert();
  64636. b.clipTo(a);
  64637. b.invert();
  64638. a.clipTo(b);
  64639. b.clipTo(a);
  64640. a.build(b.allPolygons());
  64641. a.invert();
  64642. this.polygons = a.allPolygons();
  64643. };
  64644. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64645. // not modified.
  64646. CSG.prototype.inverse = function () {
  64647. var csg = this.clone();
  64648. csg.inverseInPlace();
  64649. return csg;
  64650. };
  64651. CSG.prototype.inverseInPlace = function () {
  64652. this.polygons.map(function (p) { p.flip(); });
  64653. };
  64654. // This is used to keep meshes transformations so they can be restored
  64655. // when we build back a Babylon Mesh
  64656. // NB : All CSG operations are performed in world coordinates
  64657. CSG.prototype.copyTransformAttributes = function (csg) {
  64658. this.matrix = csg.matrix;
  64659. this.position = csg.position;
  64660. this.rotation = csg.rotation;
  64661. this.scaling = csg.scaling;
  64662. this.rotationQuaternion = csg.rotationQuaternion;
  64663. return this;
  64664. };
  64665. // Build Raw mesh from CSG
  64666. // Coordinates here are in world space
  64667. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64668. var matrix = this.matrix.clone();
  64669. matrix.invert();
  64670. 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;
  64671. if (keepSubMeshes) {
  64672. // Sort Polygons, since subMeshes are indices range
  64673. polygons.sort(function (a, b) {
  64674. if (a.shared.meshId === b.shared.meshId) {
  64675. return a.shared.subMeshId - b.shared.subMeshId;
  64676. }
  64677. else {
  64678. return a.shared.meshId - b.shared.meshId;
  64679. }
  64680. });
  64681. }
  64682. for (var i = 0, il = polygons.length; i < il; i++) {
  64683. polygon = polygons[i];
  64684. // Building SubMeshes
  64685. if (!subMesh_dict[polygon.shared.meshId]) {
  64686. subMesh_dict[polygon.shared.meshId] = {};
  64687. }
  64688. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64689. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64690. indexStart: +Infinity,
  64691. indexEnd: -Infinity,
  64692. materialIndex: polygon.shared.materialIndex
  64693. };
  64694. }
  64695. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64696. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64697. polygonIndices[0] = 0;
  64698. polygonIndices[1] = j - 1;
  64699. polygonIndices[2] = j;
  64700. for (var k = 0; k < 3; k++) {
  64701. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64702. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64703. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64704. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64705. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64706. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64707. // Check if 2 points can be merged
  64708. if (!(typeof vertex_idx !== 'undefined' &&
  64709. normals[vertex_idx * 3] === localNormal.x &&
  64710. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64711. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64712. uvs[vertex_idx * 2] === uv.x &&
  64713. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64714. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64715. uvs.push(uv.x, uv.y);
  64716. normals.push(normal.x, normal.y, normal.z);
  64717. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64718. }
  64719. indices.push(vertex_idx);
  64720. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64721. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64722. currentIndex++;
  64723. }
  64724. }
  64725. }
  64726. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64727. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64728. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64729. mesh.setIndices(indices, null);
  64730. if (keepSubMeshes) {
  64731. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64732. var materialIndexOffset = 0, materialMaxIndex;
  64733. mesh.subMeshes = new Array();
  64734. for (var m in subMesh_dict) {
  64735. materialMaxIndex = -1;
  64736. for (var sm in subMesh_dict[m]) {
  64737. subMesh_obj = subMesh_dict[m][sm];
  64738. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64739. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64740. }
  64741. materialIndexOffset += ++materialMaxIndex;
  64742. }
  64743. }
  64744. return mesh;
  64745. };
  64746. // Build Mesh from CSG taking material and transforms into account
  64747. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64748. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64749. mesh.material = material;
  64750. mesh.position.copyFrom(this.position);
  64751. mesh.rotation.copyFrom(this.rotation);
  64752. if (this.rotationQuaternion) {
  64753. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64754. }
  64755. mesh.scaling.copyFrom(this.scaling);
  64756. mesh.computeWorldMatrix(true);
  64757. return mesh;
  64758. };
  64759. return CSG;
  64760. }());
  64761. BABYLON.CSG = CSG;
  64762. })(BABYLON || (BABYLON = {}));
  64763. //# sourceMappingURL=babylon.csg.js.map
  64764. var BABYLON;
  64765. (function (BABYLON) {
  64766. var LensFlare = /** @class */ (function () {
  64767. function LensFlare(size, position, color, imgUrl, system) {
  64768. this.size = size;
  64769. this.position = position;
  64770. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64771. this.color = color || new BABYLON.Color3(1, 1, 1);
  64772. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64773. this._system = system;
  64774. system.lensFlares.push(this);
  64775. }
  64776. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64777. return new LensFlare(size, position, color, imgUrl, system);
  64778. };
  64779. LensFlare.prototype.dispose = function () {
  64780. if (this.texture) {
  64781. this.texture.dispose();
  64782. }
  64783. // Remove from scene
  64784. var index = this._system.lensFlares.indexOf(this);
  64785. this._system.lensFlares.splice(index, 1);
  64786. };
  64787. ;
  64788. return LensFlare;
  64789. }());
  64790. BABYLON.LensFlare = LensFlare;
  64791. })(BABYLON || (BABYLON = {}));
  64792. //# sourceMappingURL=babylon.lensFlare.js.map
  64793. var BABYLON;
  64794. (function (BABYLON) {
  64795. var LensFlareSystem = /** @class */ (function () {
  64796. function LensFlareSystem(name, emitter, scene) {
  64797. this.name = name;
  64798. this.lensFlares = new Array();
  64799. this.borderLimit = 300;
  64800. this.viewportBorder = 0;
  64801. this.layerMask = 0x0FFFFFFF;
  64802. this._vertexBuffers = {};
  64803. this._isEnabled = true;
  64804. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64805. this._emitter = emitter;
  64806. this.id = name;
  64807. scene.lensFlareSystems.push(this);
  64808. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64809. var engine = scene.getEngine();
  64810. // VBO
  64811. var vertices = [];
  64812. vertices.push(1, 1);
  64813. vertices.push(-1, 1);
  64814. vertices.push(-1, -1);
  64815. vertices.push(1, -1);
  64816. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64817. // Indices
  64818. var indices = [];
  64819. indices.push(0);
  64820. indices.push(1);
  64821. indices.push(2);
  64822. indices.push(0);
  64823. indices.push(2);
  64824. indices.push(3);
  64825. this._indexBuffer = engine.createIndexBuffer(indices);
  64826. // Effects
  64827. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64828. }
  64829. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64830. get: function () {
  64831. return this._isEnabled;
  64832. },
  64833. set: function (value) {
  64834. this._isEnabled = value;
  64835. },
  64836. enumerable: true,
  64837. configurable: true
  64838. });
  64839. LensFlareSystem.prototype.getScene = function () {
  64840. return this._scene;
  64841. };
  64842. LensFlareSystem.prototype.getEmitter = function () {
  64843. return this._emitter;
  64844. };
  64845. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64846. this._emitter = newEmitter;
  64847. };
  64848. LensFlareSystem.prototype.getEmitterPosition = function () {
  64849. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  64850. };
  64851. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  64852. var position = this.getEmitterPosition();
  64853. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  64854. this._positionX = position.x;
  64855. this._positionY = position.y;
  64856. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  64857. if (this.viewportBorder > 0) {
  64858. globalViewport.x -= this.viewportBorder;
  64859. globalViewport.y -= this.viewportBorder;
  64860. globalViewport.width += this.viewportBorder * 2;
  64861. globalViewport.height += this.viewportBorder * 2;
  64862. position.x += this.viewportBorder;
  64863. position.y += this.viewportBorder;
  64864. this._positionX += this.viewportBorder;
  64865. this._positionY += this.viewportBorder;
  64866. }
  64867. if (position.z > 0) {
  64868. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  64869. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  64870. return true;
  64871. }
  64872. return true;
  64873. }
  64874. return false;
  64875. };
  64876. LensFlareSystem.prototype._isVisible = function () {
  64877. if (!this._isEnabled || !this._scene.activeCamera) {
  64878. return false;
  64879. }
  64880. var emitterPosition = this.getEmitterPosition();
  64881. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  64882. var distance = direction.length();
  64883. direction.normalize();
  64884. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  64885. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  64886. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  64887. };
  64888. LensFlareSystem.prototype.render = function () {
  64889. if (!this._effect.isReady() || !this._scene.activeCamera)
  64890. return false;
  64891. var engine = this._scene.getEngine();
  64892. var viewport = this._scene.activeCamera.viewport;
  64893. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  64894. // Position
  64895. if (!this.computeEffectivePosition(globalViewport)) {
  64896. return false;
  64897. }
  64898. // Visibility
  64899. if (!this._isVisible()) {
  64900. return false;
  64901. }
  64902. // Intensity
  64903. var awayX;
  64904. var awayY;
  64905. if (this._positionX < this.borderLimit + globalViewport.x) {
  64906. awayX = this.borderLimit + globalViewport.x - this._positionX;
  64907. }
  64908. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  64909. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  64910. }
  64911. else {
  64912. awayX = 0;
  64913. }
  64914. if (this._positionY < this.borderLimit + globalViewport.y) {
  64915. awayY = this.borderLimit + globalViewport.y - this._positionY;
  64916. }
  64917. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  64918. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  64919. }
  64920. else {
  64921. awayY = 0;
  64922. }
  64923. var away = (awayX > awayY) ? awayX : awayY;
  64924. away -= this.viewportBorder;
  64925. if (away > this.borderLimit) {
  64926. away = this.borderLimit;
  64927. }
  64928. var intensity = 1.0 - (away / this.borderLimit);
  64929. if (intensity < 0) {
  64930. return false;
  64931. }
  64932. if (intensity > 1.0) {
  64933. intensity = 1.0;
  64934. }
  64935. if (this.viewportBorder > 0) {
  64936. globalViewport.x += this.viewportBorder;
  64937. globalViewport.y += this.viewportBorder;
  64938. globalViewport.width -= this.viewportBorder * 2;
  64939. globalViewport.height -= this.viewportBorder * 2;
  64940. this._positionX -= this.viewportBorder;
  64941. this._positionY -= this.viewportBorder;
  64942. }
  64943. // Position
  64944. var centerX = globalViewport.x + globalViewport.width / 2;
  64945. var centerY = globalViewport.y + globalViewport.height / 2;
  64946. var distX = centerX - this._positionX;
  64947. var distY = centerY - this._positionY;
  64948. // Effects
  64949. engine.enableEffect(this._effect);
  64950. engine.setState(false);
  64951. engine.setDepthBuffer(false);
  64952. // VBOs
  64953. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64954. // Flares
  64955. for (var index = 0; index < this.lensFlares.length; index++) {
  64956. var flare = this.lensFlares[index];
  64957. engine.setAlphaMode(flare.alphaMode);
  64958. var x = centerX - (distX * flare.position);
  64959. var y = centerY - (distY * flare.position);
  64960. var cw = flare.size;
  64961. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  64962. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  64963. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  64964. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  64965. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  64966. // Texture
  64967. this._effect.setTexture("textureSampler", flare.texture);
  64968. // Color
  64969. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  64970. // Draw order
  64971. engine.draw(true, 0, 6);
  64972. }
  64973. engine.setDepthBuffer(true);
  64974. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64975. return true;
  64976. };
  64977. LensFlareSystem.prototype.dispose = function () {
  64978. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64979. if (vertexBuffer) {
  64980. vertexBuffer.dispose();
  64981. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64982. }
  64983. if (this._indexBuffer) {
  64984. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64985. this._indexBuffer = null;
  64986. }
  64987. while (this.lensFlares.length) {
  64988. this.lensFlares[0].dispose();
  64989. }
  64990. // Remove from scene
  64991. var index = this._scene.lensFlareSystems.indexOf(this);
  64992. this._scene.lensFlareSystems.splice(index, 1);
  64993. };
  64994. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  64995. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  64996. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  64997. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  64998. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  64999. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  65000. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  65001. var parsedFlare = parsedLensFlareSystem.flares[index];
  65002. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  65003. }
  65004. return lensFlareSystem;
  65005. };
  65006. LensFlareSystem.prototype.serialize = function () {
  65007. var serializationObject = {};
  65008. serializationObject.id = this.id;
  65009. serializationObject.name = this.name;
  65010. serializationObject.emitterId = this.getEmitter().id;
  65011. serializationObject.borderLimit = this.borderLimit;
  65012. serializationObject.flares = [];
  65013. for (var index = 0; index < this.lensFlares.length; index++) {
  65014. var flare = this.lensFlares[index];
  65015. serializationObject.flares.push({
  65016. size: flare.size,
  65017. position: flare.position,
  65018. color: flare.color.asArray(),
  65019. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  65020. });
  65021. }
  65022. return serializationObject;
  65023. };
  65024. return LensFlareSystem;
  65025. }());
  65026. BABYLON.LensFlareSystem = LensFlareSystem;
  65027. })(BABYLON || (BABYLON = {}));
  65028. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  65029. var BABYLON;
  65030. (function (BABYLON) {
  65031. /**
  65032. * This is a holder class for the physics joint created by the physics plugin.
  65033. * It holds a set of functions to control the underlying joint.
  65034. */
  65035. var PhysicsJoint = /** @class */ (function () {
  65036. function PhysicsJoint(type, jointData) {
  65037. this.type = type;
  65038. this.jointData = jointData;
  65039. jointData.nativeParams = jointData.nativeParams || {};
  65040. }
  65041. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  65042. get: function () {
  65043. return this._physicsJoint;
  65044. },
  65045. set: function (newJoint) {
  65046. if (this._physicsJoint) {
  65047. //remove from the wolrd
  65048. }
  65049. this._physicsJoint = newJoint;
  65050. },
  65051. enumerable: true,
  65052. configurable: true
  65053. });
  65054. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  65055. set: function (physicsPlugin) {
  65056. this._physicsPlugin = physicsPlugin;
  65057. },
  65058. enumerable: true,
  65059. configurable: true
  65060. });
  65061. /**
  65062. * Execute a function that is physics-plugin specific.
  65063. * @param {Function} func the function that will be executed.
  65064. * It accepts two parameters: the physics world and the physics joint.
  65065. */
  65066. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  65067. func(this._physicsPlugin.world, this._physicsJoint);
  65068. };
  65069. //TODO check if the native joints are the same
  65070. //Joint Types
  65071. PhysicsJoint.DistanceJoint = 0;
  65072. PhysicsJoint.HingeJoint = 1;
  65073. PhysicsJoint.BallAndSocketJoint = 2;
  65074. PhysicsJoint.WheelJoint = 3;
  65075. PhysicsJoint.SliderJoint = 4;
  65076. //OIMO
  65077. PhysicsJoint.PrismaticJoint = 5;
  65078. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  65079. PhysicsJoint.UniversalJoint = 6;
  65080. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  65081. //Cannon
  65082. //Similar to a Ball-Joint. Different in params
  65083. PhysicsJoint.PointToPointJoint = 8;
  65084. //Cannon only at the moment
  65085. PhysicsJoint.SpringJoint = 9;
  65086. PhysicsJoint.LockJoint = 10;
  65087. return PhysicsJoint;
  65088. }());
  65089. BABYLON.PhysicsJoint = PhysicsJoint;
  65090. /**
  65091. * A class representing a physics distance joint.
  65092. */
  65093. var DistanceJoint = /** @class */ (function (_super) {
  65094. __extends(DistanceJoint, _super);
  65095. function DistanceJoint(jointData) {
  65096. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  65097. }
  65098. /**
  65099. * Update the predefined distance.
  65100. */
  65101. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  65102. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  65103. };
  65104. return DistanceJoint;
  65105. }(PhysicsJoint));
  65106. BABYLON.DistanceJoint = DistanceJoint;
  65107. var MotorEnabledJoint = /** @class */ (function (_super) {
  65108. __extends(MotorEnabledJoint, _super);
  65109. function MotorEnabledJoint(type, jointData) {
  65110. return _super.call(this, type, jointData) || this;
  65111. }
  65112. /**
  65113. * Set the motor values.
  65114. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65115. * @param {number} force the force to apply
  65116. * @param {number} maxForce max force for this motor.
  65117. */
  65118. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  65119. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65120. };
  65121. /**
  65122. * Set the motor's limits.
  65123. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65124. */
  65125. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65126. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65127. };
  65128. return MotorEnabledJoint;
  65129. }(PhysicsJoint));
  65130. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65131. /**
  65132. * This class represents a single hinge physics joint
  65133. */
  65134. var HingeJoint = /** @class */ (function (_super) {
  65135. __extends(HingeJoint, _super);
  65136. function HingeJoint(jointData) {
  65137. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65138. }
  65139. /**
  65140. * Set the motor values.
  65141. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65142. * @param {number} force the force to apply
  65143. * @param {number} maxForce max force for this motor.
  65144. */
  65145. HingeJoint.prototype.setMotor = function (force, maxForce) {
  65146. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65147. };
  65148. /**
  65149. * Set the motor's limits.
  65150. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65151. */
  65152. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65153. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65154. };
  65155. return HingeJoint;
  65156. }(MotorEnabledJoint));
  65157. BABYLON.HingeJoint = HingeJoint;
  65158. /**
  65159. * This class represents a dual hinge physics joint (same as wheel joint)
  65160. */
  65161. var Hinge2Joint = /** @class */ (function (_super) {
  65162. __extends(Hinge2Joint, _super);
  65163. function Hinge2Joint(jointData) {
  65164. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  65165. }
  65166. /**
  65167. * Set the motor values.
  65168. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65169. * @param {number} force the force to apply
  65170. * @param {number} maxForce max force for this motor.
  65171. * @param {motorIndex} the motor's index, 0 or 1.
  65172. */
  65173. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  65174. if (motorIndex === void 0) { motorIndex = 0; }
  65175. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  65176. };
  65177. /**
  65178. * Set the motor limits.
  65179. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65180. * @param {number} upperLimit the upper limit
  65181. * @param {number} lowerLimit lower limit
  65182. * @param {motorIndex} the motor's index, 0 or 1.
  65183. */
  65184. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  65185. if (motorIndex === void 0) { motorIndex = 0; }
  65186. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  65187. };
  65188. return Hinge2Joint;
  65189. }(MotorEnabledJoint));
  65190. BABYLON.Hinge2Joint = Hinge2Joint;
  65191. })(BABYLON || (BABYLON = {}));
  65192. //# sourceMappingURL=babylon.physicsJoint.js.map
  65193. var BABYLON;
  65194. (function (BABYLON) {
  65195. var PhysicsImpostor = /** @class */ (function () {
  65196. function PhysicsImpostor(object, type, _options, _scene) {
  65197. if (_options === void 0) { _options = { mass: 0 }; }
  65198. var _this = this;
  65199. this.object = object;
  65200. this.type = type;
  65201. this._options = _options;
  65202. this._scene = _scene;
  65203. this._bodyUpdateRequired = false;
  65204. this._onBeforePhysicsStepCallbacks = new Array();
  65205. this._onAfterPhysicsStepCallbacks = new Array();
  65206. this._onPhysicsCollideCallbacks = [];
  65207. this._deltaPosition = BABYLON.Vector3.Zero();
  65208. this._isDisposed = false;
  65209. //temp variables for parent rotation calculations
  65210. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  65211. this._tmpQuat = new BABYLON.Quaternion();
  65212. this._tmpQuat2 = new BABYLON.Quaternion();
  65213. /**
  65214. * this function is executed by the physics engine.
  65215. */
  65216. this.beforeStep = function () {
  65217. if (!_this._physicsEngine) {
  65218. return;
  65219. }
  65220. _this.object.translate(_this._deltaPosition, -1);
  65221. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  65222. _this.object.computeWorldMatrix(false);
  65223. if (_this.object.parent && _this.object.rotationQuaternion) {
  65224. _this.getParentsRotation();
  65225. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  65226. }
  65227. else {
  65228. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  65229. }
  65230. if (!_this._options.disableBidirectionalTransformation) {
  65231. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  65232. }
  65233. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65234. func(_this);
  65235. });
  65236. };
  65237. /**
  65238. * this function is executed by the physics engine.
  65239. */
  65240. this.afterStep = function () {
  65241. if (!_this._physicsEngine) {
  65242. return;
  65243. }
  65244. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  65245. func(_this);
  65246. });
  65247. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65248. // object has now its world rotation. needs to be converted to local.
  65249. if (_this.object.parent && _this.object.rotationQuaternion) {
  65250. _this.getParentsRotation();
  65251. _this._tmpQuat.conjugateInPlace();
  65252. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  65253. }
  65254. // take the position set and make it the absolute position of this object.
  65255. _this.object.setAbsolutePosition(_this.object.position);
  65256. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  65257. _this.object.translate(_this._deltaPosition, 1);
  65258. };
  65259. /**
  65260. * Legacy collision detection event support
  65261. */
  65262. this.onCollideEvent = null;
  65263. //event and body object due to cannon's event-based architecture.
  65264. this.onCollide = function (e) {
  65265. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65266. return;
  65267. }
  65268. if (!_this._physicsEngine) {
  65269. return;
  65270. }
  65271. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65272. if (otherImpostor) {
  65273. // Legacy collision detection event support
  65274. if (_this.onCollideEvent) {
  65275. _this.onCollideEvent(_this, otherImpostor);
  65276. }
  65277. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65278. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65279. }).forEach(function (obj) {
  65280. obj.callback(_this, otherImpostor);
  65281. });
  65282. }
  65283. };
  65284. //sanity check!
  65285. if (!this.object) {
  65286. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65287. return;
  65288. }
  65289. //legacy support for old syntax.
  65290. if (!this._scene && object.getScene) {
  65291. this._scene = object.getScene();
  65292. }
  65293. if (!this._scene) {
  65294. return;
  65295. }
  65296. this._physicsEngine = this._scene.getPhysicsEngine();
  65297. if (!this._physicsEngine) {
  65298. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65299. }
  65300. else {
  65301. //set the object's quaternion, if not set
  65302. if (!this.object.rotationQuaternion) {
  65303. if (this.object.rotation) {
  65304. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65305. }
  65306. else {
  65307. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65308. }
  65309. }
  65310. //default options params
  65311. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65312. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65313. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65314. this._joints = [];
  65315. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65316. if (!this.object.parent || this._options.ignoreParent) {
  65317. this._init();
  65318. }
  65319. else if (this.object.parent.physicsImpostor) {
  65320. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65321. }
  65322. }
  65323. }
  65324. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65325. get: function () {
  65326. return this._isDisposed;
  65327. },
  65328. enumerable: true,
  65329. configurable: true
  65330. });
  65331. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65332. get: function () {
  65333. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65334. },
  65335. set: function (value) {
  65336. this.setMass(value);
  65337. },
  65338. enumerable: true,
  65339. configurable: true
  65340. });
  65341. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65342. get: function () {
  65343. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65344. },
  65345. set: function (value) {
  65346. if (!this._physicsEngine) {
  65347. return;
  65348. }
  65349. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65350. },
  65351. enumerable: true,
  65352. configurable: true
  65353. });
  65354. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65355. get: function () {
  65356. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65357. },
  65358. set: function (value) {
  65359. if (!this._physicsEngine) {
  65360. return;
  65361. }
  65362. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65363. },
  65364. enumerable: true,
  65365. configurable: true
  65366. });
  65367. /**
  65368. * This function will completly initialize this impostor.
  65369. * It will create a new body - but only if this mesh has no parent.
  65370. * If it has, this impostor will not be used other than to define the impostor
  65371. * of the child mesh.
  65372. */
  65373. PhysicsImpostor.prototype._init = function () {
  65374. if (!this._physicsEngine) {
  65375. return;
  65376. }
  65377. this._physicsEngine.removeImpostor(this);
  65378. this.physicsBody = null;
  65379. this._parent = this._parent || this._getPhysicsParent();
  65380. if (!this.parent || this._options.ignoreParent) {
  65381. this._physicsEngine.addImpostor(this);
  65382. }
  65383. };
  65384. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65385. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65386. var parentMesh = this.object.parent;
  65387. return parentMesh.physicsImpostor;
  65388. }
  65389. return null;
  65390. };
  65391. /**
  65392. * Should a new body be generated.
  65393. */
  65394. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65395. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65396. };
  65397. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65398. this.forceUpdate();
  65399. };
  65400. /**
  65401. * Force a regeneration of this or the parent's impostor's body.
  65402. * Use under cautious - This will remove all joints already implemented.
  65403. */
  65404. PhysicsImpostor.prototype.forceUpdate = function () {
  65405. this._init();
  65406. if (this.parent && !this._options.ignoreParent) {
  65407. this.parent.forceUpdate();
  65408. }
  65409. };
  65410. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65411. /*public get mesh(): AbstractMesh {
  65412. return this._mesh;
  65413. }*/
  65414. /**
  65415. * Gets the body that holds this impostor. Either its own, or its parent.
  65416. */
  65417. get: function () {
  65418. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65419. },
  65420. /**
  65421. * Set the physics body. Used mainly by the physics engine/plugin
  65422. */
  65423. set: function (physicsBody) {
  65424. if (this._physicsBody && this._physicsEngine) {
  65425. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65426. }
  65427. this._physicsBody = physicsBody;
  65428. this.resetUpdateFlags();
  65429. },
  65430. enumerable: true,
  65431. configurable: true
  65432. });
  65433. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65434. get: function () {
  65435. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65436. },
  65437. set: function (value) {
  65438. this._parent = value;
  65439. },
  65440. enumerable: true,
  65441. configurable: true
  65442. });
  65443. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65444. this._bodyUpdateRequired = false;
  65445. };
  65446. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65447. if (this.object.getBoundingInfo) {
  65448. var q = this.object.rotationQuaternion;
  65449. //reset rotation
  65450. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65451. //calculate the world matrix with no rotation
  65452. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65453. var boundingInfo = this.object.getBoundingInfo();
  65454. var size = void 0;
  65455. if (boundingInfo) {
  65456. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65457. }
  65458. else {
  65459. size = BABYLON.Vector3.Zero();
  65460. }
  65461. //bring back the rotation
  65462. this.object.rotationQuaternion = q;
  65463. //calculate the world matrix with the new rotation
  65464. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65465. return size;
  65466. }
  65467. else {
  65468. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65469. }
  65470. };
  65471. PhysicsImpostor.prototype.getObjectCenter = function () {
  65472. if (this.object.getBoundingInfo) {
  65473. var boundingInfo = this.object.getBoundingInfo();
  65474. if (!boundingInfo) {
  65475. return this.object.position;
  65476. }
  65477. return boundingInfo.boundingBox.centerWorld;
  65478. }
  65479. else {
  65480. return this.object.position;
  65481. }
  65482. };
  65483. /**
  65484. * Get a specific parametes from the options parameter.
  65485. */
  65486. PhysicsImpostor.prototype.getParam = function (paramName) {
  65487. return this._options[paramName];
  65488. };
  65489. /**
  65490. * Sets a specific parameter in the options given to the physics plugin
  65491. */
  65492. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65493. this._options[paramName] = value;
  65494. this._bodyUpdateRequired = true;
  65495. };
  65496. /**
  65497. * Specifically change the body's mass option. Won't recreate the physics body object
  65498. */
  65499. PhysicsImpostor.prototype.setMass = function (mass) {
  65500. if (this.getParam("mass") !== mass) {
  65501. this.setParam("mass", mass);
  65502. }
  65503. if (this._physicsEngine) {
  65504. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65505. }
  65506. };
  65507. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65508. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65509. };
  65510. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65511. if (this._physicsEngine) {
  65512. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65513. }
  65514. };
  65515. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65516. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65517. };
  65518. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65519. if (this._physicsEngine) {
  65520. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65521. }
  65522. };
  65523. /**
  65524. * Execute a function with the physics plugin native code.
  65525. * Provide a function the will have two variables - the world object and the physics body object.
  65526. */
  65527. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65528. if (this._physicsEngine) {
  65529. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65530. }
  65531. };
  65532. /**
  65533. * Register a function that will be executed before the physics world is stepping forward.
  65534. */
  65535. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65536. this._onBeforePhysicsStepCallbacks.push(func);
  65537. };
  65538. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65539. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65540. if (index > -1) {
  65541. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65542. }
  65543. else {
  65544. BABYLON.Tools.Warn("Function to remove was not found");
  65545. }
  65546. };
  65547. /**
  65548. * Register a function that will be executed after the physics step
  65549. */
  65550. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65551. this._onAfterPhysicsStepCallbacks.push(func);
  65552. };
  65553. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65554. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65555. if (index > -1) {
  65556. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65557. }
  65558. else {
  65559. BABYLON.Tools.Warn("Function to remove was not found");
  65560. }
  65561. };
  65562. /**
  65563. * register a function that will be executed when this impostor collides against a different body.
  65564. */
  65565. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65566. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65567. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65568. };
  65569. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65570. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65571. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65572. if (index > -1) {
  65573. this._onPhysicsCollideCallbacks.splice(index, 1);
  65574. }
  65575. else {
  65576. BABYLON.Tools.Warn("Function to remove was not found");
  65577. }
  65578. };
  65579. PhysicsImpostor.prototype.getParentsRotation = function () {
  65580. var parent = this.object.parent;
  65581. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  65582. while (parent) {
  65583. if (parent.rotationQuaternion) {
  65584. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  65585. }
  65586. else {
  65587. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  65588. }
  65589. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  65590. parent = parent.parent;
  65591. }
  65592. return this._tmpQuat;
  65593. };
  65594. /**
  65595. * Apply a force
  65596. */
  65597. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65598. if (this._physicsEngine) {
  65599. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65600. }
  65601. return this;
  65602. };
  65603. /**
  65604. * Apply an impulse
  65605. */
  65606. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65607. if (this._physicsEngine) {
  65608. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65609. }
  65610. return this;
  65611. };
  65612. /**
  65613. * A help function to create a joint.
  65614. */
  65615. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65616. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65617. this.addJoint(otherImpostor, joint);
  65618. return this;
  65619. };
  65620. /**
  65621. * Add a joint to this impostor with a different impostor.
  65622. */
  65623. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65624. this._joints.push({
  65625. otherImpostor: otherImpostor,
  65626. joint: joint
  65627. });
  65628. if (this._physicsEngine) {
  65629. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65630. }
  65631. return this;
  65632. };
  65633. /**
  65634. * Will keep this body still, in a sleep mode.
  65635. */
  65636. PhysicsImpostor.prototype.sleep = function () {
  65637. if (this._physicsEngine) {
  65638. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65639. }
  65640. return this;
  65641. };
  65642. /**
  65643. * Wake the body up.
  65644. */
  65645. PhysicsImpostor.prototype.wakeUp = function () {
  65646. if (this._physicsEngine) {
  65647. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65648. }
  65649. return this;
  65650. };
  65651. PhysicsImpostor.prototype.clone = function (newObject) {
  65652. if (!newObject)
  65653. return null;
  65654. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65655. };
  65656. PhysicsImpostor.prototype.dispose = function () {
  65657. var _this = this;
  65658. //no dispose if no physics engine is available.
  65659. if (!this._physicsEngine) {
  65660. return;
  65661. }
  65662. this._joints.forEach(function (j) {
  65663. if (_this._physicsEngine) {
  65664. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65665. }
  65666. });
  65667. //dispose the physics body
  65668. this._physicsEngine.removeImpostor(this);
  65669. if (this.parent) {
  65670. this.parent.forceUpdate();
  65671. }
  65672. else {
  65673. /*this._object.getChildMeshes().forEach(function(mesh) {
  65674. if (mesh.physicsImpostor) {
  65675. if (disposeChildren) {
  65676. mesh.physicsImpostor.dispose();
  65677. mesh.physicsImpostor = null;
  65678. }
  65679. }
  65680. })*/
  65681. }
  65682. this._isDisposed = true;
  65683. };
  65684. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65685. this._deltaPosition.copyFrom(position);
  65686. };
  65687. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65688. if (!this._deltaRotation) {
  65689. this._deltaRotation = new BABYLON.Quaternion();
  65690. }
  65691. this._deltaRotation.copyFrom(rotation);
  65692. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65693. };
  65694. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65695. if (this._physicsEngine) {
  65696. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65697. }
  65698. return this;
  65699. };
  65700. PhysicsImpostor.prototype.getRadius = function () {
  65701. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65702. };
  65703. /**
  65704. * Sync a bone with this impostor
  65705. * @param bone The bone to sync to the impostor.
  65706. * @param boneMesh The mesh that the bone is influencing.
  65707. * @param jointPivot The pivot of the joint / bone in local space.
  65708. * @param distToJoint Optional distance from the impostor to the joint.
  65709. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65710. */
  65711. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65712. var tempVec = PhysicsImpostor._tmpVecs[0];
  65713. var mesh = this.object;
  65714. if (mesh.rotationQuaternion) {
  65715. if (adjustRotation) {
  65716. var tempQuat = PhysicsImpostor._tmpQuat;
  65717. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65718. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65719. }
  65720. else {
  65721. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65722. }
  65723. }
  65724. tempVec.x = 0;
  65725. tempVec.y = 0;
  65726. tempVec.z = 0;
  65727. if (jointPivot) {
  65728. tempVec.x = jointPivot.x;
  65729. tempVec.y = jointPivot.y;
  65730. tempVec.z = jointPivot.z;
  65731. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65732. if (distToJoint === undefined || distToJoint === null) {
  65733. distToJoint = jointPivot.length();
  65734. }
  65735. tempVec.x *= distToJoint;
  65736. tempVec.y *= distToJoint;
  65737. tempVec.z *= distToJoint;
  65738. }
  65739. if (bone.getParent()) {
  65740. tempVec.addInPlace(mesh.getAbsolutePosition());
  65741. bone.setAbsolutePosition(tempVec, boneMesh);
  65742. }
  65743. else {
  65744. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65745. boneMesh.position.x -= tempVec.x;
  65746. boneMesh.position.y -= tempVec.y;
  65747. boneMesh.position.z -= tempVec.z;
  65748. }
  65749. };
  65750. /**
  65751. * Sync impostor to a bone
  65752. * @param bone The bone that the impostor will be synced to.
  65753. * @param boneMesh The mesh that the bone is influencing.
  65754. * @param jointPivot The pivot of the joint / bone in local space.
  65755. * @param distToJoint Optional distance from the impostor to the joint.
  65756. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65757. * @param boneAxis Optional vector3 axis the bone is aligned with
  65758. */
  65759. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65760. var mesh = this.object;
  65761. if (mesh.rotationQuaternion) {
  65762. if (adjustRotation) {
  65763. var tempQuat = PhysicsImpostor._tmpQuat;
  65764. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65765. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65766. }
  65767. else {
  65768. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65769. }
  65770. }
  65771. var pos = PhysicsImpostor._tmpVecs[0];
  65772. var boneDir = PhysicsImpostor._tmpVecs[1];
  65773. if (!boneAxis) {
  65774. boneAxis = PhysicsImpostor._tmpVecs[2];
  65775. boneAxis.x = 0;
  65776. boneAxis.y = 1;
  65777. boneAxis.z = 0;
  65778. }
  65779. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65780. bone.getAbsolutePositionToRef(boneMesh, pos);
  65781. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65782. distToJoint = jointPivot.length();
  65783. }
  65784. if (distToJoint !== undefined && distToJoint !== null) {
  65785. pos.x += boneDir.x * distToJoint;
  65786. pos.y += boneDir.y * distToJoint;
  65787. pos.z += boneDir.z * distToJoint;
  65788. }
  65789. mesh.setAbsolutePosition(pos);
  65790. };
  65791. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65792. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65793. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65794. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65795. //Impostor types
  65796. PhysicsImpostor.NoImpostor = 0;
  65797. PhysicsImpostor.SphereImpostor = 1;
  65798. PhysicsImpostor.BoxImpostor = 2;
  65799. PhysicsImpostor.PlaneImpostor = 3;
  65800. PhysicsImpostor.MeshImpostor = 4;
  65801. PhysicsImpostor.CylinderImpostor = 7;
  65802. PhysicsImpostor.ParticleImpostor = 8;
  65803. PhysicsImpostor.HeightmapImpostor = 9;
  65804. return PhysicsImpostor;
  65805. }());
  65806. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65807. })(BABYLON || (BABYLON = {}));
  65808. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65809. var BABYLON;
  65810. (function (BABYLON) {
  65811. var PhysicsEngine = /** @class */ (function () {
  65812. function PhysicsEngine(gravity, _physicsPlugin) {
  65813. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65814. this._physicsPlugin = _physicsPlugin;
  65815. //new methods and parameters
  65816. this._impostors = [];
  65817. this._joints = [];
  65818. if (!this._physicsPlugin.isSupported()) {
  65819. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65820. + "Please make sure it is included.");
  65821. }
  65822. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65823. this.setGravity(gravity);
  65824. this.setTimeStep();
  65825. }
  65826. PhysicsEngine.prototype.setGravity = function (gravity) {
  65827. this.gravity = gravity;
  65828. this._physicsPlugin.setGravity(this.gravity);
  65829. };
  65830. /**
  65831. * Set the time step of the physics engine.
  65832. * default is 1/60.
  65833. * To slow it down, enter 1/600 for example.
  65834. * To speed it up, 1/30
  65835. * @param {number} newTimeStep the new timestep to apply to this world.
  65836. */
  65837. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65838. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65839. this._physicsPlugin.setTimeStep(newTimeStep);
  65840. };
  65841. /**
  65842. * Get the time step of the physics engine.
  65843. */
  65844. PhysicsEngine.prototype.getTimeStep = function () {
  65845. return this._physicsPlugin.getTimeStep();
  65846. };
  65847. PhysicsEngine.prototype.dispose = function () {
  65848. this._impostors.forEach(function (impostor) {
  65849. impostor.dispose();
  65850. });
  65851. this._physicsPlugin.dispose();
  65852. };
  65853. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  65854. return this._physicsPlugin.name;
  65855. };
  65856. /**
  65857. * Adding a new impostor for the impostor tracking.
  65858. * This will be done by the impostor itself.
  65859. * @param {PhysicsImpostor} impostor the impostor to add
  65860. */
  65861. PhysicsEngine.prototype.addImpostor = function (impostor) {
  65862. impostor.uniqueId = this._impostors.push(impostor);
  65863. //if no parent, generate the body
  65864. if (!impostor.parent) {
  65865. this._physicsPlugin.generatePhysicsBody(impostor);
  65866. }
  65867. };
  65868. /**
  65869. * Remove an impostor from the engine.
  65870. * This impostor and its mesh will not longer be updated by the physics engine.
  65871. * @param {PhysicsImpostor} impostor the impostor to remove
  65872. */
  65873. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  65874. var index = this._impostors.indexOf(impostor);
  65875. if (index > -1) {
  65876. var removed = this._impostors.splice(index, 1);
  65877. //Is it needed?
  65878. if (removed.length) {
  65879. //this will also remove it from the world.
  65880. removed[0].physicsBody = null;
  65881. }
  65882. }
  65883. };
  65884. /**
  65885. * Add a joint to the physics engine
  65886. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  65887. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  65888. * @param {PhysicsJoint} the joint that will connect both impostors.
  65889. */
  65890. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  65891. var impostorJoint = {
  65892. mainImpostor: mainImpostor,
  65893. connectedImpostor: connectedImpostor,
  65894. joint: joint
  65895. };
  65896. joint.physicsPlugin = this._physicsPlugin;
  65897. this._joints.push(impostorJoint);
  65898. this._physicsPlugin.generateJoint(impostorJoint);
  65899. };
  65900. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  65901. var matchingJoints = this._joints.filter(function (impostorJoint) {
  65902. return (impostorJoint.connectedImpostor === connectedImpostor
  65903. && impostorJoint.joint === joint
  65904. && impostorJoint.mainImpostor === mainImpostor);
  65905. });
  65906. if (matchingJoints.length) {
  65907. this._physicsPlugin.removeJoint(matchingJoints[0]);
  65908. //TODO remove it from the list as well
  65909. }
  65910. };
  65911. /**
  65912. * Called by the scene. no need to call it.
  65913. */
  65914. PhysicsEngine.prototype._step = function (delta) {
  65915. var _this = this;
  65916. //check if any mesh has no body / requires an update
  65917. this._impostors.forEach(function (impostor) {
  65918. if (impostor.isBodyInitRequired()) {
  65919. _this._physicsPlugin.generatePhysicsBody(impostor);
  65920. }
  65921. });
  65922. if (delta > 0.1) {
  65923. delta = 0.1;
  65924. }
  65925. else if (delta <= 0) {
  65926. delta = 1.0 / 60.0;
  65927. }
  65928. this._physicsPlugin.executeStep(delta, this._impostors);
  65929. };
  65930. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  65931. return this._physicsPlugin;
  65932. };
  65933. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  65934. for (var i = 0; i < this._impostors.length; ++i) {
  65935. if (this._impostors[i].object === object) {
  65936. return this._impostors[i];
  65937. }
  65938. }
  65939. return null;
  65940. };
  65941. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  65942. for (var i = 0; i < this._impostors.length; ++i) {
  65943. if (this._impostors[i].physicsBody === body) {
  65944. return this._impostors[i];
  65945. }
  65946. }
  65947. return null;
  65948. };
  65949. // Statics
  65950. PhysicsEngine.Epsilon = 0.001;
  65951. return PhysicsEngine;
  65952. }());
  65953. BABYLON.PhysicsEngine = PhysicsEngine;
  65954. })(BABYLON || (BABYLON = {}));
  65955. //# sourceMappingURL=babylon.physicsEngine.js.map
  65956. var BABYLON;
  65957. (function (BABYLON) {
  65958. var CannonJSPlugin = /** @class */ (function () {
  65959. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  65960. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  65961. if (iterations === void 0) { iterations = 10; }
  65962. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  65963. this.name = "CannonJSPlugin";
  65964. this._physicsMaterials = new Array();
  65965. this._fixedTimeStep = 1 / 60;
  65966. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  65967. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  65968. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  65969. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  65970. this._tmpPosition = BABYLON.Vector3.Zero();
  65971. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  65972. this._tmpUnityRotation = new BABYLON.Quaternion();
  65973. if (!this.isSupported()) {
  65974. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  65975. return;
  65976. }
  65977. this.world = new this.BJSCANNON.World();
  65978. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  65979. this.world.solver.iterations = iterations;
  65980. }
  65981. CannonJSPlugin.prototype.setGravity = function (gravity) {
  65982. this.world.gravity.copy(gravity);
  65983. };
  65984. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  65985. this._fixedTimeStep = timeStep;
  65986. };
  65987. CannonJSPlugin.prototype.getTimeStep = function () {
  65988. return this._fixedTimeStep;
  65989. };
  65990. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  65991. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  65992. };
  65993. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  65994. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65995. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65996. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  65997. };
  65998. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  65999. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66000. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66001. impostor.physicsBody.applyForce(impulse, worldPoint);
  66002. };
  66003. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66004. //parent-child relationship. Does this impostor has a parent impostor?
  66005. if (impostor.parent) {
  66006. if (impostor.physicsBody) {
  66007. this.removePhysicsBody(impostor);
  66008. //TODO is that needed?
  66009. impostor.forceUpdate();
  66010. }
  66011. return;
  66012. }
  66013. //should a new body be created for this impostor?
  66014. if (impostor.isBodyInitRequired()) {
  66015. var shape = this._createShape(impostor);
  66016. //unregister events, if body is being changed
  66017. var oldBody = impostor.physicsBody;
  66018. if (oldBody) {
  66019. this.removePhysicsBody(impostor);
  66020. }
  66021. //create the body and material
  66022. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  66023. var bodyCreationObject = {
  66024. mass: impostor.getParam("mass"),
  66025. material: material
  66026. };
  66027. // A simple extend, in case native options were used.
  66028. var nativeOptions = impostor.getParam("nativeOptions");
  66029. for (var key in nativeOptions) {
  66030. if (nativeOptions.hasOwnProperty(key)) {
  66031. bodyCreationObject[key] = nativeOptions[key];
  66032. }
  66033. }
  66034. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  66035. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  66036. this.world.addEventListener("preStep", impostor.beforeStep);
  66037. this.world.addEventListener("postStep", impostor.afterStep);
  66038. impostor.physicsBody.addShape(shape);
  66039. this.world.add(impostor.physicsBody);
  66040. //try to keep the body moving in the right direction by taking old properties.
  66041. //Should be tested!
  66042. if (oldBody) {
  66043. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  66044. impostor.physicsBody[param].copy(oldBody[param]);
  66045. });
  66046. }
  66047. this._processChildMeshes(impostor);
  66048. }
  66049. //now update the body's transformation
  66050. this._updatePhysicsBodyTransformation(impostor);
  66051. };
  66052. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  66053. var _this = this;
  66054. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  66055. var currentRotation = mainImpostor.object.rotationQuaternion;
  66056. if (meshChildren.length) {
  66057. var processMesh = function (localPosition, mesh) {
  66058. if (!currentRotation || !mesh.rotationQuaternion) {
  66059. return;
  66060. }
  66061. var childImpostor = mesh.getPhysicsImpostor();
  66062. if (childImpostor) {
  66063. var parent = childImpostor.parent;
  66064. if (parent !== mainImpostor) {
  66065. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  66066. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  66067. if (childImpostor.physicsBody) {
  66068. _this.removePhysicsBody(childImpostor);
  66069. childImpostor.physicsBody = null;
  66070. }
  66071. childImpostor.parent = mainImpostor;
  66072. childImpostor.resetUpdateFlags();
  66073. 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));
  66074. //Add the mass of the children.
  66075. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  66076. }
  66077. }
  66078. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  66079. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  66080. };
  66081. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  66082. }
  66083. };
  66084. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66085. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  66086. this.world.removeEventListener("preStep", impostor.beforeStep);
  66087. this.world.removeEventListener("postStep", impostor.afterStep);
  66088. this.world.remove(impostor.physicsBody);
  66089. };
  66090. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66091. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66092. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66093. if (!mainBody || !connectedBody) {
  66094. return;
  66095. }
  66096. var constraint;
  66097. var jointData = impostorJoint.joint.jointData;
  66098. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  66099. var constraintData = {
  66100. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  66101. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  66102. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  66103. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  66104. maxForce: jointData.nativeParams.maxForce,
  66105. collideConnected: !!jointData.collision
  66106. };
  66107. switch (impostorJoint.joint.type) {
  66108. case BABYLON.PhysicsJoint.HingeJoint:
  66109. case BABYLON.PhysicsJoint.Hinge2Joint:
  66110. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  66111. break;
  66112. case BABYLON.PhysicsJoint.DistanceJoint:
  66113. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  66114. break;
  66115. case BABYLON.PhysicsJoint.SpringJoint:
  66116. var springData = jointData;
  66117. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  66118. restLength: springData.length,
  66119. stiffness: springData.stiffness,
  66120. damping: springData.damping,
  66121. localAnchorA: constraintData.pivotA,
  66122. localAnchorB: constraintData.pivotB
  66123. });
  66124. break;
  66125. case BABYLON.PhysicsJoint.LockJoint:
  66126. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  66127. break;
  66128. case BABYLON.PhysicsJoint.PointToPointJoint:
  66129. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66130. default:
  66131. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  66132. break;
  66133. }
  66134. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  66135. constraint.collideConnected = !!jointData.collision;
  66136. impostorJoint.joint.physicsJoint = constraint;
  66137. //don't add spring as constraint, as it is not one.
  66138. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  66139. this.world.addConstraint(constraint);
  66140. }
  66141. else {
  66142. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  66143. constraint.applyForce();
  66144. });
  66145. }
  66146. };
  66147. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66148. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  66149. };
  66150. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  66151. var index;
  66152. var mat;
  66153. for (index = 0; index < this._physicsMaterials.length; index++) {
  66154. mat = this._physicsMaterials[index];
  66155. if (mat.friction === friction && mat.restitution === restitution) {
  66156. return mat;
  66157. }
  66158. }
  66159. var currentMat = new this.BJSCANNON.Material(name);
  66160. currentMat.friction = friction;
  66161. currentMat.restitution = restitution;
  66162. this._physicsMaterials.push(currentMat);
  66163. return currentMat;
  66164. };
  66165. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  66166. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  66167. };
  66168. CannonJSPlugin.prototype._createShape = function (impostor) {
  66169. var object = impostor.object;
  66170. var returnValue;
  66171. var extendSize = impostor.getObjectExtendSize();
  66172. switch (impostor.type) {
  66173. case BABYLON.PhysicsImpostor.SphereImpostor:
  66174. var radiusX = extendSize.x;
  66175. var radiusY = extendSize.y;
  66176. var radiusZ = extendSize.z;
  66177. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  66178. break;
  66179. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  66180. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66181. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  66182. break;
  66183. case BABYLON.PhysicsImpostor.BoxImpostor:
  66184. var box = extendSize.scale(0.5);
  66185. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  66186. break;
  66187. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66188. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  66189. returnValue = new this.BJSCANNON.Plane();
  66190. break;
  66191. case BABYLON.PhysicsImpostor.MeshImpostor:
  66192. // should transform the vertex data to world coordinates!!
  66193. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  66194. var rawFaces = object.getIndices ? object.getIndices() : [];
  66195. if (!rawVerts)
  66196. return;
  66197. // get only scale! so the object could transform correctly.
  66198. var oldPosition = object.position.clone();
  66199. var oldRotation = object.rotation && object.rotation.clone();
  66200. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  66201. object.position.copyFromFloats(0, 0, 0);
  66202. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66203. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66204. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66205. var transform = object.computeWorldMatrix(true);
  66206. // convert rawVerts to object space
  66207. var temp = new Array();
  66208. var index;
  66209. for (index = 0; index < rawVerts.length; index += 3) {
  66210. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  66211. }
  66212. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  66213. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  66214. //now set back the transformation!
  66215. object.position.copyFrom(oldPosition);
  66216. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  66217. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  66218. break;
  66219. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  66220. var oldPosition2 = object.position.clone();
  66221. var oldRotation2 = object.rotation && object.rotation.clone();
  66222. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  66223. object.position.copyFromFloats(0, 0, 0);
  66224. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66225. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66226. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66227. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  66228. returnValue = this._createHeightmap(object);
  66229. object.position.copyFrom(oldPosition2);
  66230. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  66231. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  66232. object.computeWorldMatrix(true);
  66233. break;
  66234. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66235. returnValue = new this.BJSCANNON.Particle();
  66236. break;
  66237. }
  66238. return returnValue;
  66239. };
  66240. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  66241. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66242. var transform = object.computeWorldMatrix(true);
  66243. // convert rawVerts to object space
  66244. var temp = new Array();
  66245. var index;
  66246. for (index = 0; index < pos.length; index += 3) {
  66247. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  66248. }
  66249. pos = temp;
  66250. var matrix = new Array();
  66251. //For now pointDepth will not be used and will be automatically calculated.
  66252. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  66253. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  66254. var boundingInfo = (object.getBoundingInfo());
  66255. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  66256. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  66257. var elementSize = dim * 2 / arraySize;
  66258. for (var i = 0; i < pos.length; i = i + 3) {
  66259. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  66260. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  66261. var y = -pos[i + 2] + minY;
  66262. if (!matrix[x]) {
  66263. matrix[x] = [];
  66264. }
  66265. if (!matrix[x][z]) {
  66266. matrix[x][z] = y;
  66267. }
  66268. matrix[x][z] = Math.max(y, matrix[x][z]);
  66269. }
  66270. for (var x = 0; x <= arraySize; ++x) {
  66271. if (!matrix[x]) {
  66272. var loc = 1;
  66273. while (!matrix[(x + loc) % arraySize]) {
  66274. loc++;
  66275. }
  66276. matrix[x] = matrix[(x + loc) % arraySize].slice();
  66277. //console.log("missing x", x);
  66278. }
  66279. for (var z = 0; z <= arraySize; ++z) {
  66280. if (!matrix[x][z]) {
  66281. var loc = 1;
  66282. var newValue;
  66283. while (newValue === undefined) {
  66284. newValue = matrix[x][(z + loc++) % arraySize];
  66285. }
  66286. matrix[x][z] = newValue;
  66287. }
  66288. }
  66289. }
  66290. var shape = new this.BJSCANNON.Heightfield(matrix, {
  66291. elementSize: elementSize
  66292. });
  66293. //For future reference, needed for body transformation
  66294. shape.minY = minY;
  66295. return shape;
  66296. };
  66297. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  66298. var object = impostor.object;
  66299. //make sure it is updated...
  66300. object.computeWorldMatrix && object.computeWorldMatrix(true);
  66301. // The delta between the mesh position and the mesh bounding box center
  66302. var bInfo = object.getBoundingInfo();
  66303. if (!bInfo)
  66304. return;
  66305. var center = impostor.getObjectCenter();
  66306. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  66307. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  66308. this._tmpPosition.copyFrom(center);
  66309. var quaternion = object.rotationQuaternion;
  66310. if (!quaternion) {
  66311. return;
  66312. }
  66313. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  66314. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  66315. //-90 DEG in X, precalculated
  66316. quaternion = quaternion.multiply(this._minus90X);
  66317. //Invert! (Precalculated, 90 deg in X)
  66318. //No need to clone. this will never change.
  66319. impostor.setDeltaRotation(this._plus90X);
  66320. }
  66321. //If it is a heightfield, if should be centered.
  66322. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  66323. var mesh = object;
  66324. var boundingInfo = mesh.getBoundingInfo();
  66325. //calculate the correct body position:
  66326. var rotationQuaternion = mesh.rotationQuaternion;
  66327. mesh.rotationQuaternion = this._tmpUnityRotation;
  66328. mesh.computeWorldMatrix(true);
  66329. //get original center with no rotation
  66330. var c = center.clone();
  66331. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66332. //rotation is back
  66333. mesh.rotationQuaternion = rotationQuaternion;
  66334. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66335. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66336. mesh.setPivotMatrix(p);
  66337. mesh.computeWorldMatrix(true);
  66338. //calculate the translation
  66339. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66340. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66341. //add it inverted to the delta
  66342. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66343. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66344. mesh.setPivotMatrix(oldPivot);
  66345. mesh.computeWorldMatrix(true);
  66346. }
  66347. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66348. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66349. //this._tmpPosition.copyFrom(object.position);
  66350. }
  66351. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66352. //Now update the impostor object
  66353. impostor.physicsBody.position.copy(this._tmpPosition);
  66354. impostor.physicsBody.quaternion.copy(quaternion);
  66355. };
  66356. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66357. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66358. if (impostor.object.rotationQuaternion) {
  66359. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66360. }
  66361. };
  66362. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66363. impostor.physicsBody.position.copy(newPosition);
  66364. impostor.physicsBody.quaternion.copy(newRotation);
  66365. };
  66366. CannonJSPlugin.prototype.isSupported = function () {
  66367. return this.BJSCANNON !== undefined;
  66368. };
  66369. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66370. impostor.physicsBody.velocity.copy(velocity);
  66371. };
  66372. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66373. impostor.physicsBody.angularVelocity.copy(velocity);
  66374. };
  66375. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66376. var v = impostor.physicsBody.velocity;
  66377. if (!v) {
  66378. return null;
  66379. }
  66380. return new BABYLON.Vector3(v.x, v.y, v.z);
  66381. };
  66382. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66383. var v = impostor.physicsBody.angularVelocity;
  66384. if (!v) {
  66385. return null;
  66386. }
  66387. return new BABYLON.Vector3(v.x, v.y, v.z);
  66388. };
  66389. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66390. impostor.physicsBody.mass = mass;
  66391. impostor.physicsBody.updateMassProperties();
  66392. };
  66393. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66394. return impostor.physicsBody.mass;
  66395. };
  66396. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66397. return impostor.physicsBody.material.friction;
  66398. };
  66399. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66400. impostor.physicsBody.material.friction = friction;
  66401. };
  66402. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66403. return impostor.physicsBody.material.restitution;
  66404. };
  66405. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66406. impostor.physicsBody.material.restitution = restitution;
  66407. };
  66408. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66409. impostor.physicsBody.sleep();
  66410. };
  66411. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66412. impostor.physicsBody.wakeUp();
  66413. };
  66414. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66415. joint.physicsJoint.distance = maxDistance;
  66416. };
  66417. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66418. // if (!motorIndex) {
  66419. // joint.physicsJoint.enableMotor();
  66420. // }
  66421. // }
  66422. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66423. // if (!motorIndex) {
  66424. // joint.physicsJoint.disableMotor();
  66425. // }
  66426. // }
  66427. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66428. if (!motorIndex) {
  66429. joint.physicsJoint.enableMotor();
  66430. joint.physicsJoint.setMotorSpeed(speed);
  66431. if (maxForce) {
  66432. this.setLimit(joint, maxForce);
  66433. }
  66434. }
  66435. };
  66436. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66437. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66438. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66439. };
  66440. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66441. var body = impostor.physicsBody;
  66442. mesh.position.x = body.position.x;
  66443. mesh.position.y = body.position.y;
  66444. mesh.position.z = body.position.z;
  66445. if (mesh.rotationQuaternion) {
  66446. mesh.rotationQuaternion.x = body.quaternion.x;
  66447. mesh.rotationQuaternion.y = body.quaternion.y;
  66448. mesh.rotationQuaternion.z = body.quaternion.z;
  66449. mesh.rotationQuaternion.w = body.quaternion.w;
  66450. }
  66451. };
  66452. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66453. var shape = impostor.physicsBody.shapes[0];
  66454. return shape.boundingSphereRadius;
  66455. };
  66456. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66457. var shape = impostor.physicsBody.shapes[0];
  66458. result.x = shape.halfExtents.x * 2;
  66459. result.y = shape.halfExtents.y * 2;
  66460. result.z = shape.halfExtents.z * 2;
  66461. };
  66462. CannonJSPlugin.prototype.dispose = function () {
  66463. };
  66464. return CannonJSPlugin;
  66465. }());
  66466. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66467. })(BABYLON || (BABYLON = {}));
  66468. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66469. var BABYLON;
  66470. (function (BABYLON) {
  66471. var OimoJSPlugin = /** @class */ (function () {
  66472. function OimoJSPlugin(iterations) {
  66473. this.name = "OimoJSPlugin";
  66474. this._tmpImpostorsArray = [];
  66475. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66476. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  66477. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66478. this.world.worldscale(1);
  66479. this.world.clear();
  66480. //making sure no stats are calculated
  66481. this.world.isNoStat = true;
  66482. }
  66483. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66484. this.world.gravity.copy(gravity);
  66485. };
  66486. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66487. this.world.timeStep = timeStep;
  66488. };
  66489. OimoJSPlugin.prototype.getTimeStep = function () {
  66490. return this.world.timeStep;
  66491. };
  66492. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66493. var _this = this;
  66494. impostors.forEach(function (impostor) {
  66495. impostor.beforeStep();
  66496. });
  66497. this.world.step();
  66498. impostors.forEach(function (impostor) {
  66499. impostor.afterStep();
  66500. //update the ordered impostors array
  66501. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66502. });
  66503. //check for collisions
  66504. var contact = this.world.contacts;
  66505. while (contact !== null) {
  66506. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66507. contact = contact.next;
  66508. continue;
  66509. }
  66510. //is this body colliding with any other? get the impostor
  66511. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66512. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66513. if (!mainImpostor || !collidingImpostor) {
  66514. contact = contact.next;
  66515. continue;
  66516. }
  66517. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66518. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66519. contact = contact.next;
  66520. }
  66521. };
  66522. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66523. var mass = impostor.physicsBody.massInfo.mass;
  66524. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66525. };
  66526. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66527. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66528. this.applyImpulse(impostor, force, contactPoint);
  66529. };
  66530. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66531. var _this = this;
  66532. //parent-child relationship. Does this impostor has a parent impostor?
  66533. if (impostor.parent) {
  66534. if (impostor.physicsBody) {
  66535. this.removePhysicsBody(impostor);
  66536. //TODO is that needed?
  66537. impostor.forceUpdate();
  66538. }
  66539. return;
  66540. }
  66541. if (impostor.isBodyInitRequired()) {
  66542. var bodyConfig = {
  66543. name: impostor.uniqueId,
  66544. //Oimo must have mass, also for static objects.
  66545. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66546. size: [],
  66547. type: [],
  66548. pos: [],
  66549. rot: [],
  66550. move: impostor.getParam("mass") !== 0,
  66551. //Supporting older versions of Oimo
  66552. world: this.world
  66553. };
  66554. var impostors = [impostor];
  66555. var addToArray = function (parent) {
  66556. if (!parent.getChildMeshes)
  66557. return;
  66558. parent.getChildMeshes().forEach(function (m) {
  66559. if (m.physicsImpostor) {
  66560. impostors.push(m.physicsImpostor);
  66561. //m.physicsImpostor._init();
  66562. }
  66563. });
  66564. };
  66565. addToArray(impostor.object);
  66566. var checkWithEpsilon_1 = function (value) {
  66567. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66568. };
  66569. impostors.forEach(function (i) {
  66570. if (!impostor.object.rotationQuaternion) {
  66571. return;
  66572. }
  66573. //get the correct bounding box
  66574. var oldQuaternion = i.object.rotationQuaternion;
  66575. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66576. x: impostor.object.rotationQuaternion.x,
  66577. y: impostor.object.rotationQuaternion.y,
  66578. z: impostor.object.rotationQuaternion.z,
  66579. s: impostor.object.rotationQuaternion.w
  66580. });
  66581. var extendSize = i.getObjectExtendSize();
  66582. if (i === impostor) {
  66583. var center = impostor.getObjectCenter();
  66584. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66585. //Can also use Array.prototype.push.apply
  66586. bodyConfig.pos.push(center.x);
  66587. bodyConfig.pos.push(center.y);
  66588. bodyConfig.pos.push(center.z);
  66589. //tmp solution
  66590. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66591. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66592. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66593. }
  66594. else {
  66595. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66596. bodyConfig.pos.push(localPosition.x);
  66597. bodyConfig.pos.push(localPosition.y);
  66598. bodyConfig.pos.push(localPosition.z);
  66599. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66600. bodyConfig.rot.push(0);
  66601. bodyConfig.rot.push(0);
  66602. bodyConfig.rot.push(0);
  66603. }
  66604. // register mesh
  66605. switch (i.type) {
  66606. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66607. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66608. case BABYLON.PhysicsImpostor.SphereImpostor:
  66609. var radiusX = extendSize.x;
  66610. var radiusY = extendSize.y;
  66611. var radiusZ = extendSize.z;
  66612. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66613. bodyConfig.type.push('sphere');
  66614. //due to the way oimo works with compounds, add 3 times
  66615. bodyConfig.size.push(size);
  66616. bodyConfig.size.push(size);
  66617. bodyConfig.size.push(size);
  66618. break;
  66619. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66620. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66621. var sizeY = checkWithEpsilon_1(extendSize.y);
  66622. bodyConfig.type.push('cylinder');
  66623. bodyConfig.size.push(sizeX);
  66624. bodyConfig.size.push(sizeY);
  66625. //due to the way oimo works with compounds, add one more value.
  66626. bodyConfig.size.push(sizeY);
  66627. break;
  66628. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66629. case BABYLON.PhysicsImpostor.BoxImpostor:
  66630. default:
  66631. var sizeX = checkWithEpsilon_1(extendSize.x);
  66632. var sizeY = checkWithEpsilon_1(extendSize.y);
  66633. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66634. bodyConfig.type.push('box');
  66635. bodyConfig.size.push(sizeX);
  66636. bodyConfig.size.push(sizeY);
  66637. bodyConfig.size.push(sizeZ);
  66638. break;
  66639. }
  66640. //actually not needed, but hey...
  66641. i.object.rotationQuaternion = oldQuaternion;
  66642. });
  66643. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66644. }
  66645. else {
  66646. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66647. }
  66648. impostor.setDeltaPosition(this._tmpPositionVector);
  66649. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66650. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66651. };
  66652. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66653. //impostor.physicsBody.dispose();
  66654. //Same as : (older oimo versions)
  66655. this.world.removeRigidBody(impostor.physicsBody);
  66656. };
  66657. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66658. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66659. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66660. if (!mainBody || !connectedBody) {
  66661. return;
  66662. }
  66663. var jointData = impostorJoint.joint.jointData;
  66664. var options = jointData.nativeParams || {};
  66665. var type;
  66666. var nativeJointData = {
  66667. body1: mainBody,
  66668. body2: connectedBody,
  66669. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66670. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66671. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66672. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66673. min: options.min,
  66674. max: options.max,
  66675. collision: options.collision || jointData.collision,
  66676. spring: options.spring,
  66677. //supporting older version of Oimo
  66678. world: this.world
  66679. };
  66680. switch (impostorJoint.joint.type) {
  66681. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66682. type = "jointBall";
  66683. break;
  66684. case BABYLON.PhysicsJoint.SpringJoint:
  66685. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66686. var springData = jointData;
  66687. nativeJointData.min = springData.length || nativeJointData.min;
  66688. //Max should also be set, just make sure it is at least min
  66689. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66690. case BABYLON.PhysicsJoint.DistanceJoint:
  66691. type = "jointDistance";
  66692. nativeJointData.max = jointData.maxDistance;
  66693. break;
  66694. case BABYLON.PhysicsJoint.PrismaticJoint:
  66695. type = "jointPrisme";
  66696. break;
  66697. case BABYLON.PhysicsJoint.SliderJoint:
  66698. type = "jointSlide";
  66699. break;
  66700. case BABYLON.PhysicsJoint.WheelJoint:
  66701. type = "jointWheel";
  66702. break;
  66703. case BABYLON.PhysicsJoint.HingeJoint:
  66704. default:
  66705. type = "jointHinge";
  66706. break;
  66707. }
  66708. nativeJointData.type = type;
  66709. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66710. };
  66711. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66712. //Bug in Oimo prevents us from disposing a joint in the playground
  66713. //joint.joint.physicsJoint.dispose();
  66714. //So we will bruteforce it!
  66715. try {
  66716. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66717. }
  66718. catch (e) {
  66719. BABYLON.Tools.Warn(e);
  66720. }
  66721. };
  66722. OimoJSPlugin.prototype.isSupported = function () {
  66723. return this.BJSOIMO !== undefined;
  66724. };
  66725. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66726. if (!impostor.physicsBody.sleeping) {
  66727. //TODO check that
  66728. if (impostor.physicsBody.shapes.next) {
  66729. var parentShape = this._getLastShape(impostor.physicsBody);
  66730. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66731. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66732. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66733. }
  66734. else {
  66735. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66736. }
  66737. if (impostor.object.rotationQuaternion) {
  66738. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66739. impostor.object.rotationQuaternion.normalize();
  66740. }
  66741. }
  66742. };
  66743. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66744. var body = impostor.physicsBody;
  66745. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66746. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66747. body.syncShapes();
  66748. body.awake();
  66749. };
  66750. OimoJSPlugin.prototype._getLastShape = function (body) {
  66751. var lastShape = body.shapes;
  66752. while (lastShape.next) {
  66753. lastShape = lastShape.next;
  66754. }
  66755. return lastShape;
  66756. };
  66757. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66758. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66759. };
  66760. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66761. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66762. };
  66763. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66764. var v = impostor.physicsBody.linearVelocity;
  66765. if (!v) {
  66766. return null;
  66767. }
  66768. return new BABYLON.Vector3(v.x, v.y, v.z);
  66769. };
  66770. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66771. var v = impostor.physicsBody.angularVelocity;
  66772. if (!v) {
  66773. return null;
  66774. }
  66775. return new BABYLON.Vector3(v.x, v.y, v.z);
  66776. };
  66777. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66778. var staticBody = mass === 0;
  66779. //this will actually set the body's density and not its mass.
  66780. //But this is how oimo treats the mass variable.
  66781. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66782. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66783. };
  66784. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66785. return impostor.physicsBody.shapes.density;
  66786. };
  66787. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66788. return impostor.physicsBody.shapes.friction;
  66789. };
  66790. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66791. impostor.physicsBody.shapes.friction = friction;
  66792. };
  66793. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66794. return impostor.physicsBody.shapes.restitution;
  66795. };
  66796. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66797. impostor.physicsBody.shapes.restitution = restitution;
  66798. };
  66799. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66800. impostor.physicsBody.sleep();
  66801. };
  66802. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66803. impostor.physicsBody.awake();
  66804. };
  66805. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66806. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66807. if (minDistance !== void 0) {
  66808. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66809. }
  66810. };
  66811. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66812. //TODO separate rotational and transational motors.
  66813. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66814. if (motor) {
  66815. motor.setMotor(speed, maxForce);
  66816. }
  66817. };
  66818. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66819. //TODO separate rotational and transational motors.
  66820. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66821. if (motor) {
  66822. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66823. }
  66824. };
  66825. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66826. var body = impostor.physicsBody;
  66827. mesh.position.x = body.position.x;
  66828. mesh.position.y = body.position.y;
  66829. mesh.position.z = body.position.z;
  66830. if (mesh.rotationQuaternion) {
  66831. mesh.rotationQuaternion.x = body.orientation.x;
  66832. mesh.rotationQuaternion.y = body.orientation.y;
  66833. mesh.rotationQuaternion.z = body.orientation.z;
  66834. mesh.rotationQuaternion.w = body.orientation.s;
  66835. }
  66836. };
  66837. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66838. return impostor.physicsBody.shapes.radius;
  66839. };
  66840. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66841. var shape = impostor.physicsBody.shapes;
  66842. result.x = shape.halfWidth * 2;
  66843. result.y = shape.halfHeight * 2;
  66844. result.z = shape.halfDepth * 2;
  66845. };
  66846. OimoJSPlugin.prototype.dispose = function () {
  66847. this.world.clear();
  66848. };
  66849. return OimoJSPlugin;
  66850. }());
  66851. BABYLON.OimoJSPlugin = OimoJSPlugin;
  66852. })(BABYLON || (BABYLON = {}));
  66853. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  66854. var BABYLON;
  66855. (function (BABYLON) {
  66856. var Internals;
  66857. (function (Internals) {
  66858. /*
  66859. * Based on jsTGALoader - Javascript loader for TGA file
  66860. * By Vincent Thibault
  66861. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  66862. */
  66863. var TGATools = /** @class */ (function () {
  66864. function TGATools() {
  66865. }
  66866. TGATools.GetTGAHeader = function (data) {
  66867. var offset = 0;
  66868. var header = {
  66869. id_length: data[offset++],
  66870. colormap_type: data[offset++],
  66871. image_type: data[offset++],
  66872. colormap_index: data[offset++] | data[offset++] << 8,
  66873. colormap_length: data[offset++] | data[offset++] << 8,
  66874. colormap_size: data[offset++],
  66875. origin: [
  66876. data[offset++] | data[offset++] << 8,
  66877. data[offset++] | data[offset++] << 8
  66878. ],
  66879. width: data[offset++] | data[offset++] << 8,
  66880. height: data[offset++] | data[offset++] << 8,
  66881. pixel_size: data[offset++],
  66882. flags: data[offset++]
  66883. };
  66884. return header;
  66885. };
  66886. TGATools.UploadContent = function (gl, data) {
  66887. // Not enough data to contain header ?
  66888. if (data.length < 19) {
  66889. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  66890. return;
  66891. }
  66892. // Read Header
  66893. var offset = 18;
  66894. var header = TGATools.GetTGAHeader(data);
  66895. // Assume it's a valid Targa file.
  66896. if (header.id_length + offset > data.length) {
  66897. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  66898. return;
  66899. }
  66900. // Skip not needed data
  66901. offset += header.id_length;
  66902. var use_rle = false;
  66903. var use_pal = false;
  66904. var use_rgb = false;
  66905. var use_grey = false;
  66906. // Get some informations.
  66907. switch (header.image_type) {
  66908. case TGATools._TYPE_RLE_INDEXED:
  66909. use_rle = true;
  66910. case TGATools._TYPE_INDEXED:
  66911. use_pal = true;
  66912. break;
  66913. case TGATools._TYPE_RLE_RGB:
  66914. use_rle = true;
  66915. case TGATools._TYPE_RGB:
  66916. use_rgb = true;
  66917. break;
  66918. case TGATools._TYPE_RLE_GREY:
  66919. use_rle = true;
  66920. case TGATools._TYPE_GREY:
  66921. use_grey = true;
  66922. break;
  66923. }
  66924. var pixel_data;
  66925. // var numAlphaBits = header.flags & 0xf;
  66926. var pixel_size = header.pixel_size >> 3;
  66927. var pixel_total = header.width * header.height * pixel_size;
  66928. // Read palettes
  66929. var palettes;
  66930. if (use_pal) {
  66931. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  66932. }
  66933. // Read LRE
  66934. if (use_rle) {
  66935. pixel_data = new Uint8Array(pixel_total);
  66936. var c, count, i;
  66937. var localOffset = 0;
  66938. var pixels = new Uint8Array(pixel_size);
  66939. while (offset < pixel_total && localOffset < pixel_total) {
  66940. c = data[offset++];
  66941. count = (c & 0x7f) + 1;
  66942. // RLE pixels
  66943. if (c & 0x80) {
  66944. // Bind pixel tmp array
  66945. for (i = 0; i < pixel_size; ++i) {
  66946. pixels[i] = data[offset++];
  66947. }
  66948. // Copy pixel array
  66949. for (i = 0; i < count; ++i) {
  66950. pixel_data.set(pixels, localOffset + i * pixel_size);
  66951. }
  66952. localOffset += pixel_size * count;
  66953. }
  66954. else {
  66955. count *= pixel_size;
  66956. for (i = 0; i < count; ++i) {
  66957. pixel_data[localOffset + i] = data[offset++];
  66958. }
  66959. localOffset += count;
  66960. }
  66961. }
  66962. }
  66963. else {
  66964. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  66965. }
  66966. // Load to texture
  66967. var x_start, y_start, x_step, y_step, y_end, x_end;
  66968. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  66969. default:
  66970. case TGATools._ORIGIN_UL:
  66971. x_start = 0;
  66972. x_step = 1;
  66973. x_end = header.width;
  66974. y_start = 0;
  66975. y_step = 1;
  66976. y_end = header.height;
  66977. break;
  66978. case TGATools._ORIGIN_BL:
  66979. x_start = 0;
  66980. x_step = 1;
  66981. x_end = header.width;
  66982. y_start = header.height - 1;
  66983. y_step = -1;
  66984. y_end = -1;
  66985. break;
  66986. case TGATools._ORIGIN_UR:
  66987. x_start = header.width - 1;
  66988. x_step = -1;
  66989. x_end = -1;
  66990. y_start = 0;
  66991. y_step = 1;
  66992. y_end = header.height;
  66993. break;
  66994. case TGATools._ORIGIN_BR:
  66995. x_start = header.width - 1;
  66996. x_step = -1;
  66997. x_end = -1;
  66998. y_start = header.height - 1;
  66999. y_step = -1;
  67000. y_end = -1;
  67001. break;
  67002. }
  67003. // Load the specify method
  67004. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  67005. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  67006. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  67007. };
  67008. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67009. var image = pixel_data, colormap = palettes;
  67010. var width = header.width, height = header.height;
  67011. var color, i = 0, x, y;
  67012. var imageData = new Uint8Array(width * height * 4);
  67013. for (y = y_start; y !== y_end; y += y_step) {
  67014. for (x = x_start; x !== x_end; x += x_step, i++) {
  67015. color = image[i];
  67016. imageData[(x + width * y) * 4 + 3] = 255;
  67017. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  67018. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  67019. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  67020. }
  67021. }
  67022. return imageData;
  67023. };
  67024. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67025. var image = pixel_data;
  67026. var width = header.width, height = header.height;
  67027. var color, i = 0, x, y;
  67028. var imageData = new Uint8Array(width * height * 4);
  67029. for (y = y_start; y !== y_end; y += y_step) {
  67030. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67031. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  67032. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  67033. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  67034. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  67035. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  67036. }
  67037. }
  67038. return imageData;
  67039. };
  67040. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67041. var image = pixel_data;
  67042. var width = header.width, height = header.height;
  67043. var i = 0, x, y;
  67044. var imageData = new Uint8Array(width * height * 4);
  67045. for (y = y_start; y !== y_end; y += y_step) {
  67046. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  67047. imageData[(x + width * y) * 4 + 3] = 255;
  67048. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67049. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67050. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67051. }
  67052. }
  67053. return imageData;
  67054. };
  67055. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67056. var image = pixel_data;
  67057. var width = header.width, height = header.height;
  67058. var i = 0, x, y;
  67059. var imageData = new Uint8Array(width * height * 4);
  67060. for (y = y_start; y !== y_end; y += y_step) {
  67061. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  67062. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67063. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67064. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67065. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  67066. }
  67067. }
  67068. return imageData;
  67069. };
  67070. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67071. var image = pixel_data;
  67072. var width = header.width, height = header.height;
  67073. var color, i = 0, x, y;
  67074. var imageData = new Uint8Array(width * height * 4);
  67075. for (y = y_start; y !== y_end; y += y_step) {
  67076. for (x = x_start; x !== x_end; x += x_step, i++) {
  67077. color = image[i];
  67078. imageData[(x + width * y) * 4 + 0] = color;
  67079. imageData[(x + width * y) * 4 + 1] = color;
  67080. imageData[(x + width * y) * 4 + 2] = color;
  67081. imageData[(x + width * y) * 4 + 3] = 255;
  67082. }
  67083. }
  67084. return imageData;
  67085. };
  67086. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67087. var image = pixel_data;
  67088. var width = header.width, height = header.height;
  67089. var i = 0, x, y;
  67090. var imageData = new Uint8Array(width * height * 4);
  67091. for (y = y_start; y !== y_end; y += y_step) {
  67092. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67093. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  67094. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  67095. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67096. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  67097. }
  67098. }
  67099. return imageData;
  67100. };
  67101. //private static _TYPE_NO_DATA = 0;
  67102. TGATools._TYPE_INDEXED = 1;
  67103. TGATools._TYPE_RGB = 2;
  67104. TGATools._TYPE_GREY = 3;
  67105. TGATools._TYPE_RLE_INDEXED = 9;
  67106. TGATools._TYPE_RLE_RGB = 10;
  67107. TGATools._TYPE_RLE_GREY = 11;
  67108. TGATools._ORIGIN_MASK = 0x30;
  67109. TGATools._ORIGIN_SHIFT = 0x04;
  67110. TGATools._ORIGIN_BL = 0x00;
  67111. TGATools._ORIGIN_BR = 0x01;
  67112. TGATools._ORIGIN_UL = 0x02;
  67113. TGATools._ORIGIN_UR = 0x03;
  67114. return TGATools;
  67115. }());
  67116. Internals.TGATools = TGATools;
  67117. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67118. })(BABYLON || (BABYLON = {}));
  67119. //# sourceMappingURL=babylon.tga.js.map
  67120. var BABYLON;
  67121. (function (BABYLON) {
  67122. var Internals;
  67123. (function (Internals) {
  67124. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  67125. // All values and structures referenced from:
  67126. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  67127. var DDS_MAGIC = 0x20534444;
  67128. var
  67129. //DDSD_CAPS = 0x1,
  67130. //DDSD_HEIGHT = 0x2,
  67131. //DDSD_WIDTH = 0x4,
  67132. //DDSD_PITCH = 0x8,
  67133. //DDSD_PIXELFORMAT = 0x1000,
  67134. DDSD_MIPMAPCOUNT = 0x20000;
  67135. //DDSD_LINEARSIZE = 0x80000,
  67136. //DDSD_DEPTH = 0x800000;
  67137. // var DDSCAPS_COMPLEX = 0x8,
  67138. // DDSCAPS_MIPMAP = 0x400000,
  67139. // DDSCAPS_TEXTURE = 0x1000;
  67140. var DDSCAPS2_CUBEMAP = 0x200;
  67141. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  67142. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  67143. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  67144. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  67145. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  67146. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  67147. // DDSCAPS2_VOLUME = 0x200000;
  67148. var
  67149. //DDPF_ALPHAPIXELS = 0x1,
  67150. //DDPF_ALPHA = 0x2,
  67151. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  67152. //DDPF_YUV = 0x200,
  67153. DDPF_LUMINANCE = 0x20000;
  67154. function FourCCToInt32(value) {
  67155. return value.charCodeAt(0) +
  67156. (value.charCodeAt(1) << 8) +
  67157. (value.charCodeAt(2) << 16) +
  67158. (value.charCodeAt(3) << 24);
  67159. }
  67160. function Int32ToFourCC(value) {
  67161. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  67162. }
  67163. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  67164. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  67165. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  67166. var FOURCC_DX10 = FourCCToInt32("DX10");
  67167. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  67168. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  67169. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  67170. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  67171. var headerLengthInt = 31; // The header length in 32 bit ints
  67172. // Offsets into the header array
  67173. var off_magic = 0;
  67174. var off_size = 1;
  67175. var off_flags = 2;
  67176. var off_height = 3;
  67177. var off_width = 4;
  67178. var off_mipmapCount = 7;
  67179. var off_pfFlags = 20;
  67180. var off_pfFourCC = 21;
  67181. var off_RGBbpp = 22;
  67182. // var off_RMask = 23;
  67183. // var off_GMask = 24;
  67184. // var off_BMask = 25;
  67185. // var off_AMask = 26;
  67186. // var off_caps1 = 27;
  67187. var off_caps2 = 28;
  67188. // var off_caps3 = 29;
  67189. // var off_caps4 = 30;
  67190. var off_dxgiFormat = 32;
  67191. ;
  67192. var DDSTools = /** @class */ (function () {
  67193. function DDSTools() {
  67194. }
  67195. DDSTools.GetDDSInfo = function (arrayBuffer) {
  67196. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  67197. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  67198. var mipmapCount = 1;
  67199. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  67200. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67201. }
  67202. var fourCC = header[off_pfFourCC];
  67203. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  67204. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67205. switch (fourCC) {
  67206. case FOURCC_D3DFMT_R16G16B16A16F:
  67207. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67208. break;
  67209. case FOURCC_D3DFMT_R32G32B32A32F:
  67210. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67211. break;
  67212. case FOURCC_DX10:
  67213. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  67214. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67215. break;
  67216. }
  67217. }
  67218. return {
  67219. width: header[off_width],
  67220. height: header[off_height],
  67221. mipmapCount: mipmapCount,
  67222. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  67223. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  67224. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  67225. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  67226. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  67227. dxgiFormat: dxgiFormat,
  67228. textureType: textureType
  67229. };
  67230. };
  67231. DDSTools._ToHalfFloat = function (value) {
  67232. if (!DDSTools._FloatView) {
  67233. DDSTools._FloatView = new Float32Array(1);
  67234. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  67235. }
  67236. DDSTools._FloatView[0] = value;
  67237. var x = DDSTools._Int32View[0];
  67238. var bits = (x >> 16) & 0x8000; /* Get the sign */
  67239. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  67240. var e = (x >> 23) & 0xff; /* Using int is faster here */
  67241. /* If zero, or denormal, or exponent underflows too much for a denormal
  67242. * half, return signed zero. */
  67243. if (e < 103) {
  67244. return bits;
  67245. }
  67246. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  67247. if (e > 142) {
  67248. bits |= 0x7c00;
  67249. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  67250. * not Inf, so make sure we set one mantissa bit too. */
  67251. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  67252. return bits;
  67253. }
  67254. /* If exponent underflows but not too much, return a denormal */
  67255. if (e < 113) {
  67256. m |= 0x0800;
  67257. /* Extra rounding may overflow and set mantissa to 0 and exponent
  67258. * to 1, which is OK. */
  67259. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  67260. return bits;
  67261. }
  67262. bits |= ((e - 112) << 10) | (m >> 1);
  67263. bits += m & 1;
  67264. return bits;
  67265. };
  67266. DDSTools._FromHalfFloat = function (value) {
  67267. var s = (value & 0x8000) >> 15;
  67268. var e = (value & 0x7C00) >> 10;
  67269. var f = value & 0x03FF;
  67270. if (e === 0) {
  67271. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  67272. }
  67273. else if (e == 0x1F) {
  67274. return f ? NaN : ((s ? -1 : 1) * Infinity);
  67275. }
  67276. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  67277. };
  67278. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67279. var destArray = new Float32Array(dataLength);
  67280. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67281. var index = 0;
  67282. for (var y = 0; y < height; y++) {
  67283. for (var x = 0; x < width; x++) {
  67284. var srcPos = (x + y * width) * 4;
  67285. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  67286. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  67287. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  67288. if (DDSTools.StoreLODInAlphaChannel) {
  67289. destArray[index + 3] = lod;
  67290. }
  67291. else {
  67292. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  67293. }
  67294. index += 4;
  67295. }
  67296. }
  67297. return destArray;
  67298. };
  67299. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67300. if (DDSTools.StoreLODInAlphaChannel) {
  67301. var destArray = new Uint16Array(dataLength);
  67302. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67303. var index = 0;
  67304. for (var y = 0; y < height; y++) {
  67305. for (var x = 0; x < width; x++) {
  67306. var srcPos = (x + y * width) * 4;
  67307. destArray[index] = srcData[srcPos];
  67308. destArray[index + 1] = srcData[srcPos + 1];
  67309. destArray[index + 2] = srcData[srcPos + 2];
  67310. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  67311. index += 4;
  67312. }
  67313. }
  67314. return destArray;
  67315. }
  67316. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  67317. };
  67318. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67319. if (DDSTools.StoreLODInAlphaChannel) {
  67320. var destArray = new Float32Array(dataLength);
  67321. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67322. var index = 0;
  67323. for (var y = 0; y < height; y++) {
  67324. for (var x = 0; x < width; x++) {
  67325. var srcPos = (x + y * width) * 4;
  67326. destArray[index] = srcData[srcPos];
  67327. destArray[index + 1] = srcData[srcPos + 1];
  67328. destArray[index + 2] = srcData[srcPos + 2];
  67329. destArray[index + 3] = lod;
  67330. index += 4;
  67331. }
  67332. }
  67333. return destArray;
  67334. }
  67335. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67336. };
  67337. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67338. var destArray = new Uint8Array(dataLength);
  67339. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67340. var index = 0;
  67341. for (var y = 0; y < height; y++) {
  67342. for (var x = 0; x < width; x++) {
  67343. var srcPos = (x + y * width) * 4;
  67344. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67345. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67346. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67347. if (DDSTools.StoreLODInAlphaChannel) {
  67348. destArray[index + 3] = lod;
  67349. }
  67350. else {
  67351. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67352. }
  67353. index += 4;
  67354. }
  67355. }
  67356. return destArray;
  67357. };
  67358. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67359. var destArray = new Uint8Array(dataLength);
  67360. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67361. var index = 0;
  67362. for (var y = 0; y < height; y++) {
  67363. for (var x = 0; x < width; x++) {
  67364. var srcPos = (x + y * width) * 4;
  67365. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67366. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67367. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67368. if (DDSTools.StoreLODInAlphaChannel) {
  67369. destArray[index + 3] = lod;
  67370. }
  67371. else {
  67372. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67373. }
  67374. index += 4;
  67375. }
  67376. }
  67377. return destArray;
  67378. };
  67379. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67380. var byteArray = new Uint8Array(dataLength);
  67381. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67382. var index = 0;
  67383. for (var y = 0; y < height; y++) {
  67384. for (var x = 0; x < width; x++) {
  67385. var srcPos = (x + y * width) * 4;
  67386. byteArray[index] = srcData[srcPos + 2];
  67387. byteArray[index + 1] = srcData[srcPos + 1];
  67388. byteArray[index + 2] = srcData[srcPos];
  67389. byteArray[index + 3] = srcData[srcPos + 3];
  67390. index += 4;
  67391. }
  67392. }
  67393. return byteArray;
  67394. };
  67395. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67396. var byteArray = new Uint8Array(dataLength);
  67397. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67398. var index = 0;
  67399. for (var y = 0; y < height; y++) {
  67400. for (var x = 0; x < width; x++) {
  67401. var srcPos = (x + y * width) * 3;
  67402. byteArray[index] = srcData[srcPos + 2];
  67403. byteArray[index + 1] = srcData[srcPos + 1];
  67404. byteArray[index + 2] = srcData[srcPos];
  67405. index += 3;
  67406. }
  67407. }
  67408. return byteArray;
  67409. };
  67410. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67411. var byteArray = new Uint8Array(dataLength);
  67412. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67413. var index = 0;
  67414. for (var y = 0; y < height; y++) {
  67415. for (var x = 0; x < width; x++) {
  67416. var srcPos = (x + y * width);
  67417. byteArray[index] = srcData[srcPos];
  67418. index++;
  67419. }
  67420. }
  67421. return byteArray;
  67422. };
  67423. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67424. if (lodIndex === void 0) { lodIndex = -1; }
  67425. var ext = engine.getCaps().s3tc;
  67426. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67427. var internalFormat = 0;
  67428. var format = 0;
  67429. var blockBytes = 1;
  67430. if (header[off_magic] != DDS_MAGIC) {
  67431. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67432. return;
  67433. }
  67434. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67435. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67436. return;
  67437. }
  67438. if (info.isCompressed && !ext) {
  67439. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67440. return;
  67441. }
  67442. var bpp = header[off_RGBbpp];
  67443. dataOffset = header[off_size] + 4;
  67444. var computeFormats = false;
  67445. if (info.isFourCC) {
  67446. fourCC = header[off_pfFourCC];
  67447. switch (fourCC) {
  67448. case FOURCC_DXT1:
  67449. blockBytes = 8;
  67450. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67451. break;
  67452. case FOURCC_DXT3:
  67453. blockBytes = 16;
  67454. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67455. break;
  67456. case FOURCC_DXT5:
  67457. blockBytes = 16;
  67458. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67459. break;
  67460. case FOURCC_D3DFMT_R16G16B16A16F:
  67461. computeFormats = true;
  67462. break;
  67463. case FOURCC_D3DFMT_R32G32B32A32F:
  67464. computeFormats = true;
  67465. break;
  67466. case FOURCC_DX10:
  67467. // There is an additionnal header so dataOffset need to be changed
  67468. dataOffset += 5 * 4; // 5 uints
  67469. var supported = false;
  67470. switch (info.dxgiFormat) {
  67471. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67472. computeFormats = true;
  67473. supported = true;
  67474. break;
  67475. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67476. info.isRGB = true;
  67477. info.isFourCC = false;
  67478. bpp = 32;
  67479. supported = true;
  67480. break;
  67481. }
  67482. if (supported) {
  67483. break;
  67484. }
  67485. default:
  67486. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67487. return;
  67488. }
  67489. }
  67490. if (computeFormats) {
  67491. format = engine._getWebGLTextureType(info.textureType);
  67492. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67493. }
  67494. mipmapCount = 1;
  67495. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67496. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67497. }
  67498. for (var face = 0; face < faces; face++) {
  67499. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67500. width = header[off_width];
  67501. height = header[off_height];
  67502. for (mip = 0; mip < mipmapCount; ++mip) {
  67503. if (lodIndex === -1 || lodIndex === mip) {
  67504. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67505. var i = (lodIndex === -1) ? mip : 0;
  67506. if (!info.isCompressed && info.isFourCC) {
  67507. dataLength = width * height * 4;
  67508. var FloatArray = null;
  67509. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67510. if (bpp === 128) {
  67511. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67512. }
  67513. else if (bpp === 64) {
  67514. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67515. }
  67516. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67517. format = engine._getWebGLTextureType(info.textureType);
  67518. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67519. }
  67520. else {
  67521. if (bpp === 128) {
  67522. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67523. }
  67524. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67525. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67526. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67527. format = engine._getWebGLTextureType(info.textureType);
  67528. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67529. }
  67530. else {
  67531. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67532. }
  67533. }
  67534. if (FloatArray) {
  67535. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67536. }
  67537. }
  67538. else if (info.isRGB) {
  67539. if (bpp === 24) {
  67540. dataLength = width * height * 3;
  67541. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67542. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67543. }
  67544. else {
  67545. dataLength = width * height * 4;
  67546. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67547. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67548. }
  67549. }
  67550. else if (info.isLuminance) {
  67551. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67552. var unpaddedRowSize = width;
  67553. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67554. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67555. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67556. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67557. }
  67558. else {
  67559. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67560. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67561. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67562. }
  67563. }
  67564. dataOffset += width * height * (bpp / 8);
  67565. width *= 0.5;
  67566. height *= 0.5;
  67567. width = Math.max(1.0, width);
  67568. height = Math.max(1.0, height);
  67569. }
  67570. }
  67571. };
  67572. DDSTools.StoreLODInAlphaChannel = false;
  67573. return DDSTools;
  67574. }());
  67575. Internals.DDSTools = DDSTools;
  67576. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67577. })(BABYLON || (BABYLON = {}));
  67578. //# sourceMappingURL=babylon.dds.js.map
  67579. var BABYLON;
  67580. (function (BABYLON) {
  67581. var Internals;
  67582. (function (Internals) {
  67583. /**
  67584. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67585. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67586. */
  67587. var KhronosTextureContainer = /** @class */ (function () {
  67588. /**
  67589. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67590. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67591. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67592. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67593. */
  67594. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67595. this.arrayBuffer = arrayBuffer;
  67596. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67597. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67598. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67599. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67600. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67601. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67602. BABYLON.Tools.Error("texture missing KTX identifier");
  67603. return;
  67604. }
  67605. // load the reset of the header in native 32 bit int
  67606. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67607. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67608. var oppositeEndianess = header[0] === 0x01020304;
  67609. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67610. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67611. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67612. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67613. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67614. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67615. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67616. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67617. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67618. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67619. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67620. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67621. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67622. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67623. if (this.glType !== 0) {
  67624. BABYLON.Tools.Error("only compressed formats currently supported");
  67625. return;
  67626. }
  67627. else {
  67628. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67629. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67630. }
  67631. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67632. BABYLON.Tools.Error("only 2D textures currently supported");
  67633. return;
  67634. }
  67635. if (this.numberOfArrayElements !== 0) {
  67636. BABYLON.Tools.Error("texture arrays not currently supported");
  67637. return;
  67638. }
  67639. if (this.numberOfFaces !== facesExpected) {
  67640. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67641. return;
  67642. }
  67643. // we now have a completely validated file, so could use existence of loadType as success
  67644. // would need to make this more elaborate & adjust checks above to support more than one load type
  67645. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67646. }
  67647. // not as fast hardware based, but will probably never need to use
  67648. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67649. return ((val & 0xFF) << 24)
  67650. | ((val & 0xFF00) << 8)
  67651. | ((val >> 8) & 0xFF00)
  67652. | ((val >> 24) & 0xFF);
  67653. };
  67654. /**
  67655. * It is assumed that the texture has already been created & is currently bound
  67656. */
  67657. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67658. switch (this.loadType) {
  67659. case KhronosTextureContainer.COMPRESSED_2D:
  67660. this._upload2DCompressedLevels(gl, loadMipmaps);
  67661. break;
  67662. case KhronosTextureContainer.TEX_2D:
  67663. case KhronosTextureContainer.COMPRESSED_3D:
  67664. case KhronosTextureContainer.TEX_3D:
  67665. }
  67666. };
  67667. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67668. // initialize width & height for level 1
  67669. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67670. var width = this.pixelWidth;
  67671. var height = this.pixelHeight;
  67672. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67673. for (var level = 0; level < mipmapCount; level++) {
  67674. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67675. for (var face = 0; face < this.numberOfFaces; face++) {
  67676. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67677. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67678. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67679. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67680. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67681. }
  67682. width = Math.max(1.0, width * 0.5);
  67683. height = Math.max(1.0, height * 0.5);
  67684. }
  67685. };
  67686. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67687. // load types
  67688. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67689. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67690. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67691. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67692. return KhronosTextureContainer;
  67693. }());
  67694. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67695. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67696. })(BABYLON || (BABYLON = {}));
  67697. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67698. var BABYLON;
  67699. (function (BABYLON) {
  67700. var Debug;
  67701. (function (Debug) {
  67702. /**
  67703. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67704. */
  67705. var SkeletonViewer = /** @class */ (function () {
  67706. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67707. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67708. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67709. this.skeleton = skeleton;
  67710. this.mesh = mesh;
  67711. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67712. this.renderingGroupId = renderingGroupId;
  67713. this.color = BABYLON.Color3.White();
  67714. this._debugLines = new Array();
  67715. this._isEnabled = false;
  67716. this._scene = scene;
  67717. this.update();
  67718. this._renderFunction = this.update.bind(this);
  67719. }
  67720. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67721. get: function () {
  67722. return this._isEnabled;
  67723. },
  67724. set: function (value) {
  67725. if (this._isEnabled === value) {
  67726. return;
  67727. }
  67728. this._isEnabled = value;
  67729. if (value) {
  67730. this._scene.registerBeforeRender(this._renderFunction);
  67731. }
  67732. else {
  67733. this._scene.unregisterBeforeRender(this._renderFunction);
  67734. }
  67735. },
  67736. enumerable: true,
  67737. configurable: true
  67738. });
  67739. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67740. if (x === void 0) { x = 0; }
  67741. if (y === void 0) { y = 0; }
  67742. if (z === void 0) { z = 0; }
  67743. var tmat = BABYLON.Tmp.Matrix[0];
  67744. var parentBone = bone.getParent();
  67745. tmat.copyFrom(bone.getLocalMatrix());
  67746. if (x !== 0 || y !== 0 || z !== 0) {
  67747. var tmat2 = BABYLON.Tmp.Matrix[1];
  67748. BABYLON.Matrix.IdentityToRef(tmat2);
  67749. tmat2.m[12] = x;
  67750. tmat2.m[13] = y;
  67751. tmat2.m[14] = z;
  67752. tmat2.multiplyToRef(tmat, tmat);
  67753. }
  67754. if (parentBone) {
  67755. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67756. }
  67757. tmat.multiplyToRef(meshMat, tmat);
  67758. position.x = tmat.m[12];
  67759. position.y = tmat.m[13];
  67760. position.z = tmat.m[14];
  67761. };
  67762. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67763. var len = bones.length;
  67764. var meshPos = this.mesh.position;
  67765. for (var i = 0; i < len; i++) {
  67766. var bone = bones[i];
  67767. var points = this._debugLines[i];
  67768. if (!points) {
  67769. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67770. this._debugLines[i] = points;
  67771. }
  67772. this._getBonePosition(points[0], bone, meshMat);
  67773. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67774. points[0].subtractInPlace(meshPos);
  67775. points[1].subtractInPlace(meshPos);
  67776. }
  67777. };
  67778. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67779. var len = bones.length;
  67780. var boneNum = 0;
  67781. var meshPos = this.mesh.position;
  67782. for (var i = len - 1; i >= 0; i--) {
  67783. var childBone = bones[i];
  67784. var parentBone = childBone.getParent();
  67785. if (!parentBone) {
  67786. continue;
  67787. }
  67788. var points = this._debugLines[boneNum];
  67789. if (!points) {
  67790. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67791. this._debugLines[boneNum] = points;
  67792. }
  67793. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67794. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67795. points[0].subtractInPlace(meshPos);
  67796. points[1].subtractInPlace(meshPos);
  67797. boneNum++;
  67798. }
  67799. };
  67800. SkeletonViewer.prototype.update = function () {
  67801. if (this.autoUpdateBonesMatrices) {
  67802. this.skeleton.computeAbsoluteTransforms();
  67803. }
  67804. if (this.skeleton.bones[0].length === undefined) {
  67805. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67806. }
  67807. else {
  67808. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67809. }
  67810. if (!this._debugMesh) {
  67811. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67812. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67813. }
  67814. else {
  67815. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67816. }
  67817. this._debugMesh.position.copyFrom(this.mesh.position);
  67818. this._debugMesh.color = this.color;
  67819. };
  67820. SkeletonViewer.prototype.dispose = function () {
  67821. if (this._debugMesh) {
  67822. this.isEnabled = false;
  67823. this._debugMesh.dispose();
  67824. this._debugMesh = null;
  67825. }
  67826. };
  67827. return SkeletonViewer;
  67828. }());
  67829. Debug.SkeletonViewer = SkeletonViewer;
  67830. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67831. })(BABYLON || (BABYLON = {}));
  67832. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67833. var BABYLON;
  67834. (function (BABYLON) {
  67835. var Debug;
  67836. (function (Debug) {
  67837. var AxesViewer = /** @class */ (function () {
  67838. function AxesViewer(scene, scaleLines) {
  67839. if (scaleLines === void 0) { scaleLines = 1; }
  67840. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67841. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67842. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67843. this.scaleLines = 1;
  67844. this.scaleLines = scaleLines;
  67845. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67846. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67847. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  67848. this._xmesh.renderingGroupId = 2;
  67849. this._ymesh.renderingGroupId = 2;
  67850. this._zmesh.renderingGroupId = 2;
  67851. this._xmesh.material.checkReadyOnlyOnce = true;
  67852. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  67853. this._ymesh.material.checkReadyOnlyOnce = true;
  67854. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  67855. this._zmesh.material.checkReadyOnlyOnce = true;
  67856. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  67857. this.scene = scene;
  67858. }
  67859. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  67860. var scaleLines = this.scaleLines;
  67861. if (this._xmesh) {
  67862. this._xmesh.position.copyFrom(position);
  67863. }
  67864. if (this._ymesh) {
  67865. this._ymesh.position.copyFrom(position);
  67866. }
  67867. if (this._zmesh) {
  67868. this._zmesh.position.copyFrom(position);
  67869. }
  67870. var point2 = this._xline[1];
  67871. point2.x = xaxis.x * scaleLines;
  67872. point2.y = xaxis.y * scaleLines;
  67873. point2.z = xaxis.z * scaleLines;
  67874. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  67875. point2 = this._yline[1];
  67876. point2.x = yaxis.x * scaleLines;
  67877. point2.y = yaxis.y * scaleLines;
  67878. point2.z = yaxis.z * scaleLines;
  67879. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  67880. point2 = this._zline[1];
  67881. point2.x = zaxis.x * scaleLines;
  67882. point2.y = zaxis.y * scaleLines;
  67883. point2.z = zaxis.z * scaleLines;
  67884. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  67885. };
  67886. AxesViewer.prototype.dispose = function () {
  67887. if (this._xmesh) {
  67888. this._xmesh.dispose();
  67889. }
  67890. if (this._ymesh) {
  67891. this._ymesh.dispose();
  67892. }
  67893. if (this._zmesh) {
  67894. this._zmesh.dispose();
  67895. }
  67896. this._xmesh = null;
  67897. this._ymesh = null;
  67898. this._zmesh = null;
  67899. this.scene = null;
  67900. };
  67901. return AxesViewer;
  67902. }());
  67903. Debug.AxesViewer = AxesViewer;
  67904. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67905. })(BABYLON || (BABYLON = {}));
  67906. //# sourceMappingURL=babylon.axesViewer.js.map
  67907. var BABYLON;
  67908. (function (BABYLON) {
  67909. var Debug;
  67910. (function (Debug) {
  67911. var BoneAxesViewer = /** @class */ (function (_super) {
  67912. __extends(BoneAxesViewer, _super);
  67913. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  67914. if (scaleLines === void 0) { scaleLines = 1; }
  67915. var _this = _super.call(this, scene, scaleLines) || this;
  67916. _this.pos = BABYLON.Vector3.Zero();
  67917. _this.xaxis = BABYLON.Vector3.Zero();
  67918. _this.yaxis = BABYLON.Vector3.Zero();
  67919. _this.zaxis = BABYLON.Vector3.Zero();
  67920. _this.mesh = mesh;
  67921. _this.bone = bone;
  67922. return _this;
  67923. }
  67924. BoneAxesViewer.prototype.update = function () {
  67925. if (!this.mesh || !this.bone) {
  67926. return;
  67927. }
  67928. var bone = this.bone;
  67929. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  67930. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  67931. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  67932. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  67933. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  67934. };
  67935. BoneAxesViewer.prototype.dispose = function () {
  67936. if (this.mesh) {
  67937. this.mesh = null;
  67938. this.bone = null;
  67939. _super.prototype.dispose.call(this);
  67940. }
  67941. };
  67942. return BoneAxesViewer;
  67943. }(Debug.AxesViewer));
  67944. Debug.BoneAxesViewer = BoneAxesViewer;
  67945. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67946. })(BABYLON || (BABYLON = {}));
  67947. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  67948. var BABYLON;
  67949. (function (BABYLON) {
  67950. var RayHelper = /** @class */ (function () {
  67951. function RayHelper(ray) {
  67952. this.ray = ray;
  67953. }
  67954. RayHelper.CreateAndShow = function (ray, scene, color) {
  67955. var helper = new RayHelper(ray);
  67956. helper.show(scene, color);
  67957. return helper;
  67958. };
  67959. RayHelper.prototype.show = function (scene, color) {
  67960. if (!this._renderFunction && this.ray) {
  67961. var ray = this.ray;
  67962. this._renderFunction = this._render.bind(this);
  67963. this._scene = scene;
  67964. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  67965. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  67966. if (this._renderFunction) {
  67967. this._scene.registerBeforeRender(this._renderFunction);
  67968. }
  67969. }
  67970. if (color && this._renderLine) {
  67971. this._renderLine.color.copyFrom(color);
  67972. }
  67973. };
  67974. RayHelper.prototype.hide = function () {
  67975. if (this._renderFunction && this._scene) {
  67976. this._scene.unregisterBeforeRender(this._renderFunction);
  67977. this._scene = null;
  67978. this._renderFunction = null;
  67979. if (this._renderLine) {
  67980. this._renderLine.dispose();
  67981. this._renderLine = null;
  67982. }
  67983. this._renderPoints = [];
  67984. }
  67985. };
  67986. RayHelper.prototype._render = function () {
  67987. var ray = this.ray;
  67988. if (!ray) {
  67989. return;
  67990. }
  67991. var point = this._renderPoints[1];
  67992. var len = Math.min(ray.length, 1000000);
  67993. point.copyFrom(ray.direction);
  67994. point.scaleInPlace(len);
  67995. point.addInPlace(ray.origin);
  67996. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  67997. };
  67998. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  67999. this._attachedToMesh = mesh;
  68000. var ray = this.ray;
  68001. if (!ray) {
  68002. return;
  68003. }
  68004. if (!ray.direction) {
  68005. ray.direction = BABYLON.Vector3.Zero();
  68006. }
  68007. if (!ray.origin) {
  68008. ray.origin = BABYLON.Vector3.Zero();
  68009. }
  68010. if (length) {
  68011. ray.length = length;
  68012. }
  68013. if (!meshSpaceOrigin) {
  68014. meshSpaceOrigin = BABYLON.Vector3.Zero();
  68015. }
  68016. if (!meshSpaceDirection) {
  68017. // -1 so that this will work with Mesh.lookAt
  68018. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  68019. }
  68020. if (!this._meshSpaceDirection) {
  68021. this._meshSpaceDirection = meshSpaceDirection.clone();
  68022. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  68023. }
  68024. else {
  68025. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  68026. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  68027. }
  68028. if (!this._updateToMeshFunction) {
  68029. this._updateToMeshFunction = this._updateToMesh.bind(this);
  68030. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  68031. }
  68032. this._updateToMesh();
  68033. };
  68034. RayHelper.prototype.detachFromMesh = function () {
  68035. if (this._attachedToMesh) {
  68036. if (this._updateToMeshFunction) {
  68037. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  68038. }
  68039. this._attachedToMesh = null;
  68040. this._updateToMeshFunction = null;
  68041. }
  68042. };
  68043. RayHelper.prototype._updateToMesh = function () {
  68044. var ray = this.ray;
  68045. if (!this._attachedToMesh || !ray) {
  68046. return;
  68047. }
  68048. if (this._attachedToMesh._isDisposed) {
  68049. this.detachFromMesh();
  68050. return;
  68051. }
  68052. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  68053. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  68054. };
  68055. RayHelper.prototype.dispose = function () {
  68056. this.hide();
  68057. this.detachFromMesh();
  68058. this.ray = null;
  68059. };
  68060. return RayHelper;
  68061. }());
  68062. BABYLON.RayHelper = RayHelper;
  68063. })(BABYLON || (BABYLON = {}));
  68064. //# sourceMappingURL=babylon.rayHelper.js.map
  68065. var BABYLON;
  68066. (function (BABYLON) {
  68067. var DebugLayer = /** @class */ (function () {
  68068. function DebugLayer(scene) {
  68069. this._scene = scene;
  68070. }
  68071. /** Creates the inspector window. */
  68072. DebugLayer.prototype._createInspector = function (config) {
  68073. if (config === void 0) { config = {}; }
  68074. var popup = config.popup || false;
  68075. var initialTab = config.initialTab || 0;
  68076. var parentElement = config.parentElement || null;
  68077. if (!this._inspector) {
  68078. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  68079. } // else nothing to do,; instance is already existing
  68080. };
  68081. DebugLayer.prototype.isVisible = function () {
  68082. if (!this._inspector) {
  68083. return false;
  68084. }
  68085. return true;
  68086. };
  68087. DebugLayer.prototype.hide = function () {
  68088. if (this._inspector) {
  68089. try {
  68090. this._inspector.dispose();
  68091. }
  68092. catch (e) {
  68093. // If the inspector has been removed directly from the inspector tool
  68094. }
  68095. this._inspector = null;
  68096. }
  68097. };
  68098. DebugLayer.prototype.show = function (config) {
  68099. if (config === void 0) { config = {}; }
  68100. if (typeof INSPECTOR == 'undefined') {
  68101. // Load inspector and add it to the DOM
  68102. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  68103. }
  68104. else {
  68105. // Otherwise creates the inspector
  68106. this._createInspector(config);
  68107. }
  68108. };
  68109. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  68110. return DebugLayer;
  68111. }());
  68112. BABYLON.DebugLayer = DebugLayer;
  68113. })(BABYLON || (BABYLON = {}));
  68114. //# sourceMappingURL=babylon.debugLayer.js.map
  68115. var BABYLON;
  68116. (function (BABYLON) {
  68117. var Debug;
  68118. (function (Debug) {
  68119. var PhysicsViewer = /** @class */ (function () {
  68120. function PhysicsViewer(scene) {
  68121. this._impostors = [];
  68122. this._meshes = [];
  68123. this._numMeshes = 0;
  68124. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68125. var physicEngine = this._scene.getPhysicsEngine();
  68126. if (physicEngine) {
  68127. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  68128. }
  68129. }
  68130. PhysicsViewer.prototype._updateDebugMeshes = function () {
  68131. var plugin = this._physicsEnginePlugin;
  68132. for (var i = 0; i < this._numMeshes; i++) {
  68133. var impostor = this._impostors[i];
  68134. if (!impostor) {
  68135. continue;
  68136. }
  68137. if (impostor.isDisposed) {
  68138. this.hideImpostor(this._impostors[i--]);
  68139. }
  68140. else {
  68141. var mesh = this._meshes[i];
  68142. if (mesh && plugin) {
  68143. plugin.syncMeshWithImpostor(mesh, impostor);
  68144. }
  68145. }
  68146. }
  68147. };
  68148. PhysicsViewer.prototype.showImpostor = function (impostor) {
  68149. if (!this._scene) {
  68150. return;
  68151. }
  68152. for (var i = 0; i < this._numMeshes; i++) {
  68153. if (this._impostors[i] == impostor) {
  68154. return;
  68155. }
  68156. }
  68157. var debugMesh = this._getDebugMesh(impostor, this._scene);
  68158. if (debugMesh) {
  68159. this._impostors[this._numMeshes] = impostor;
  68160. this._meshes[this._numMeshes] = debugMesh;
  68161. if (this._numMeshes === 0) {
  68162. this._renderFunction = this._updateDebugMeshes.bind(this);
  68163. this._scene.registerBeforeRender(this._renderFunction);
  68164. }
  68165. this._numMeshes++;
  68166. }
  68167. };
  68168. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  68169. if (!impostor || !this._scene) {
  68170. return;
  68171. }
  68172. var removed = false;
  68173. for (var i = 0; i < this._numMeshes; i++) {
  68174. if (this._impostors[i] == impostor) {
  68175. var mesh = this._meshes[i];
  68176. if (!mesh) {
  68177. continue;
  68178. }
  68179. this._scene.removeMesh(mesh);
  68180. mesh.dispose();
  68181. this._numMeshes--;
  68182. if (this._numMeshes > 0) {
  68183. this._meshes[i] = this._meshes[this._numMeshes];
  68184. this._impostors[i] = this._impostors[this._numMeshes];
  68185. this._meshes[this._numMeshes] = null;
  68186. this._impostors[this._numMeshes] = null;
  68187. }
  68188. else {
  68189. this._meshes[0] = null;
  68190. this._impostors[0] = null;
  68191. }
  68192. removed = true;
  68193. break;
  68194. }
  68195. }
  68196. if (removed && this._numMeshes === 0) {
  68197. this._scene.unregisterBeforeRender(this._renderFunction);
  68198. }
  68199. };
  68200. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  68201. if (!this._debugMaterial) {
  68202. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  68203. this._debugMaterial.wireframe = true;
  68204. }
  68205. return this._debugMaterial;
  68206. };
  68207. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  68208. if (!this._debugBoxMesh) {
  68209. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  68210. this._debugBoxMesh.renderingGroupId = 1;
  68211. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68212. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  68213. scene.removeMesh(this._debugBoxMesh);
  68214. }
  68215. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  68216. };
  68217. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  68218. if (!this._debugSphereMesh) {
  68219. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  68220. this._debugSphereMesh.renderingGroupId = 1;
  68221. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68222. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  68223. scene.removeMesh(this._debugSphereMesh);
  68224. }
  68225. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  68226. };
  68227. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  68228. var mesh = null;
  68229. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  68230. mesh = this._getDebugBoxMesh(scene);
  68231. impostor.getBoxSizeToRef(mesh.scaling);
  68232. }
  68233. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  68234. mesh = this._getDebugSphereMesh(scene);
  68235. var radius = impostor.getRadius();
  68236. mesh.scaling.x = radius * 2;
  68237. mesh.scaling.y = radius * 2;
  68238. mesh.scaling.z = radius * 2;
  68239. }
  68240. return mesh;
  68241. };
  68242. PhysicsViewer.prototype.dispose = function () {
  68243. for (var i = 0; i < this._numMeshes; i++) {
  68244. this.hideImpostor(this._impostors[i]);
  68245. }
  68246. if (this._debugBoxMesh) {
  68247. this._debugBoxMesh.dispose();
  68248. }
  68249. if (this._debugSphereMesh) {
  68250. this._debugSphereMesh.dispose();
  68251. }
  68252. if (this._debugMaterial) {
  68253. this._debugMaterial.dispose();
  68254. }
  68255. this._impostors.length = 0;
  68256. this._scene = null;
  68257. this._physicsEnginePlugin = null;
  68258. };
  68259. return PhysicsViewer;
  68260. }());
  68261. Debug.PhysicsViewer = PhysicsViewer;
  68262. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68263. })(BABYLON || (BABYLON = {}));
  68264. //# sourceMappingURL=babylon.physicsViewer.js.map
  68265. var BABYLON;
  68266. (function (BABYLON) {
  68267. var BoundingBoxRenderer = /** @class */ (function () {
  68268. function BoundingBoxRenderer(scene) {
  68269. this.frontColor = new BABYLON.Color3(1, 1, 1);
  68270. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  68271. this.showBackLines = true;
  68272. this.renderList = new BABYLON.SmartArray(32);
  68273. this._vertexBuffers = {};
  68274. this._scene = scene;
  68275. }
  68276. BoundingBoxRenderer.prototype._prepareRessources = function () {
  68277. if (this._colorShader) {
  68278. return;
  68279. }
  68280. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  68281. attributes: [BABYLON.VertexBuffer.PositionKind],
  68282. uniforms: ["world", "viewProjection", "color"]
  68283. });
  68284. var engine = this._scene.getEngine();
  68285. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  68286. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  68287. this._createIndexBuffer();
  68288. };
  68289. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  68290. var engine = this._scene.getEngine();
  68291. 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]);
  68292. };
  68293. BoundingBoxRenderer.prototype._rebuild = function () {
  68294. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68295. if (vb) {
  68296. vb._rebuild();
  68297. }
  68298. this._createIndexBuffer();
  68299. };
  68300. BoundingBoxRenderer.prototype.reset = function () {
  68301. this.renderList.reset();
  68302. };
  68303. BoundingBoxRenderer.prototype.render = function () {
  68304. if (this.renderList.length === 0) {
  68305. return;
  68306. }
  68307. this._prepareRessources();
  68308. if (!this._colorShader.isReady()) {
  68309. return;
  68310. }
  68311. var engine = this._scene.getEngine();
  68312. engine.setDepthWrite(false);
  68313. this._colorShader._preBind();
  68314. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  68315. var boundingBox = this.renderList.data[boundingBoxIndex];
  68316. var min = boundingBox.minimum;
  68317. var max = boundingBox.maximum;
  68318. var diff = max.subtract(min);
  68319. var median = min.add(diff.scale(0.5));
  68320. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68321. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68322. .multiply(boundingBox.getWorldMatrix());
  68323. // VBOs
  68324. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68325. if (this.showBackLines) {
  68326. // Back
  68327. engine.setDepthFunctionToGreaterOrEqual();
  68328. this._scene.resetCachedMaterial();
  68329. this._colorShader.setColor4("color", this.backColor.toColor4());
  68330. this._colorShader.bind(worldMatrix);
  68331. // Draw order
  68332. engine.draw(false, 0, 24);
  68333. }
  68334. // Front
  68335. engine.setDepthFunctionToLess();
  68336. this._scene.resetCachedMaterial();
  68337. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68338. this._colorShader.bind(worldMatrix);
  68339. // Draw order
  68340. engine.draw(false, 0, 24);
  68341. }
  68342. this._colorShader.unbind();
  68343. engine.setDepthFunctionToLessOrEqual();
  68344. engine.setDepthWrite(true);
  68345. };
  68346. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68347. this._prepareRessources();
  68348. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68349. return;
  68350. }
  68351. var engine = this._scene.getEngine();
  68352. engine.setDepthWrite(false);
  68353. engine.setColorWrite(false);
  68354. this._colorShader._preBind();
  68355. var boundingBox = mesh._boundingInfo.boundingBox;
  68356. var min = boundingBox.minimum;
  68357. var max = boundingBox.maximum;
  68358. var diff = max.subtract(min);
  68359. var median = min.add(diff.scale(0.5));
  68360. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68361. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68362. .multiply(boundingBox.getWorldMatrix());
  68363. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68364. engine.setDepthFunctionToLess();
  68365. this._scene.resetCachedMaterial();
  68366. this._colorShader.bind(worldMatrix);
  68367. engine.draw(false, 0, 24);
  68368. this._colorShader.unbind();
  68369. engine.setDepthFunctionToLessOrEqual();
  68370. engine.setDepthWrite(true);
  68371. engine.setColorWrite(true);
  68372. };
  68373. BoundingBoxRenderer.prototype.dispose = function () {
  68374. if (!this._colorShader) {
  68375. return;
  68376. }
  68377. this.renderList.dispose();
  68378. this._colorShader.dispose();
  68379. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68380. if (buffer) {
  68381. buffer.dispose();
  68382. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68383. }
  68384. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68385. };
  68386. return BoundingBoxRenderer;
  68387. }());
  68388. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68389. })(BABYLON || (BABYLON = {}));
  68390. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68391. var BABYLON;
  68392. (function (BABYLON) {
  68393. var MorphTarget = /** @class */ (function () {
  68394. function MorphTarget(name, influence) {
  68395. if (influence === void 0) { influence = 0; }
  68396. this.name = name;
  68397. this.animations = new Array();
  68398. this._positions = null;
  68399. this._normals = null;
  68400. this._tangents = null;
  68401. this.onInfluenceChanged = new BABYLON.Observable();
  68402. this.influence = influence;
  68403. }
  68404. Object.defineProperty(MorphTarget.prototype, "influence", {
  68405. get: function () {
  68406. return this._influence;
  68407. },
  68408. set: function (influence) {
  68409. if (this._influence === influence) {
  68410. return;
  68411. }
  68412. var previous = this._influence;
  68413. this._influence = influence;
  68414. if (this.onInfluenceChanged.hasObservers) {
  68415. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68416. }
  68417. },
  68418. enumerable: true,
  68419. configurable: true
  68420. });
  68421. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  68422. get: function () {
  68423. return !!this._positions;
  68424. },
  68425. enumerable: true,
  68426. configurable: true
  68427. });
  68428. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68429. get: function () {
  68430. return !!this._normals;
  68431. },
  68432. enumerable: true,
  68433. configurable: true
  68434. });
  68435. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68436. get: function () {
  68437. return !!this._tangents;
  68438. },
  68439. enumerable: true,
  68440. configurable: true
  68441. });
  68442. MorphTarget.prototype.setPositions = function (data) {
  68443. this._positions = data;
  68444. };
  68445. MorphTarget.prototype.getPositions = function () {
  68446. return this._positions;
  68447. };
  68448. MorphTarget.prototype.setNormals = function (data) {
  68449. this._normals = data;
  68450. };
  68451. MorphTarget.prototype.getNormals = function () {
  68452. return this._normals;
  68453. };
  68454. MorphTarget.prototype.setTangents = function (data) {
  68455. this._tangents = data;
  68456. };
  68457. MorphTarget.prototype.getTangents = function () {
  68458. return this._tangents;
  68459. };
  68460. /**
  68461. * Serializes the current target into a Serialization object.
  68462. * Returns the serialized object.
  68463. */
  68464. MorphTarget.prototype.serialize = function () {
  68465. var serializationObject = {};
  68466. serializationObject.name = this.name;
  68467. serializationObject.influence = this.influence;
  68468. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68469. if (this.hasNormals) {
  68470. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68471. }
  68472. if (this.hasTangents) {
  68473. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68474. }
  68475. // Animations
  68476. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68477. return serializationObject;
  68478. };
  68479. // Statics
  68480. MorphTarget.Parse = function (serializationObject) {
  68481. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68482. result.setPositions(serializationObject.positions);
  68483. if (serializationObject.normals) {
  68484. result.setNormals(serializationObject.normals);
  68485. }
  68486. if (serializationObject.tangents) {
  68487. result.setTangents(serializationObject.tangents);
  68488. }
  68489. // Animations
  68490. if (serializationObject.animations) {
  68491. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68492. var parsedAnimation = serializationObject.animations[animationIndex];
  68493. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68494. }
  68495. }
  68496. return result;
  68497. };
  68498. MorphTarget.FromMesh = function (mesh, name, influence) {
  68499. if (!name) {
  68500. name = mesh.name;
  68501. }
  68502. var result = new MorphTarget(name, influence);
  68503. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68504. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68505. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68506. }
  68507. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68508. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68509. }
  68510. return result;
  68511. };
  68512. return MorphTarget;
  68513. }());
  68514. BABYLON.MorphTarget = MorphTarget;
  68515. })(BABYLON || (BABYLON = {}));
  68516. //# sourceMappingURL=babylon.morphTarget.js.map
  68517. var BABYLON;
  68518. (function (BABYLON) {
  68519. var MorphTargetManager = /** @class */ (function () {
  68520. function MorphTargetManager(scene) {
  68521. if (scene === void 0) { scene = null; }
  68522. this._targets = new Array();
  68523. this._targetObservable = new Array();
  68524. this._activeTargets = new BABYLON.SmartArray(16);
  68525. this._supportsNormals = false;
  68526. this._supportsTangents = false;
  68527. this._vertexCount = 0;
  68528. this._uniqueId = 0;
  68529. this._tempInfluences = new Array();
  68530. if (!scene) {
  68531. scene = BABYLON.Engine.LastCreatedScene;
  68532. }
  68533. this._scene = scene;
  68534. if (this._scene) {
  68535. this._scene.morphTargetManagers.push(this);
  68536. this._uniqueId = this._scene.getUniqueId();
  68537. }
  68538. }
  68539. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68540. get: function () {
  68541. return this._uniqueId;
  68542. },
  68543. enumerable: true,
  68544. configurable: true
  68545. });
  68546. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68547. get: function () {
  68548. return this._vertexCount;
  68549. },
  68550. enumerable: true,
  68551. configurable: true
  68552. });
  68553. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68554. get: function () {
  68555. return this._supportsNormals;
  68556. },
  68557. enumerable: true,
  68558. configurable: true
  68559. });
  68560. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68561. get: function () {
  68562. return this._supportsTangents;
  68563. },
  68564. enumerable: true,
  68565. configurable: true
  68566. });
  68567. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68568. get: function () {
  68569. return this._targets.length;
  68570. },
  68571. enumerable: true,
  68572. configurable: true
  68573. });
  68574. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68575. get: function () {
  68576. return this._activeTargets.length;
  68577. },
  68578. enumerable: true,
  68579. configurable: true
  68580. });
  68581. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68582. get: function () {
  68583. return this._influences;
  68584. },
  68585. enumerable: true,
  68586. configurable: true
  68587. });
  68588. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68589. return this._activeTargets.data[index];
  68590. };
  68591. MorphTargetManager.prototype.getTarget = function (index) {
  68592. return this._targets[index];
  68593. };
  68594. MorphTargetManager.prototype.addTarget = function (target) {
  68595. var _this = this;
  68596. this._targets.push(target);
  68597. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68598. _this._syncActiveTargets(needUpdate);
  68599. }));
  68600. this._syncActiveTargets(true);
  68601. };
  68602. MorphTargetManager.prototype.removeTarget = function (target) {
  68603. var index = this._targets.indexOf(target);
  68604. if (index >= 0) {
  68605. this._targets.splice(index, 1);
  68606. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68607. this._syncActiveTargets(true);
  68608. }
  68609. };
  68610. /**
  68611. * Serializes the current manager into a Serialization object.
  68612. * Returns the serialized object.
  68613. */
  68614. MorphTargetManager.prototype.serialize = function () {
  68615. var serializationObject = {};
  68616. serializationObject.id = this.uniqueId;
  68617. serializationObject.targets = [];
  68618. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68619. var target = _a[_i];
  68620. serializationObject.targets.push(target.serialize());
  68621. }
  68622. return serializationObject;
  68623. };
  68624. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68625. var influenceCount = 0;
  68626. this._activeTargets.reset();
  68627. this._supportsNormals = true;
  68628. this._supportsTangents = true;
  68629. this._vertexCount = 0;
  68630. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68631. var target = _a[_i];
  68632. if (target.influence > 0) {
  68633. this._activeTargets.push(target);
  68634. this._tempInfluences[influenceCount++] = target.influence;
  68635. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68636. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68637. var positions = target.getPositions();
  68638. if (!positions) {
  68639. BABYLON.Tools.Error("Invalid target. Target must positions.");
  68640. return;
  68641. }
  68642. var vertexCount = positions.length / 3;
  68643. if (this._vertexCount === 0) {
  68644. this._vertexCount = vertexCount;
  68645. }
  68646. else if (this._vertexCount !== vertexCount) {
  68647. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68648. return;
  68649. }
  68650. }
  68651. }
  68652. if (!this._influences || this._influences.length !== influenceCount) {
  68653. this._influences = new Float32Array(influenceCount);
  68654. }
  68655. for (var index = 0; index < influenceCount; index++) {
  68656. this._influences[index] = this._tempInfluences[index];
  68657. }
  68658. if (needUpdate && this._scene) {
  68659. // Flag meshes as dirty to resync with the active targets
  68660. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68661. var mesh = _c[_b];
  68662. if (mesh.morphTargetManager === this) {
  68663. mesh._syncGeometryWithMorphTargetManager();
  68664. }
  68665. }
  68666. }
  68667. };
  68668. // Statics
  68669. MorphTargetManager.Parse = function (serializationObject, scene) {
  68670. var result = new MorphTargetManager(scene);
  68671. result._uniqueId = serializationObject.id;
  68672. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68673. var targetData = _a[_i];
  68674. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68675. }
  68676. return result;
  68677. };
  68678. return MorphTargetManager;
  68679. }());
  68680. BABYLON.MorphTargetManager = MorphTargetManager;
  68681. })(BABYLON || (BABYLON = {}));
  68682. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68683. var BABYLON;
  68684. (function (BABYLON) {
  68685. var Octree = /** @class */ (function () {
  68686. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68687. if (maxDepth === void 0) { maxDepth = 2; }
  68688. this.maxDepth = maxDepth;
  68689. this.dynamicContent = new Array();
  68690. this._maxBlockCapacity = maxBlockCapacity || 64;
  68691. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  68692. this._creationFunc = creationFunc;
  68693. }
  68694. // Methods
  68695. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68696. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68697. };
  68698. Octree.prototype.addMesh = function (entry) {
  68699. for (var index = 0; index < this.blocks.length; index++) {
  68700. var block = this.blocks[index];
  68701. block.addEntry(entry);
  68702. }
  68703. };
  68704. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68705. this._selectionContent.reset();
  68706. for (var index = 0; index < this.blocks.length; index++) {
  68707. var block = this.blocks[index];
  68708. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68709. }
  68710. if (allowDuplicate) {
  68711. this._selectionContent.concat(this.dynamicContent);
  68712. }
  68713. else {
  68714. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68715. }
  68716. return this._selectionContent;
  68717. };
  68718. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68719. this._selectionContent.reset();
  68720. for (var index = 0; index < this.blocks.length; index++) {
  68721. var block = this.blocks[index];
  68722. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68723. }
  68724. if (allowDuplicate) {
  68725. this._selectionContent.concat(this.dynamicContent);
  68726. }
  68727. else {
  68728. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68729. }
  68730. return this._selectionContent;
  68731. };
  68732. Octree.prototype.intersectsRay = function (ray) {
  68733. this._selectionContent.reset();
  68734. for (var index = 0; index < this.blocks.length; index++) {
  68735. var block = this.blocks[index];
  68736. block.intersectsRay(ray, this._selectionContent);
  68737. }
  68738. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68739. return this._selectionContent;
  68740. };
  68741. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68742. target.blocks = new Array();
  68743. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68744. // Segmenting space
  68745. for (var x = 0; x < 2; x++) {
  68746. for (var y = 0; y < 2; y++) {
  68747. for (var z = 0; z < 2; z++) {
  68748. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68749. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68750. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68751. block.addEntries(entries);
  68752. target.blocks.push(block);
  68753. }
  68754. }
  68755. }
  68756. };
  68757. Octree.CreationFuncForMeshes = function (entry, block) {
  68758. var boundingInfo = entry.getBoundingInfo();
  68759. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68760. block.entries.push(entry);
  68761. }
  68762. };
  68763. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68764. var boundingInfo = entry.getBoundingInfo();
  68765. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68766. block.entries.push(entry);
  68767. }
  68768. };
  68769. return Octree;
  68770. }());
  68771. BABYLON.Octree = Octree;
  68772. })(BABYLON || (BABYLON = {}));
  68773. //# sourceMappingURL=babylon.octree.js.map
  68774. var BABYLON;
  68775. (function (BABYLON) {
  68776. var OctreeBlock = /** @class */ (function () {
  68777. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68778. this.entries = new Array();
  68779. this._boundingVectors = new Array();
  68780. this._capacity = capacity;
  68781. this._depth = depth;
  68782. this._maxDepth = maxDepth;
  68783. this._creationFunc = creationFunc;
  68784. this._minPoint = minPoint;
  68785. this._maxPoint = maxPoint;
  68786. this._boundingVectors.push(minPoint.clone());
  68787. this._boundingVectors.push(maxPoint.clone());
  68788. this._boundingVectors.push(minPoint.clone());
  68789. this._boundingVectors[2].x = maxPoint.x;
  68790. this._boundingVectors.push(minPoint.clone());
  68791. this._boundingVectors[3].y = maxPoint.y;
  68792. this._boundingVectors.push(minPoint.clone());
  68793. this._boundingVectors[4].z = maxPoint.z;
  68794. this._boundingVectors.push(maxPoint.clone());
  68795. this._boundingVectors[5].z = minPoint.z;
  68796. this._boundingVectors.push(maxPoint.clone());
  68797. this._boundingVectors[6].x = minPoint.x;
  68798. this._boundingVectors.push(maxPoint.clone());
  68799. this._boundingVectors[7].y = minPoint.y;
  68800. }
  68801. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68802. // Property
  68803. get: function () {
  68804. return this._capacity;
  68805. },
  68806. enumerable: true,
  68807. configurable: true
  68808. });
  68809. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68810. get: function () {
  68811. return this._minPoint;
  68812. },
  68813. enumerable: true,
  68814. configurable: true
  68815. });
  68816. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68817. get: function () {
  68818. return this._maxPoint;
  68819. },
  68820. enumerable: true,
  68821. configurable: true
  68822. });
  68823. // Methods
  68824. OctreeBlock.prototype.addEntry = function (entry) {
  68825. if (this.blocks) {
  68826. for (var index = 0; index < this.blocks.length; index++) {
  68827. var block = this.blocks[index];
  68828. block.addEntry(entry);
  68829. }
  68830. return;
  68831. }
  68832. this._creationFunc(entry, this);
  68833. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68834. this.createInnerBlocks();
  68835. }
  68836. };
  68837. OctreeBlock.prototype.addEntries = function (entries) {
  68838. for (var index = 0; index < entries.length; index++) {
  68839. var mesh = entries[index];
  68840. this.addEntry(mesh);
  68841. }
  68842. };
  68843. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68844. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68845. if (this.blocks) {
  68846. for (var index = 0; index < this.blocks.length; index++) {
  68847. var block = this.blocks[index];
  68848. block.select(frustumPlanes, selection, allowDuplicate);
  68849. }
  68850. return;
  68851. }
  68852. if (allowDuplicate) {
  68853. selection.concat(this.entries);
  68854. }
  68855. else {
  68856. selection.concatWithNoDuplicate(this.entries);
  68857. }
  68858. }
  68859. };
  68860. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  68861. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  68862. if (this.blocks) {
  68863. for (var index = 0; index < this.blocks.length; index++) {
  68864. var block = this.blocks[index];
  68865. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  68866. }
  68867. return;
  68868. }
  68869. if (allowDuplicate) {
  68870. selection.concat(this.entries);
  68871. }
  68872. else {
  68873. selection.concatWithNoDuplicate(this.entries);
  68874. }
  68875. }
  68876. };
  68877. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  68878. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  68879. if (this.blocks) {
  68880. for (var index = 0; index < this.blocks.length; index++) {
  68881. var block = this.blocks[index];
  68882. block.intersectsRay(ray, selection);
  68883. }
  68884. return;
  68885. }
  68886. selection.concatWithNoDuplicate(this.entries);
  68887. }
  68888. };
  68889. OctreeBlock.prototype.createInnerBlocks = function () {
  68890. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  68891. };
  68892. return OctreeBlock;
  68893. }());
  68894. BABYLON.OctreeBlock = OctreeBlock;
  68895. })(BABYLON || (BABYLON = {}));
  68896. //# sourceMappingURL=babylon.octreeBlock.js.map
  68897. var BABYLON;
  68898. (function (BABYLON) {
  68899. var SIMDVector3 = /** @class */ (function () {
  68900. function SIMDVector3() {
  68901. }
  68902. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  68903. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  68904. };
  68905. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  68906. var m = transformation.m;
  68907. var m0 = SIMD.Float32x4.load(m, 0);
  68908. var m1 = SIMD.Float32x4.load(m, 4);
  68909. var m2 = SIMD.Float32x4.load(m, 8);
  68910. var m3 = SIMD.Float32x4.load(m, 12);
  68911. 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));
  68912. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  68913. result.x = SIMD.Float32x4.extractLane(r, 0);
  68914. result.y = SIMD.Float32x4.extractLane(r, 1);
  68915. result.z = SIMD.Float32x4.extractLane(r, 2);
  68916. };
  68917. return SIMDVector3;
  68918. }());
  68919. var SIMDMatrix = /** @class */ (function () {
  68920. function SIMDMatrix() {
  68921. }
  68922. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  68923. var tm = this.m;
  68924. var om = other.m;
  68925. var m0 = SIMD.Float32x4.load(om, 0);
  68926. var m1 = SIMD.Float32x4.load(om, 4);
  68927. var m2 = SIMD.Float32x4.load(om, 8);
  68928. var m3 = SIMD.Float32x4.load(om, 12);
  68929. for (var i = 0; i < 16; i += 4) {
  68930. 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)))));
  68931. }
  68932. return this;
  68933. };
  68934. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  68935. var src = this.m;
  68936. var dest = other.m;
  68937. // Load the 4 rows
  68938. var src0 = SIMD.Float32x4.load(src, 0);
  68939. var src1 = SIMD.Float32x4.load(src, 4);
  68940. var src2 = SIMD.Float32x4.load(src, 8);
  68941. var src3 = SIMD.Float32x4.load(src, 12);
  68942. // Transpose the source matrix. Sort of. Not a true transpose operation
  68943. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  68944. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  68945. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  68946. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  68947. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  68948. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  68949. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  68950. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  68951. // This is a true transposition, but it will lead to an incorrect result
  68952. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  68953. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  68954. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68955. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68956. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  68957. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  68958. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68959. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68960. // ----
  68961. tmp1 = SIMD.Float32x4.mul(row2, row3);
  68962. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68963. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  68964. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  68965. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68966. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  68967. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  68968. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  68969. // ----
  68970. tmp1 = SIMD.Float32x4.mul(row1, row2);
  68971. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68972. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  68973. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  68974. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68975. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  68976. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  68977. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  68978. // ----
  68979. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  68980. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68981. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  68982. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  68983. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  68984. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68985. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  68986. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  68987. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  68988. // ----
  68989. tmp1 = SIMD.Float32x4.mul(row0, row1);
  68990. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68991. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68992. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  68993. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68994. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68995. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  68996. // ----
  68997. tmp1 = SIMD.Float32x4.mul(row0, row3);
  68998. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68999. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  69000. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  69001. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69002. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  69003. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  69004. // ----
  69005. tmp1 = SIMD.Float32x4.mul(row0, row2);
  69006. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69007. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  69008. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  69009. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69010. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  69011. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  69012. // Compute determinant
  69013. var det = SIMD.Float32x4.mul(row0, minor0);
  69014. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  69015. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  69016. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  69017. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  69018. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  69019. // These shuffles aren't necessary if the faulty transposition is done
  69020. // up at the top of this function.
  69021. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  69022. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  69023. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  69024. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  69025. // Compute final values by multiplying with 1/det
  69026. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  69027. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  69028. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  69029. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  69030. return this;
  69031. };
  69032. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  69033. var out = result.m;
  69034. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  69035. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  69036. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  69037. // cc.kmVec3Subtract(f, pCenter, pEye);
  69038. var f = SIMD.Float32x4.sub(center, eye);
  69039. // cc.kmVec3Normalize(f, f);
  69040. var tmp = SIMD.Float32x4.mul(f, f);
  69041. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69042. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69043. // cc.kmVec3Assign(up, pUp);
  69044. // cc.kmVec3Normalize(up, up);
  69045. tmp = SIMD.Float32x4.mul(up, up);
  69046. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69047. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69048. // cc.kmVec3Cross(s, f, up);
  69049. 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)));
  69050. // cc.kmVec3Normalize(s, s);
  69051. tmp = SIMD.Float32x4.mul(s, s);
  69052. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69053. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69054. // cc.kmVec3Cross(u, s, f);
  69055. 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)));
  69056. // cc.kmVec3Normalize(s, s);
  69057. tmp = SIMD.Float32x4.mul(s, s);
  69058. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69059. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69060. var zero = SIMD.Float32x4.splat(0.0);
  69061. s = SIMD.Float32x4.neg(s);
  69062. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  69063. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  69064. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  69065. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  69066. 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);
  69067. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  69068. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  69069. 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)))));
  69070. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  69071. 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)))));
  69072. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  69073. 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)))));
  69074. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  69075. 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)))));
  69076. };
  69077. return SIMDMatrix;
  69078. }());
  69079. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  69080. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  69081. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  69082. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  69083. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  69084. var SIMDHelper = /** @class */ (function () {
  69085. function SIMDHelper() {
  69086. }
  69087. Object.defineProperty(SIMDHelper, "IsEnabled", {
  69088. get: function () {
  69089. return SIMDHelper._isEnabled;
  69090. },
  69091. enumerable: true,
  69092. configurable: true
  69093. });
  69094. SIMDHelper.DisableSIMD = function () {
  69095. // Replace functions
  69096. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  69097. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  69098. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  69099. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  69100. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  69101. SIMDHelper._isEnabled = false;
  69102. };
  69103. SIMDHelper.EnableSIMD = function () {
  69104. if (self.SIMD === undefined) {
  69105. return;
  69106. }
  69107. // check if polyfills needed
  69108. if (!self.Math.fround) {
  69109. self.Math.fround = (function (array) { return function (x) {
  69110. return array[0] = x, array[0];
  69111. }; })(new Float32Array(1));
  69112. }
  69113. if (!self.Math.imul) {
  69114. self.Math.imul = function (a, b) {
  69115. var ah = (a >>> 16) & 0xffff;
  69116. var al = a & 0xffff;
  69117. var bh = (b >>> 16) & 0xffff;
  69118. var bl = b & 0xffff;
  69119. // the shift by 0 fixes the sign on the high part
  69120. // the final |0 converts the unsigned value into a signed value
  69121. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  69122. };
  69123. }
  69124. // Replace functions
  69125. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  69126. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  69127. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  69128. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  69129. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  69130. SIMDHelper._isEnabled = true;
  69131. };
  69132. SIMDHelper._isEnabled = false;
  69133. return SIMDHelper;
  69134. }());
  69135. BABYLON.SIMDHelper = SIMDHelper;
  69136. })(BABYLON || (BABYLON = {}));
  69137. //# sourceMappingURL=babylon.math.SIMD.js.map
  69138. var BABYLON;
  69139. (function (BABYLON) {
  69140. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  69141. __extends(VRDistortionCorrectionPostProcess, _super);
  69142. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  69143. var _this = _super.call(this, name, "vrDistortionCorrection", [
  69144. 'LensCenter',
  69145. 'Scale',
  69146. 'ScaleIn',
  69147. 'HmdWarpParam'
  69148. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  69149. _this._isRightEye = isRightEye;
  69150. _this._distortionFactors = vrMetrics.distortionK;
  69151. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  69152. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  69153. _this.adaptScaleToCurrentViewport = true;
  69154. _this.onSizeChangedObservable.add(function () {
  69155. _this.aspectRatio = _this.width * .5 / _this.height;
  69156. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  69157. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  69158. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  69159. });
  69160. _this.onApplyObservable.add(function (effect) {
  69161. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  69162. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  69163. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  69164. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  69165. });
  69166. return _this;
  69167. }
  69168. return VRDistortionCorrectionPostProcess;
  69169. }(BABYLON.PostProcess));
  69170. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  69171. })(BABYLON || (BABYLON = {}));
  69172. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  69173. var BABYLON;
  69174. (function (BABYLON) {
  69175. var AnaglyphPostProcess = /** @class */ (function (_super) {
  69176. __extends(AnaglyphPostProcess, _super);
  69177. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  69178. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  69179. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69180. _this.onApplyObservable.add(function (effect) {
  69181. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  69182. });
  69183. return _this;
  69184. }
  69185. return AnaglyphPostProcess;
  69186. }(BABYLON.PostProcess));
  69187. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  69188. })(BABYLON || (BABYLON = {}));
  69189. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  69190. var BABYLON;
  69191. (function (BABYLON) {
  69192. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  69193. __extends(StereoscopicInterlacePostProcess, _super);
  69194. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  69195. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  69196. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69197. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69198. _this.onSizeChangedObservable.add(function () {
  69199. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69200. });
  69201. _this.onApplyObservable.add(function (effect) {
  69202. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  69203. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  69204. });
  69205. return _this;
  69206. }
  69207. return StereoscopicInterlacePostProcess;
  69208. }(BABYLON.PostProcess));
  69209. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  69210. })(BABYLON || (BABYLON = {}));
  69211. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  69212. var BABYLON;
  69213. (function (BABYLON) {
  69214. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  69215. function FreeCameraDeviceOrientationInput() {
  69216. var _this = this;
  69217. this._screenOrientationAngle = 0;
  69218. this._screenQuaternion = new BABYLON.Quaternion();
  69219. this._alpha = 0;
  69220. this._beta = 0;
  69221. this._gamma = 0;
  69222. this._orientationChanged = function () {
  69223. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  69224. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  69225. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  69226. };
  69227. this._deviceOrientation = function (evt) {
  69228. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  69229. _this._beta = evt.beta !== null ? evt.beta : 0;
  69230. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  69231. };
  69232. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  69233. this._orientationChanged();
  69234. }
  69235. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  69236. get: function () {
  69237. return this._camera;
  69238. },
  69239. set: function (camera) {
  69240. this._camera = camera;
  69241. if (this._camera != null && !this._camera.rotationQuaternion) {
  69242. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  69243. }
  69244. },
  69245. enumerable: true,
  69246. configurable: true
  69247. });
  69248. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69249. window.addEventListener("orientationchange", this._orientationChanged);
  69250. window.addEventListener("deviceorientation", this._deviceOrientation);
  69251. //In certain cases, the attach control is called AFTER orientation was changed,
  69252. //So this is needed.
  69253. this._orientationChanged();
  69254. };
  69255. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  69256. window.removeEventListener("orientationchange", this._orientationChanged);
  69257. window.removeEventListener("deviceorientation", this._deviceOrientation);
  69258. };
  69259. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  69260. //if no device orientation provided, don't update the rotation.
  69261. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  69262. if (!this._alpha)
  69263. return;
  69264. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  69265. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  69266. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  69267. //Mirror on XY Plane
  69268. this._camera.rotationQuaternion.z *= -1;
  69269. this._camera.rotationQuaternion.w *= -1;
  69270. };
  69271. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  69272. return "FreeCameraDeviceOrientationInput";
  69273. };
  69274. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  69275. return "deviceOrientation";
  69276. };
  69277. return FreeCameraDeviceOrientationInput;
  69278. }());
  69279. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  69280. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  69281. })(BABYLON || (BABYLON = {}));
  69282. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  69283. var BABYLON;
  69284. (function (BABYLON) {
  69285. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  69286. function ArcRotateCameraVRDeviceOrientationInput() {
  69287. this.alphaCorrection = 1;
  69288. this.betaCorrection = 1;
  69289. this.gammaCorrection = 1;
  69290. this._alpha = 0;
  69291. this._beta = 0;
  69292. this._gamma = 0;
  69293. this._dirty = false;
  69294. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  69295. }
  69296. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69297. this.camera.attachControl(element, noPreventDefault);
  69298. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  69299. };
  69300. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  69301. if (evt.alpha !== null) {
  69302. this._alpha = +evt.alpha | 0;
  69303. }
  69304. if (evt.beta !== null) {
  69305. this._beta = +evt.beta | 0;
  69306. }
  69307. if (evt.gamma !== null) {
  69308. this._gamma = +evt.gamma | 0;
  69309. }
  69310. this._dirty = true;
  69311. };
  69312. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  69313. if (this._dirty) {
  69314. this._dirty = false;
  69315. if (this._gamma < 0) {
  69316. this._gamma = 180 + this._gamma;
  69317. }
  69318. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  69319. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  69320. }
  69321. };
  69322. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  69323. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  69324. };
  69325. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  69326. return "ArcRotateCameraVRDeviceOrientationInput";
  69327. };
  69328. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  69329. return "VRDeviceOrientation";
  69330. };
  69331. return ArcRotateCameraVRDeviceOrientationInput;
  69332. }());
  69333. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  69334. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  69335. })(BABYLON || (BABYLON = {}));
  69336. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  69337. var BABYLON;
  69338. (function (BABYLON) {
  69339. var VRCameraMetrics = /** @class */ (function () {
  69340. function VRCameraMetrics() {
  69341. this.compensateDistortion = true;
  69342. }
  69343. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  69344. get: function () {
  69345. return this.hResolution / (2 * this.vResolution);
  69346. },
  69347. enumerable: true,
  69348. configurable: true
  69349. });
  69350. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69351. get: function () {
  69352. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69353. },
  69354. enumerable: true,
  69355. configurable: true
  69356. });
  69357. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69358. get: function () {
  69359. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69360. var h = (4 * meters) / this.hScreenSize;
  69361. return BABYLON.Matrix.Translation(h, 0, 0);
  69362. },
  69363. enumerable: true,
  69364. configurable: true
  69365. });
  69366. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69367. get: function () {
  69368. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69369. var h = (4 * meters) / this.hScreenSize;
  69370. return BABYLON.Matrix.Translation(-h, 0, 0);
  69371. },
  69372. enumerable: true,
  69373. configurable: true
  69374. });
  69375. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69376. get: function () {
  69377. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69378. },
  69379. enumerable: true,
  69380. configurable: true
  69381. });
  69382. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69383. get: function () {
  69384. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69385. },
  69386. enumerable: true,
  69387. configurable: true
  69388. });
  69389. VRCameraMetrics.GetDefault = function () {
  69390. var result = new VRCameraMetrics();
  69391. result.hResolution = 1280;
  69392. result.vResolution = 800;
  69393. result.hScreenSize = 0.149759993;
  69394. result.vScreenSize = 0.0935999975;
  69395. result.vScreenCenter = 0.0467999987;
  69396. result.eyeToScreenDistance = 0.0410000011;
  69397. result.lensSeparationDistance = 0.0635000020;
  69398. result.interpupillaryDistance = 0.0640000030;
  69399. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69400. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69401. result.postProcessScaleFactor = 1.714605507808412;
  69402. result.lensCenterOffset = 0.151976421;
  69403. return result;
  69404. };
  69405. return VRCameraMetrics;
  69406. }());
  69407. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69408. })(BABYLON || (BABYLON = {}));
  69409. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69410. var BABYLON;
  69411. (function (BABYLON) {
  69412. var WebVRFreeCamera = /** @class */ (function (_super) {
  69413. __extends(WebVRFreeCamera, _super);
  69414. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69415. if (webVROptions === void 0) { webVROptions = {}; }
  69416. var _this = _super.call(this, name, position, scene) || this;
  69417. _this.webVROptions = webVROptions;
  69418. _this._vrDevice = null;
  69419. _this.rawPose = null;
  69420. _this._specsVersion = "1.1";
  69421. _this._attached = false;
  69422. _this._descendants = [];
  69423. _this.devicePosition = BABYLON.Vector3.Zero();
  69424. _this.deviceScaleFactor = 1;
  69425. _this.controllers = [];
  69426. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69427. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69428. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69429. _this.minZ = 0.1;
  69430. //legacy support - the compensation boolean was removed.
  69431. if (arguments.length === 5) {
  69432. _this.webVROptions = arguments[4];
  69433. }
  69434. // default webVR options
  69435. if (_this.webVROptions.trackPosition == undefined) {
  69436. _this.webVROptions.trackPosition = true;
  69437. }
  69438. if (_this.webVROptions.controllerMeshes == undefined) {
  69439. _this.webVROptions.controllerMeshes = true;
  69440. }
  69441. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69442. _this.webVROptions.defaultLightingOnControllers = true;
  69443. }
  69444. _this.rotationQuaternion = new BABYLON.Quaternion();
  69445. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69446. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69447. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69448. }
  69449. //enable VR
  69450. var engine = _this.getEngine();
  69451. _this._onVREnabled = function (success) { if (success) {
  69452. _this.initControllers();
  69453. } };
  69454. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69455. engine.initWebVR().add(function (event) {
  69456. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69457. return;
  69458. }
  69459. _this._vrDevice = event.vrDisplay;
  69460. //reset the rig parameters.
  69461. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69462. if (_this._attached) {
  69463. _this.getEngine().enableVR();
  69464. }
  69465. });
  69466. if (typeof (VRFrameData) !== "undefined")
  69467. _this._frameData = new VRFrameData();
  69468. /**
  69469. * The idea behind the following lines:
  69470. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69471. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69472. * the second will not show it correctly.
  69473. *
  69474. * To solve this - each object that has the camera as parent will be added to a protected array.
  69475. * When the rig camera renders, it will take this array and set all of those to be its children.
  69476. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69477. * Amazing!
  69478. */
  69479. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69480. if (camera.parent === _this && _this.rigParenting) {
  69481. _this._descendants = _this.getDescendants(true, function (n) {
  69482. // don't take the cameras or the controllers!
  69483. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69484. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69485. return !isController && !isRigCamera;
  69486. });
  69487. _this._descendants.forEach(function (node) {
  69488. node.parent = camera;
  69489. });
  69490. }
  69491. });
  69492. scene.onAfterCameraRenderObservable.add(function (camera) {
  69493. if (camera.parent === _this && _this.rigParenting) {
  69494. _this._descendants.forEach(function (node) {
  69495. node.parent = _this;
  69496. });
  69497. }
  69498. });
  69499. return _this;
  69500. }
  69501. WebVRFreeCamera.prototype.dispose = function () {
  69502. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69503. _super.prototype.dispose.call(this);
  69504. };
  69505. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69506. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69507. var gp = _a[_i];
  69508. if (gp.hand === name) {
  69509. return gp;
  69510. }
  69511. }
  69512. return null;
  69513. };
  69514. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69515. get: function () {
  69516. if (!this._leftController) {
  69517. this._leftController = this.getControllerByName("left");
  69518. }
  69519. return this._leftController;
  69520. },
  69521. enumerable: true,
  69522. configurable: true
  69523. });
  69524. ;
  69525. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69526. get: function () {
  69527. if (!this._rightController) {
  69528. this._rightController = this.getControllerByName("right");
  69529. }
  69530. return this._rightController;
  69531. },
  69532. enumerable: true,
  69533. configurable: true
  69534. });
  69535. ;
  69536. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69537. if (length === void 0) { length = 100; }
  69538. if (this.leftCamera) {
  69539. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69540. }
  69541. else {
  69542. return _super.prototype.getForwardRay.call(this, length);
  69543. }
  69544. };
  69545. WebVRFreeCamera.prototype._checkInputs = function () {
  69546. if (this._vrDevice && this._vrDevice.isPresenting) {
  69547. this._vrDevice.getFrameData(this._frameData);
  69548. this.updateFromDevice(this._frameData.pose);
  69549. }
  69550. _super.prototype._checkInputs.call(this);
  69551. };
  69552. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69553. if (poseData && poseData.orientation) {
  69554. this.rawPose = poseData;
  69555. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69556. if (this.getScene().useRightHandedSystem) {
  69557. this.deviceRotationQuaternion.z *= -1;
  69558. this.deviceRotationQuaternion.w *= -1;
  69559. }
  69560. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69561. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69562. if (this.getScene().useRightHandedSystem) {
  69563. this.devicePosition.z *= -1;
  69564. }
  69565. }
  69566. }
  69567. };
  69568. /**
  69569. * WebVR's attach control will start broadcasting frames to the device.
  69570. * Note that in certain browsers (chrome for example) this function must be called
  69571. * within a user-interaction callback. Example:
  69572. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69573. *
  69574. * @param {HTMLElement} element
  69575. * @param {boolean} [noPreventDefault]
  69576. *
  69577. * @memberOf WebVRFreeCamera
  69578. */
  69579. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69580. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69581. this._attached = true;
  69582. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69583. if (this._vrDevice) {
  69584. this.getEngine().enableVR();
  69585. }
  69586. };
  69587. WebVRFreeCamera.prototype.detachControl = function (element) {
  69588. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69589. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69590. _super.prototype.detachControl.call(this, element);
  69591. this._attached = false;
  69592. this.getEngine().disableVR();
  69593. };
  69594. WebVRFreeCamera.prototype.getClassName = function () {
  69595. return "WebVRFreeCamera";
  69596. };
  69597. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69598. //uses the vrDisplay's "resetPose()".
  69599. //pitch and roll won't be affected.
  69600. this._vrDevice.resetPose();
  69601. };
  69602. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69603. var camLeft = this._rigCameras[0];
  69604. var camRight = this._rigCameras[1];
  69605. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69606. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69607. camLeft.position.copyFrom(this.devicePosition);
  69608. camRight.position.copyFrom(this.devicePosition);
  69609. };
  69610. /**
  69611. * This function is called by the two RIG cameras.
  69612. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69613. */
  69614. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69615. var _this = this;
  69616. //WebVR 1.1
  69617. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69618. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69619. if (!this.getScene().useRightHandedSystem) {
  69620. [2, 6, 8, 9, 14].forEach(function (num) {
  69621. _this._webvrViewMatrix.m[num] *= -1;
  69622. });
  69623. }
  69624. // update the camera rotation matrix
  69625. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69626. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69627. // Computing target and final matrix
  69628. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69629. var parentCamera = this._cameraRigParams["parentCamera"];
  69630. // should the view matrix be updated with scale and position offset?
  69631. if (parentCamera.deviceScaleFactor !== 1) {
  69632. this._webvrViewMatrix.invert();
  69633. // scale the position, if set
  69634. if (parentCamera.deviceScaleFactor) {
  69635. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69636. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69637. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69638. }
  69639. this._webvrViewMatrix.invert();
  69640. }
  69641. return this._webvrViewMatrix;
  69642. };
  69643. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69644. var _this = this;
  69645. var parentCamera = this.parent;
  69646. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69647. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69648. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69649. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69650. //babylon compatible matrix
  69651. if (!this.getScene().useRightHandedSystem) {
  69652. [8, 9, 10, 11].forEach(function (num) {
  69653. _this._projectionMatrix.m[num] *= -1;
  69654. });
  69655. }
  69656. return this._projectionMatrix;
  69657. };
  69658. WebVRFreeCamera.prototype.initControllers = function () {
  69659. var _this = this;
  69660. this.controllers = [];
  69661. var manager = this.getScene().gamepadManager;
  69662. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69663. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69664. var webVrController = gamepad;
  69665. if (webVrController.defaultModel) {
  69666. webVrController.defaultModel.setEnabled(false);
  69667. }
  69668. }
  69669. });
  69670. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69671. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69672. var webVrController_1 = gamepad;
  69673. if (_this.webVROptions.controllerMeshes) {
  69674. if (webVrController_1.defaultModel) {
  69675. webVrController_1.defaultModel.setEnabled(true);
  69676. }
  69677. else {
  69678. // Load the meshes
  69679. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69680. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69681. if (_this.webVROptions.defaultLightingOnControllers) {
  69682. if (!_this._lightOnControllers) {
  69683. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69684. }
  69685. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69686. var children = mesh.getChildren();
  69687. if (children.length !== 0) {
  69688. children.forEach(function (mesh) {
  69689. light.includedOnlyMeshes.push(mesh);
  69690. activateLightOnSubMeshes_1(mesh, light);
  69691. });
  69692. }
  69693. };
  69694. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69695. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69696. }
  69697. });
  69698. }
  69699. }
  69700. webVrController_1.attachToPoseControlledCamera(_this);
  69701. // since this is async - sanity check. Is the controller already stored?
  69702. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69703. //add to the controllers array
  69704. _this.controllers.push(webVrController_1);
  69705. //did we find enough controllers? Great! let the developer know.
  69706. if (_this.controllers.length >= 2) {
  69707. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69708. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69709. // So we're overriding setting left & right manually to be sure
  69710. var firstViveWandDetected = false;
  69711. for (var i = 0; i < _this.controllers.length; i++) {
  69712. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69713. if (!firstViveWandDetected) {
  69714. firstViveWandDetected = true;
  69715. _this.controllers[i].hand = "left";
  69716. }
  69717. else {
  69718. _this.controllers[i].hand = "right";
  69719. }
  69720. }
  69721. }
  69722. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69723. }
  69724. }
  69725. }
  69726. });
  69727. };
  69728. return WebVRFreeCamera;
  69729. }(BABYLON.FreeCamera));
  69730. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69731. })(BABYLON || (BABYLON = {}));
  69732. //# sourceMappingURL=babylon.webVRCamera.js.map
  69733. var BABYLON;
  69734. (function (BABYLON) {
  69735. // We're mainly based on the logic defined into the FreeCamera code
  69736. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69737. __extends(DeviceOrientationCamera, _super);
  69738. function DeviceOrientationCamera(name, position, scene) {
  69739. var _this = _super.call(this, name, position, scene) || this;
  69740. _this._quaternionCache = new BABYLON.Quaternion();
  69741. _this.inputs.addDeviceOrientation();
  69742. return _this;
  69743. }
  69744. DeviceOrientationCamera.prototype.getClassName = function () {
  69745. return "DeviceOrientationCamera";
  69746. };
  69747. DeviceOrientationCamera.prototype._checkInputs = function () {
  69748. _super.prototype._checkInputs.call(this);
  69749. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69750. if (this._initialQuaternion) {
  69751. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69752. }
  69753. };
  69754. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69755. var _this = this;
  69756. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69757. //can only work if this camera has a rotation quaternion already.
  69758. if (!this.rotationQuaternion)
  69759. return;
  69760. if (!this._initialQuaternion) {
  69761. this._initialQuaternion = new BABYLON.Quaternion();
  69762. }
  69763. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69764. ['x', 'y', 'z'].forEach(function (axisName) {
  69765. if (!axis[axisName]) {
  69766. _this._initialQuaternion[axisName] = 0;
  69767. }
  69768. else {
  69769. _this._initialQuaternion[axisName] *= -1;
  69770. }
  69771. });
  69772. this._initialQuaternion.normalize();
  69773. //force rotation update
  69774. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69775. };
  69776. return DeviceOrientationCamera;
  69777. }(BABYLON.FreeCamera));
  69778. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69779. })(BABYLON || (BABYLON = {}));
  69780. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69781. var BABYLON;
  69782. (function (BABYLON) {
  69783. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69784. __extends(VRDeviceOrientationFreeCamera, _super);
  69785. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69786. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69787. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69788. var _this = _super.call(this, name, position, scene) || this;
  69789. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69790. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69791. return _this;
  69792. }
  69793. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69794. return "VRDeviceOrientationFreeCamera";
  69795. };
  69796. return VRDeviceOrientationFreeCamera;
  69797. }(BABYLON.DeviceOrientationCamera));
  69798. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69799. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69800. __extends(VRDeviceOrientationGamepadCamera, _super);
  69801. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69802. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69803. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69804. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69805. _this.inputs.addGamepad();
  69806. return _this;
  69807. }
  69808. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69809. return "VRDeviceOrientationGamepadCamera";
  69810. };
  69811. return VRDeviceOrientationGamepadCamera;
  69812. }(VRDeviceOrientationFreeCamera));
  69813. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69814. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69815. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69816. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69817. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69818. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69819. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69820. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69821. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69822. _this.inputs.addVRDeviceOrientation();
  69823. return _this;
  69824. }
  69825. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69826. return "VRDeviceOrientationArcRotateCamera";
  69827. };
  69828. return VRDeviceOrientationArcRotateCamera;
  69829. }(BABYLON.ArcRotateCamera));
  69830. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69831. })(BABYLON || (BABYLON = {}));
  69832. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69833. var BABYLON;
  69834. (function (BABYLON) {
  69835. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69836. __extends(AnaglyphFreeCamera, _super);
  69837. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69838. var _this = _super.call(this, name, position, scene) || this;
  69839. _this.interaxialDistance = interaxialDistance;
  69840. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69841. return _this;
  69842. }
  69843. AnaglyphFreeCamera.prototype.getClassName = function () {
  69844. return "AnaglyphFreeCamera";
  69845. };
  69846. return AnaglyphFreeCamera;
  69847. }(BABYLON.FreeCamera));
  69848. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  69849. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  69850. __extends(AnaglyphArcRotateCamera, _super);
  69851. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  69852. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69853. _this.interaxialDistance = interaxialDistance;
  69854. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69855. return _this;
  69856. }
  69857. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  69858. return "AnaglyphArcRotateCamera";
  69859. };
  69860. return AnaglyphArcRotateCamera;
  69861. }(BABYLON.ArcRotateCamera));
  69862. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  69863. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  69864. __extends(AnaglyphGamepadCamera, _super);
  69865. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  69866. var _this = _super.call(this, name, position, scene) || this;
  69867. _this.interaxialDistance = interaxialDistance;
  69868. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69869. return _this;
  69870. }
  69871. AnaglyphGamepadCamera.prototype.getClassName = function () {
  69872. return "AnaglyphGamepadCamera";
  69873. };
  69874. return AnaglyphGamepadCamera;
  69875. }(BABYLON.GamepadCamera));
  69876. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  69877. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  69878. __extends(AnaglyphUniversalCamera, _super);
  69879. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  69880. var _this = _super.call(this, name, position, scene) || this;
  69881. _this.interaxialDistance = interaxialDistance;
  69882. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69883. return _this;
  69884. }
  69885. AnaglyphUniversalCamera.prototype.getClassName = function () {
  69886. return "AnaglyphUniversalCamera";
  69887. };
  69888. return AnaglyphUniversalCamera;
  69889. }(BABYLON.UniversalCamera));
  69890. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  69891. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  69892. __extends(StereoscopicFreeCamera, _super);
  69893. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69894. var _this = _super.call(this, name, position, scene) || this;
  69895. _this.interaxialDistance = interaxialDistance;
  69896. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69897. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69898. return _this;
  69899. }
  69900. StereoscopicFreeCamera.prototype.getClassName = function () {
  69901. return "StereoscopicFreeCamera";
  69902. };
  69903. return StereoscopicFreeCamera;
  69904. }(BABYLON.FreeCamera));
  69905. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  69906. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  69907. __extends(StereoscopicArcRotateCamera, _super);
  69908. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  69909. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69910. _this.interaxialDistance = interaxialDistance;
  69911. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69912. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69913. return _this;
  69914. }
  69915. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  69916. return "StereoscopicArcRotateCamera";
  69917. };
  69918. return StereoscopicArcRotateCamera;
  69919. }(BABYLON.ArcRotateCamera));
  69920. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  69921. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  69922. __extends(StereoscopicGamepadCamera, _super);
  69923. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69924. var _this = _super.call(this, name, position, scene) || this;
  69925. _this.interaxialDistance = interaxialDistance;
  69926. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69927. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69928. return _this;
  69929. }
  69930. StereoscopicGamepadCamera.prototype.getClassName = function () {
  69931. return "StereoscopicGamepadCamera";
  69932. };
  69933. return StereoscopicGamepadCamera;
  69934. }(BABYLON.GamepadCamera));
  69935. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  69936. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  69937. __extends(StereoscopicUniversalCamera, _super);
  69938. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69939. var _this = _super.call(this, name, position, scene) || this;
  69940. _this.interaxialDistance = interaxialDistance;
  69941. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69942. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69943. return _this;
  69944. }
  69945. StereoscopicUniversalCamera.prototype.getClassName = function () {
  69946. return "StereoscopicUniversalCamera";
  69947. };
  69948. return StereoscopicUniversalCamera;
  69949. }(BABYLON.UniversalCamera));
  69950. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  69951. })(BABYLON || (BABYLON = {}));
  69952. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  69953. var BABYLON;
  69954. (function (BABYLON) {
  69955. var VRExperienceHelper = /** @class */ (function () {
  69956. function VRExperienceHelper(scene, webVROptions) {
  69957. if (webVROptions === void 0) { webVROptions = {}; }
  69958. var _this = this;
  69959. this.webVROptions = webVROptions;
  69960. // Can the system support WebVR, even if a headset isn't plugged in?
  69961. this._webVRsupported = false;
  69962. // If WebVR is supported, is a headset plugged in and are we ready to present?
  69963. this._webVRready = false;
  69964. // Are we waiting for the requestPresent callback to complete?
  69965. this._webVRrequesting = false;
  69966. // Are we presenting to the headset right now?
  69967. this._webVRpresenting = false;
  69968. // Are we presenting in the fullscreen fallback?
  69969. this._fullscreenVRpresenting = false;
  69970. this._scene = scene;
  69971. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  69972. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  69973. }
  69974. else {
  69975. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  69976. if (scene.activeCamera.rotation) {
  69977. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  69978. }
  69979. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  69980. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  69981. }
  69982. this._scene.activeCamera = this._deviceOrientationCamera;
  69983. this._position = this._scene.activeCamera.position;
  69984. this._canvas = scene.getEngine().getRenderingCanvas();
  69985. if (this._canvas) {
  69986. this._scene.activeCamera.attachControl(this._canvas);
  69987. }
  69988. this._btnVR = document.createElement("BUTTON");
  69989. this._btnVR.className = "babylonVRicon";
  69990. this._btnVR.id = "babylonVRiconbtn";
  69991. this._btnVR.title = "Click to switch to VR";
  69992. 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) }";
  69993. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  69994. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  69995. // css += ".babylonVRicon.vrdisplaysupported { }";
  69996. // css += ".babylonVRicon.vrdisplayready { }";
  69997. // css += ".babylonVRicon.vrdisplayrequesting { }";
  69998. var style = document.createElement('style');
  69999. style.appendChild(document.createTextNode(css));
  70000. document.getElementsByTagName('head')[0].appendChild(style);
  70001. if (this._canvas) {
  70002. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70003. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70004. this._btnVR.addEventListener("click", function () {
  70005. _this.enterVR();
  70006. });
  70007. window.addEventListener("resize", function () {
  70008. if (_this._canvas) {
  70009. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  70010. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  70011. }
  70012. if (_this._fullscreenVRpresenting && _this._webVRready) {
  70013. _this.exitVR();
  70014. }
  70015. });
  70016. }
  70017. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70018. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70019. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70020. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70021. document.body.appendChild(this._btnVR);
  70022. // Exiting VR mode using 'ESC' key on desktop
  70023. this._onKeyDown = function (event) {
  70024. if (event.keyCode === 27 && _this.isInVRMode()) {
  70025. _this.exitVR();
  70026. }
  70027. };
  70028. document.addEventListener("keydown", this._onKeyDown);
  70029. // Exiting VR mode double tapping the touch screen
  70030. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  70031. if (_this.isInVRMode()) {
  70032. _this.exitVR();
  70033. if (_this._fullscreenVRpresenting) {
  70034. _this._scene.getEngine().switchFullscreen(true);
  70035. }
  70036. }
  70037. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  70038. // Listen for WebVR display changes
  70039. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  70040. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  70041. this._onVRRequestPresentStart = function () {
  70042. _this._webVRrequesting = true;
  70043. _this.updateButtonVisibility();
  70044. };
  70045. this._onVRRequestPresentComplete = function (success) {
  70046. _this._webVRrequesting = false;
  70047. _this.updateButtonVisibility();
  70048. };
  70049. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  70050. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  70051. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  70052. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70053. // Create the cameras
  70054. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  70055. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  70056. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  70057. this.updateButtonVisibility();
  70058. }
  70059. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  70060. if (this.onControllerMeshLoaded) {
  70061. this.onControllerMeshLoaded(webVRController);
  70062. }
  70063. };
  70064. VRExperienceHelper.prototype._onFullscreenChange = function () {
  70065. if (document.fullscreen !== undefined) {
  70066. this._fullscreenVRpresenting = document.fullscreen;
  70067. }
  70068. else if (document.mozFullScreen !== undefined) {
  70069. this._fullscreenVRpresenting = document.mozFullScreen;
  70070. }
  70071. else if (document.webkitIsFullScreen !== undefined) {
  70072. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  70073. }
  70074. else if (document.msIsFullScreen !== undefined) {
  70075. this._fullscreenVRpresenting = document.msIsFullScreen;
  70076. }
  70077. if (!this._fullscreenVRpresenting && this._canvas) {
  70078. this.exitVR();
  70079. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70080. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70081. }
  70082. };
  70083. VRExperienceHelper.prototype.isInVRMode = function () {
  70084. return this._webVRpresenting || this._fullscreenVRpresenting;
  70085. };
  70086. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  70087. var vrDisplay = this._scene.getEngine().getVRDevice();
  70088. if (vrDisplay) {
  70089. var wasPresenting = this._webVRpresenting;
  70090. // A VR display is connected
  70091. this._webVRpresenting = vrDisplay.isPresenting;
  70092. if (wasPresenting && !this._webVRpresenting)
  70093. this.exitVR();
  70094. }
  70095. else {
  70096. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  70097. }
  70098. this.updateButtonVisibility();
  70099. };
  70100. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  70101. this._webVRsupported = eventArgs.vrSupported;
  70102. this._webVRready = !!eventArgs.vrDisplay;
  70103. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  70104. this.updateButtonVisibility();
  70105. };
  70106. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  70107. if (!this._btnVR) {
  70108. return;
  70109. }
  70110. this._btnVR.className = "babylonVRicon";
  70111. if (this.isInVRMode()) {
  70112. this._btnVR.className += " vrdisplaypresenting";
  70113. }
  70114. else {
  70115. if (this._webVRready)
  70116. this._btnVR.className += " vrdisplayready";
  70117. if (this._webVRsupported)
  70118. this._btnVR.className += " vrdisplaysupported";
  70119. if (this._webVRrequesting)
  70120. this._btnVR.className += " vrdisplayrequesting";
  70121. }
  70122. };
  70123. /**
  70124. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  70125. * Otherwise, will use the fullscreen API.
  70126. */
  70127. VRExperienceHelper.prototype.enterVR = function () {
  70128. if (this.onEnteringVR) {
  70129. this.onEnteringVR();
  70130. }
  70131. if (this._webVRrequesting)
  70132. return;
  70133. // If WebVR is supported and a headset is connected
  70134. if (this._webVRready) {
  70135. if (!this._webVRpresenting) {
  70136. this._webVRCamera.position = this._position;
  70137. this._scene.activeCamera = this._webVRCamera;
  70138. }
  70139. }
  70140. else {
  70141. this._vrDeviceOrientationCamera.position = this._position;
  70142. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  70143. this._scene.getEngine().switchFullscreen(true);
  70144. this.updateButtonVisibility();
  70145. }
  70146. if (this._scene.activeCamera && this._canvas) {
  70147. this._scene.activeCamera.attachControl(this._canvas);
  70148. }
  70149. };
  70150. /**
  70151. * Attempt to exit VR, or fullscreen.
  70152. */
  70153. VRExperienceHelper.prototype.exitVR = function () {
  70154. if (this.onExitingVR) {
  70155. this.onExitingVR();
  70156. }
  70157. if (this._webVRpresenting) {
  70158. this._scene.getEngine().disableVR();
  70159. }
  70160. if (this._scene.activeCamera) {
  70161. this._position = this._scene.activeCamera.position;
  70162. }
  70163. this._deviceOrientationCamera.position = this._position;
  70164. this._scene.activeCamera = this._deviceOrientationCamera;
  70165. if (this._canvas) {
  70166. this._scene.activeCamera.attachControl(this._canvas);
  70167. }
  70168. this.updateButtonVisibility();
  70169. };
  70170. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  70171. get: function () {
  70172. return this._position;
  70173. },
  70174. set: function (value) {
  70175. this._position = value;
  70176. if (this._scene.activeCamera) {
  70177. this._scene.activeCamera.position = value;
  70178. }
  70179. },
  70180. enumerable: true,
  70181. configurable: true
  70182. });
  70183. VRExperienceHelper.prototype.dispose = function () {
  70184. if (this.isInVRMode()) {
  70185. this.exitVR();
  70186. }
  70187. this._deviceOrientationCamera.dispose();
  70188. if (this._webVRCamera) {
  70189. this._webVRCamera.dispose();
  70190. }
  70191. if (this._vrDeviceOrientationCamera) {
  70192. this._vrDeviceOrientationCamera.dispose();
  70193. }
  70194. document.body.removeChild(this._btnVR);
  70195. document.removeEventListener("keydown", this._onKeyDown);
  70196. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70197. };
  70198. VRExperienceHelper.prototype.getClassName = function () {
  70199. return "VRExperienceHelper";
  70200. };
  70201. return VRExperienceHelper;
  70202. }());
  70203. BABYLON.VRExperienceHelper = VRExperienceHelper;
  70204. })(BABYLON || (BABYLON = {}));
  70205. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  70206. // Mainly based on these 2 articles :
  70207. // 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
  70208. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  70209. var BABYLON;
  70210. (function (BABYLON) {
  70211. var JoystickAxis;
  70212. (function (JoystickAxis) {
  70213. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  70214. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  70215. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  70216. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  70217. var VirtualJoystick = /** @class */ (function () {
  70218. function VirtualJoystick(leftJoystick) {
  70219. var _this = this;
  70220. if (leftJoystick) {
  70221. this._leftJoystick = true;
  70222. }
  70223. else {
  70224. this._leftJoystick = false;
  70225. }
  70226. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  70227. VirtualJoystick._globalJoystickIndex++;
  70228. // By default left & right arrow keys are moving the X
  70229. // and up & down keys are moving the Y
  70230. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70231. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70232. this.reverseLeftRight = false;
  70233. this.reverseUpDown = false;
  70234. // collections of pointers
  70235. this._touches = new BABYLON.StringDictionary();
  70236. this.deltaPosition = BABYLON.Vector3.Zero();
  70237. this._joystickSensibility = 25;
  70238. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70239. this._rotationSpeed = 25;
  70240. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  70241. this._rotateOnAxisRelativeToMesh = false;
  70242. this._onResize = function (evt) {
  70243. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70244. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70245. if (VirtualJoystick.vjCanvas) {
  70246. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  70247. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  70248. }
  70249. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  70250. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  70251. };
  70252. // injecting a canvas element on top of the canvas 3D game
  70253. if (!VirtualJoystick.vjCanvas) {
  70254. window.addEventListener("resize", this._onResize, false);
  70255. VirtualJoystick.vjCanvas = document.createElement("canvas");
  70256. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70257. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70258. VirtualJoystick.vjCanvas.width = window.innerWidth;
  70259. VirtualJoystick.vjCanvas.height = window.innerHeight;
  70260. VirtualJoystick.vjCanvas.style.width = "100%";
  70261. VirtualJoystick.vjCanvas.style.height = "100%";
  70262. VirtualJoystick.vjCanvas.style.position = "absolute";
  70263. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  70264. VirtualJoystick.vjCanvas.style.top = "0px";
  70265. VirtualJoystick.vjCanvas.style.left = "0px";
  70266. VirtualJoystick.vjCanvas.style.zIndex = "5";
  70267. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  70268. // Support for jQuery PEP polyfill
  70269. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  70270. var context = VirtualJoystick.vjCanvas.getContext('2d');
  70271. if (!context) {
  70272. throw new Error("Unable to create canvas for virtual joystick");
  70273. }
  70274. VirtualJoystick.vjCanvasContext = context;
  70275. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  70276. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70277. document.body.appendChild(VirtualJoystick.vjCanvas);
  70278. }
  70279. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  70280. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  70281. this.pressed = false;
  70282. // default joystick color
  70283. this._joystickColor = "cyan";
  70284. this._joystickPointerID = -1;
  70285. // current joystick position
  70286. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  70287. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  70288. // origin joystick position
  70289. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  70290. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  70291. this._onPointerDownHandlerRef = function (evt) {
  70292. _this._onPointerDown(evt);
  70293. };
  70294. this._onPointerMoveHandlerRef = function (evt) {
  70295. _this._onPointerMove(evt);
  70296. };
  70297. this._onPointerOutHandlerRef = function (evt) {
  70298. _this._onPointerUp(evt);
  70299. };
  70300. this._onPointerUpHandlerRef = function (evt) {
  70301. _this._onPointerUp(evt);
  70302. };
  70303. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  70304. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  70305. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  70306. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  70307. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  70308. evt.preventDefault(); // Disables system menu
  70309. }, false);
  70310. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70311. }
  70312. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  70313. this._joystickSensibility = newJoystickSensibility;
  70314. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70315. };
  70316. VirtualJoystick.prototype._onPointerDown = function (e) {
  70317. var positionOnScreenCondition;
  70318. e.preventDefault();
  70319. if (this._leftJoystick === true) {
  70320. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  70321. }
  70322. else {
  70323. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  70324. }
  70325. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  70326. // First contact will be dedicated to the virtual joystick
  70327. this._joystickPointerID = e.pointerId;
  70328. this._joystickPointerStartPos.x = e.clientX;
  70329. this._joystickPointerStartPos.y = e.clientY;
  70330. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  70331. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  70332. this._deltaJoystickVector.x = 0;
  70333. this._deltaJoystickVector.y = 0;
  70334. this.pressed = true;
  70335. this._touches.add(e.pointerId.toString(), e);
  70336. }
  70337. else {
  70338. // You can only trigger the action buttons with a joystick declared
  70339. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  70340. this._action();
  70341. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  70342. }
  70343. }
  70344. };
  70345. VirtualJoystick.prototype._onPointerMove = function (e) {
  70346. // If the current pointer is the one associated to the joystick (first touch contact)
  70347. if (this._joystickPointerID == e.pointerId) {
  70348. this._joystickPointerPos.x = e.clientX;
  70349. this._joystickPointerPos.y = e.clientY;
  70350. this._deltaJoystickVector = this._joystickPointerPos.clone();
  70351. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  70352. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  70353. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  70354. switch (this._axisTargetedByLeftAndRight) {
  70355. case JoystickAxis.X:
  70356. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70357. break;
  70358. case JoystickAxis.Y:
  70359. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70360. break;
  70361. case JoystickAxis.Z:
  70362. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70363. break;
  70364. }
  70365. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70366. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70367. switch (this._axisTargetedByUpAndDown) {
  70368. case JoystickAxis.X:
  70369. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70370. break;
  70371. case JoystickAxis.Y:
  70372. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70373. break;
  70374. case JoystickAxis.Z:
  70375. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70376. break;
  70377. }
  70378. }
  70379. else {
  70380. var data = this._touches.get(e.pointerId.toString());
  70381. if (data) {
  70382. data.x = e.clientX;
  70383. data.y = e.clientY;
  70384. }
  70385. }
  70386. };
  70387. VirtualJoystick.prototype._onPointerUp = function (e) {
  70388. if (this._joystickPointerID == e.pointerId) {
  70389. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70390. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70391. this._joystickPointerID = -1;
  70392. this.pressed = false;
  70393. }
  70394. else {
  70395. var touch = this._touches.get(e.pointerId.toString());
  70396. if (touch) {
  70397. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70398. }
  70399. }
  70400. this._deltaJoystickVector.x = 0;
  70401. this._deltaJoystickVector.y = 0;
  70402. this._touches.remove(e.pointerId.toString());
  70403. };
  70404. /**
  70405. * Change the color of the virtual joystick
  70406. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70407. */
  70408. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70409. this._joystickColor = newColor;
  70410. };
  70411. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70412. this._action = action;
  70413. };
  70414. // Define which axis you'd like to control for left & right
  70415. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70416. switch (axis) {
  70417. case JoystickAxis.X:
  70418. case JoystickAxis.Y:
  70419. case JoystickAxis.Z:
  70420. this._axisTargetedByLeftAndRight = axis;
  70421. break;
  70422. default:
  70423. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70424. break;
  70425. }
  70426. };
  70427. // Define which axis you'd like to control for up & down
  70428. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70429. switch (axis) {
  70430. case JoystickAxis.X:
  70431. case JoystickAxis.Y:
  70432. case JoystickAxis.Z:
  70433. this._axisTargetedByUpAndDown = axis;
  70434. break;
  70435. default:
  70436. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70437. break;
  70438. }
  70439. };
  70440. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70441. var _this = this;
  70442. if (this.pressed) {
  70443. this._touches.forEach(function (key, touch) {
  70444. if (touch.pointerId === _this._joystickPointerID) {
  70445. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70446. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70447. VirtualJoystick.vjCanvasContext.beginPath();
  70448. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70449. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70450. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70451. VirtualJoystick.vjCanvasContext.stroke();
  70452. VirtualJoystick.vjCanvasContext.closePath();
  70453. VirtualJoystick.vjCanvasContext.beginPath();
  70454. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70455. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70456. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70457. VirtualJoystick.vjCanvasContext.stroke();
  70458. VirtualJoystick.vjCanvasContext.closePath();
  70459. VirtualJoystick.vjCanvasContext.beginPath();
  70460. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70461. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70462. VirtualJoystick.vjCanvasContext.stroke();
  70463. VirtualJoystick.vjCanvasContext.closePath();
  70464. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70465. }
  70466. else {
  70467. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70468. VirtualJoystick.vjCanvasContext.beginPath();
  70469. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70470. VirtualJoystick.vjCanvasContext.beginPath();
  70471. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70472. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70473. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70474. VirtualJoystick.vjCanvasContext.stroke();
  70475. VirtualJoystick.vjCanvasContext.closePath();
  70476. touch.prevX = touch.x;
  70477. touch.prevY = touch.y;
  70478. }
  70479. ;
  70480. });
  70481. }
  70482. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70483. };
  70484. VirtualJoystick.prototype.releaseCanvas = function () {
  70485. if (VirtualJoystick.vjCanvas) {
  70486. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70487. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70488. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70489. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70490. window.removeEventListener("resize", this._onResize);
  70491. document.body.removeChild(VirtualJoystick.vjCanvas);
  70492. VirtualJoystick.vjCanvas = null;
  70493. }
  70494. };
  70495. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70496. VirtualJoystick._globalJoystickIndex = 0;
  70497. return VirtualJoystick;
  70498. }());
  70499. BABYLON.VirtualJoystick = VirtualJoystick;
  70500. })(BABYLON || (BABYLON = {}));
  70501. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70502. var BABYLON;
  70503. (function (BABYLON) {
  70504. // We're mainly based on the logic defined into the FreeCamera code
  70505. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70506. __extends(VirtualJoysticksCamera, _super);
  70507. function VirtualJoysticksCamera(name, position, scene) {
  70508. var _this = _super.call(this, name, position, scene) || this;
  70509. _this.inputs.addVirtualJoystick();
  70510. return _this;
  70511. }
  70512. VirtualJoysticksCamera.prototype.getClassName = function () {
  70513. return "VirtualJoysticksCamera";
  70514. };
  70515. return VirtualJoysticksCamera;
  70516. }(BABYLON.FreeCamera));
  70517. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70518. })(BABYLON || (BABYLON = {}));
  70519. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70520. var BABYLON;
  70521. (function (BABYLON) {
  70522. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70523. function FreeCameraVirtualJoystickInput() {
  70524. }
  70525. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70526. return this._leftjoystick;
  70527. };
  70528. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70529. return this._rightjoystick;
  70530. };
  70531. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70532. if (this._leftjoystick) {
  70533. var camera = this.camera;
  70534. var speed = camera._computeLocalCameraSpeed() * 50;
  70535. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70536. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70537. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70538. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70539. if (!this._leftjoystick.pressed) {
  70540. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70541. }
  70542. if (!this._rightjoystick.pressed) {
  70543. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70544. }
  70545. }
  70546. };
  70547. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70548. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70549. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70550. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70551. this._leftjoystick.setJoystickSensibility(0.15);
  70552. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70553. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70554. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70555. this._rightjoystick.reverseUpDown = true;
  70556. this._rightjoystick.setJoystickSensibility(0.05);
  70557. this._rightjoystick.setJoystickColor("yellow");
  70558. };
  70559. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70560. this._leftjoystick.releaseCanvas();
  70561. this._rightjoystick.releaseCanvas();
  70562. };
  70563. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70564. return "FreeCameraVirtualJoystickInput";
  70565. };
  70566. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70567. return "virtualJoystick";
  70568. };
  70569. return FreeCameraVirtualJoystickInput;
  70570. }());
  70571. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70572. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70573. })(BABYLON || (BABYLON = {}));
  70574. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70575. var BABYLON;
  70576. (function (BABYLON) {
  70577. var SimplificationSettings = /** @class */ (function () {
  70578. function SimplificationSettings(quality, distance, optimizeMesh) {
  70579. this.quality = quality;
  70580. this.distance = distance;
  70581. this.optimizeMesh = optimizeMesh;
  70582. }
  70583. return SimplificationSettings;
  70584. }());
  70585. BABYLON.SimplificationSettings = SimplificationSettings;
  70586. var SimplificationQueue = /** @class */ (function () {
  70587. function SimplificationQueue() {
  70588. this.running = false;
  70589. this._simplificationArray = [];
  70590. }
  70591. SimplificationQueue.prototype.addTask = function (task) {
  70592. this._simplificationArray.push(task);
  70593. };
  70594. SimplificationQueue.prototype.executeNext = function () {
  70595. var task = this._simplificationArray.pop();
  70596. if (task) {
  70597. this.running = true;
  70598. this.runSimplification(task);
  70599. }
  70600. else {
  70601. this.running = false;
  70602. }
  70603. };
  70604. SimplificationQueue.prototype.runSimplification = function (task) {
  70605. var _this = this;
  70606. if (task.parallelProcessing) {
  70607. //parallel simplifier
  70608. task.settings.forEach(function (setting) {
  70609. var simplifier = _this.getSimplifier(task);
  70610. simplifier.simplify(setting, function (newMesh) {
  70611. task.mesh.addLODLevel(setting.distance, newMesh);
  70612. newMesh.isVisible = true;
  70613. //check if it is the last
  70614. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70615. //all done, run the success callback.
  70616. task.successCallback();
  70617. }
  70618. _this.executeNext();
  70619. });
  70620. });
  70621. }
  70622. else {
  70623. //single simplifier.
  70624. var simplifier = this.getSimplifier(task);
  70625. var runDecimation = function (setting, callback) {
  70626. simplifier.simplify(setting, function (newMesh) {
  70627. task.mesh.addLODLevel(setting.distance, newMesh);
  70628. newMesh.isVisible = true;
  70629. //run the next quality level
  70630. callback();
  70631. });
  70632. };
  70633. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70634. runDecimation(task.settings[loop.index], function () {
  70635. loop.executeNext();
  70636. });
  70637. }, function () {
  70638. //execution ended, run the success callback.
  70639. if (task.successCallback) {
  70640. task.successCallback();
  70641. }
  70642. _this.executeNext();
  70643. });
  70644. }
  70645. };
  70646. SimplificationQueue.prototype.getSimplifier = function (task) {
  70647. switch (task.simplificationType) {
  70648. case SimplificationType.QUADRATIC:
  70649. default:
  70650. return new QuadraticErrorSimplification(task.mesh);
  70651. }
  70652. };
  70653. return SimplificationQueue;
  70654. }());
  70655. BABYLON.SimplificationQueue = SimplificationQueue;
  70656. /**
  70657. * The implemented types of simplification.
  70658. * At the moment only Quadratic Error Decimation is implemented.
  70659. */
  70660. var SimplificationType;
  70661. (function (SimplificationType) {
  70662. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70663. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70664. var DecimationTriangle = /** @class */ (function () {
  70665. function DecimationTriangle(vertices) {
  70666. this.vertices = vertices;
  70667. this.error = new Array(4);
  70668. this.deleted = false;
  70669. this.isDirty = false;
  70670. this.deletePending = false;
  70671. this.borderFactor = 0;
  70672. }
  70673. return DecimationTriangle;
  70674. }());
  70675. BABYLON.DecimationTriangle = DecimationTriangle;
  70676. var DecimationVertex = /** @class */ (function () {
  70677. function DecimationVertex(position, id) {
  70678. this.position = position;
  70679. this.id = id;
  70680. this.isBorder = true;
  70681. this.q = new QuadraticMatrix();
  70682. this.triangleCount = 0;
  70683. this.triangleStart = 0;
  70684. this.originalOffsets = [];
  70685. }
  70686. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70687. this.position.copyFrom(newPosition);
  70688. };
  70689. return DecimationVertex;
  70690. }());
  70691. BABYLON.DecimationVertex = DecimationVertex;
  70692. var QuadraticMatrix = /** @class */ (function () {
  70693. function QuadraticMatrix(data) {
  70694. this.data = new Array(10);
  70695. for (var i = 0; i < 10; ++i) {
  70696. if (data && data[i]) {
  70697. this.data[i] = data[i];
  70698. }
  70699. else {
  70700. this.data[i] = 0;
  70701. }
  70702. }
  70703. }
  70704. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70705. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70706. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70707. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70708. return det;
  70709. };
  70710. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70711. for (var i = 0; i < 10; ++i) {
  70712. this.data[i] += matrix.data[i];
  70713. }
  70714. };
  70715. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70716. for (var i = 0; i < 10; ++i) {
  70717. this.data[i] += data[i];
  70718. }
  70719. };
  70720. QuadraticMatrix.prototype.add = function (matrix) {
  70721. var m = new QuadraticMatrix();
  70722. for (var i = 0; i < 10; ++i) {
  70723. m.data[i] = this.data[i] + matrix.data[i];
  70724. }
  70725. return m;
  70726. };
  70727. QuadraticMatrix.FromData = function (a, b, c, d) {
  70728. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70729. };
  70730. //returning an array to avoid garbage collection
  70731. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70732. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70733. };
  70734. return QuadraticMatrix;
  70735. }());
  70736. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70737. var Reference = /** @class */ (function () {
  70738. function Reference(vertexId, triangleId) {
  70739. this.vertexId = vertexId;
  70740. this.triangleId = triangleId;
  70741. }
  70742. return Reference;
  70743. }());
  70744. BABYLON.Reference = Reference;
  70745. /**
  70746. * An implementation of the Quadratic Error simplification algorithm.
  70747. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70748. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70749. * @author RaananW
  70750. */
  70751. var QuadraticErrorSimplification = /** @class */ (function () {
  70752. function QuadraticErrorSimplification(_mesh) {
  70753. this._mesh = _mesh;
  70754. this.initialized = false;
  70755. this.syncIterations = 5000;
  70756. this.aggressiveness = 7;
  70757. this.decimationIterations = 100;
  70758. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70759. }
  70760. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70761. var _this = this;
  70762. this.initDecimatedMesh();
  70763. //iterating through the submeshes array, one after the other.
  70764. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70765. _this.initWithMesh(loop.index, function () {
  70766. _this.runDecimation(settings, loop.index, function () {
  70767. loop.executeNext();
  70768. });
  70769. }, settings.optimizeMesh);
  70770. }, function () {
  70771. setTimeout(function () {
  70772. successCallback(_this._reconstructedMesh);
  70773. }, 0);
  70774. });
  70775. };
  70776. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70777. var _this = this;
  70778. var targetCount = ~~(this.triangles.length * settings.quality);
  70779. var deletedTriangles = 0;
  70780. var triangleCount = this.triangles.length;
  70781. var iterationFunction = function (iteration, callback) {
  70782. setTimeout(function () {
  70783. if (iteration % 5 === 0) {
  70784. _this.updateMesh(iteration === 0);
  70785. }
  70786. for (var i = 0; i < _this.triangles.length; ++i) {
  70787. _this.triangles[i].isDirty = false;
  70788. }
  70789. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70790. var trianglesIterator = function (i) {
  70791. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70792. var t = _this.triangles[tIdx];
  70793. if (!t)
  70794. return;
  70795. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70796. return;
  70797. }
  70798. for (var j = 0; j < 3; ++j) {
  70799. if (t.error[j] < threshold) {
  70800. var deleted0 = [];
  70801. var deleted1 = [];
  70802. var v0 = t.vertices[j];
  70803. var v1 = t.vertices[(j + 1) % 3];
  70804. if (v0.isBorder || v1.isBorder)
  70805. continue;
  70806. var p = BABYLON.Vector3.Zero();
  70807. var n = BABYLON.Vector3.Zero();
  70808. var uv = BABYLON.Vector2.Zero();
  70809. var color = new BABYLON.Color4(0, 0, 0, 1);
  70810. _this.calculateError(v0, v1, p, n, uv, color);
  70811. var delTr = new Array();
  70812. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70813. continue;
  70814. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70815. continue;
  70816. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70817. continue;
  70818. var uniqueArray = new Array();
  70819. delTr.forEach(function (deletedT) {
  70820. if (uniqueArray.indexOf(deletedT) === -1) {
  70821. deletedT.deletePending = true;
  70822. uniqueArray.push(deletedT);
  70823. }
  70824. });
  70825. if (uniqueArray.length % 2 !== 0) {
  70826. continue;
  70827. }
  70828. v0.q = v1.q.add(v0.q);
  70829. v0.updatePosition(p);
  70830. var tStart = _this.references.length;
  70831. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70832. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70833. var tCount = _this.references.length - tStart;
  70834. if (tCount <= v0.triangleCount) {
  70835. if (tCount) {
  70836. for (var c = 0; c < tCount; c++) {
  70837. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70838. }
  70839. }
  70840. }
  70841. else {
  70842. v0.triangleStart = tStart;
  70843. }
  70844. v0.triangleCount = tCount;
  70845. break;
  70846. }
  70847. }
  70848. };
  70849. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  70850. }, 0);
  70851. };
  70852. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  70853. if (triangleCount - deletedTriangles <= targetCount)
  70854. loop.breakLoop();
  70855. else {
  70856. iterationFunction(loop.index, function () {
  70857. loop.executeNext();
  70858. });
  70859. }
  70860. }, function () {
  70861. setTimeout(function () {
  70862. //reconstruct this part of the mesh
  70863. _this.reconstructMesh(submeshIndex);
  70864. successCallback();
  70865. }, 0);
  70866. });
  70867. };
  70868. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  70869. var _this = this;
  70870. this.vertices = [];
  70871. this.triangles = [];
  70872. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70873. var indices = this._mesh.getIndices();
  70874. var submesh = this._mesh.subMeshes[submeshIndex];
  70875. var findInVertices = function (positionToSearch) {
  70876. if (optimizeMesh) {
  70877. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  70878. if (_this.vertices[ii].position.equals(positionToSearch)) {
  70879. return _this.vertices[ii];
  70880. }
  70881. }
  70882. }
  70883. return null;
  70884. };
  70885. var vertexReferences = [];
  70886. var vertexInit = function (i) {
  70887. if (!positionData) {
  70888. return;
  70889. }
  70890. var offset = i + submesh.verticesStart;
  70891. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  70892. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  70893. vertex.originalOffsets.push(offset);
  70894. if (vertex.id === _this.vertices.length) {
  70895. _this.vertices.push(vertex);
  70896. }
  70897. vertexReferences.push(vertex.id);
  70898. };
  70899. //var totalVertices = mesh.getTotalVertices();
  70900. var totalVertices = submesh.verticesCount;
  70901. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  70902. var indicesInit = function (i) {
  70903. if (!indices) {
  70904. return;
  70905. }
  70906. var offset = (submesh.indexStart / 3) + i;
  70907. var pos = (offset * 3);
  70908. var i0 = indices[pos + 0];
  70909. var i1 = indices[pos + 1];
  70910. var i2 = indices[pos + 2];
  70911. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  70912. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  70913. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  70914. var triangle = new DecimationTriangle([v0, v1, v2]);
  70915. triangle.originalOffset = pos;
  70916. _this.triangles.push(triangle);
  70917. };
  70918. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  70919. _this.init(callback);
  70920. });
  70921. });
  70922. };
  70923. QuadraticErrorSimplification.prototype.init = function (callback) {
  70924. var _this = this;
  70925. var triangleInit1 = function (i) {
  70926. var t = _this.triangles[i];
  70927. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  70928. for (var j = 0; j < 3; j++) {
  70929. 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))));
  70930. }
  70931. };
  70932. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  70933. var triangleInit2 = function (i) {
  70934. var t = _this.triangles[i];
  70935. for (var j = 0; j < 3; ++j) {
  70936. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  70937. }
  70938. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70939. };
  70940. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  70941. _this.initialized = true;
  70942. callback();
  70943. });
  70944. });
  70945. };
  70946. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  70947. var newTriangles = [];
  70948. var i;
  70949. for (i = 0; i < this.vertices.length; ++i) {
  70950. this.vertices[i].triangleCount = 0;
  70951. }
  70952. var t;
  70953. var j;
  70954. for (i = 0; i < this.triangles.length; ++i) {
  70955. if (!this.triangles[i].deleted) {
  70956. t = this.triangles[i];
  70957. for (j = 0; j < 3; ++j) {
  70958. t.vertices[j].triangleCount = 1;
  70959. }
  70960. newTriangles.push(t);
  70961. }
  70962. }
  70963. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  70964. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  70965. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  70966. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  70967. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70968. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70969. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70970. var vertexCount = 0;
  70971. for (i = 0; i < this.vertices.length; ++i) {
  70972. var vertex = this.vertices[i];
  70973. vertex.id = vertexCount;
  70974. if (vertex.triangleCount) {
  70975. vertex.originalOffsets.forEach(function (originalOffset) {
  70976. if (!normalData) {
  70977. return;
  70978. }
  70979. newPositionData.push(vertex.position.x);
  70980. newPositionData.push(vertex.position.y);
  70981. newPositionData.push(vertex.position.z);
  70982. newNormalData.push(normalData[originalOffset * 3]);
  70983. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  70984. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  70985. if (uvs && uvs.length) {
  70986. newUVsData.push(uvs[(originalOffset * 2)]);
  70987. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  70988. }
  70989. else if (colorsData && colorsData.length) {
  70990. newColorsData.push(colorsData[(originalOffset * 4)]);
  70991. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  70992. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  70993. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  70994. }
  70995. ++vertexCount;
  70996. });
  70997. }
  70998. }
  70999. var startingIndex = this._reconstructedMesh.getTotalIndices();
  71000. var startingVertex = this._reconstructedMesh.getTotalVertices();
  71001. var submeshesArray = this._reconstructedMesh.subMeshes;
  71002. this._reconstructedMesh.subMeshes = [];
  71003. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  71004. var originalIndices = this._mesh.getIndices();
  71005. for (i = 0; i < newTriangles.length; ++i) {
  71006. t = newTriangles[i]; //now get the new referencing point for each vertex
  71007. [0, 1, 2].forEach(function (idx) {
  71008. var id = originalIndices[t.originalOffset + idx];
  71009. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  71010. if (offset < 0)
  71011. offset = 0;
  71012. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  71013. });
  71014. }
  71015. //overwriting the old vertex buffers and indices.
  71016. this._reconstructedMesh.setIndices(newIndicesArray);
  71017. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  71018. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  71019. if (newUVsData.length > 0)
  71020. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  71021. if (newColorsData.length > 0)
  71022. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  71023. //create submesh
  71024. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  71025. if (submeshIndex > 0) {
  71026. this._reconstructedMesh.subMeshes = [];
  71027. submeshesArray.forEach(function (submesh) {
  71028. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  71029. });
  71030. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  71031. }
  71032. };
  71033. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  71034. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  71035. this._reconstructedMesh.material = this._mesh.material;
  71036. this._reconstructedMesh.parent = this._mesh.parent;
  71037. this._reconstructedMesh.isVisible = false;
  71038. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  71039. };
  71040. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  71041. for (var i = 0; i < vertex1.triangleCount; ++i) {
  71042. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  71043. if (t.deleted)
  71044. continue;
  71045. var s = this.references[vertex1.triangleStart + i].vertexId;
  71046. var v1 = t.vertices[(s + 1) % 3];
  71047. var v2 = t.vertices[(s + 2) % 3];
  71048. if ((v1 === vertex2 || v2 === vertex2)) {
  71049. deletedArray[i] = true;
  71050. delTr.push(t);
  71051. continue;
  71052. }
  71053. var d1 = v1.position.subtract(point);
  71054. d1 = d1.normalize();
  71055. var d2 = v2.position.subtract(point);
  71056. d2 = d2.normalize();
  71057. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  71058. return true;
  71059. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  71060. deletedArray[i] = false;
  71061. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  71062. return true;
  71063. }
  71064. return false;
  71065. };
  71066. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  71067. var newDeleted = deletedTriangles;
  71068. for (var i = 0; i < vertex.triangleCount; ++i) {
  71069. var ref = this.references[vertex.triangleStart + i];
  71070. var t = this.triangles[ref.triangleId];
  71071. if (t.deleted)
  71072. continue;
  71073. if (deletedArray[i] && t.deletePending) {
  71074. t.deleted = true;
  71075. newDeleted++;
  71076. continue;
  71077. }
  71078. t.vertices[ref.vertexId] = origVertex;
  71079. t.isDirty = true;
  71080. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  71081. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  71082. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  71083. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  71084. this.references.push(ref);
  71085. }
  71086. return newDeleted;
  71087. };
  71088. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  71089. for (var i = 0; i < this.vertices.length; ++i) {
  71090. var vCount = [];
  71091. var vId = [];
  71092. var v = this.vertices[i];
  71093. var j;
  71094. for (j = 0; j < v.triangleCount; ++j) {
  71095. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  71096. for (var ii = 0; ii < 3; ii++) {
  71097. var ofs = 0;
  71098. var vv = triangle.vertices[ii];
  71099. while (ofs < vCount.length) {
  71100. if (vId[ofs] === vv.id)
  71101. break;
  71102. ++ofs;
  71103. }
  71104. if (ofs === vCount.length) {
  71105. vCount.push(1);
  71106. vId.push(vv.id);
  71107. }
  71108. else {
  71109. vCount[ofs]++;
  71110. }
  71111. }
  71112. }
  71113. for (j = 0; j < vCount.length; ++j) {
  71114. if (vCount[j] === 1) {
  71115. this.vertices[vId[j]].isBorder = true;
  71116. }
  71117. else {
  71118. this.vertices[vId[j]].isBorder = false;
  71119. }
  71120. }
  71121. }
  71122. };
  71123. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  71124. if (identifyBorders === void 0) { identifyBorders = false; }
  71125. var i;
  71126. if (!identifyBorders) {
  71127. var newTrianglesVector = [];
  71128. for (i = 0; i < this.triangles.length; ++i) {
  71129. if (!this.triangles[i].deleted) {
  71130. newTrianglesVector.push(this.triangles[i]);
  71131. }
  71132. }
  71133. this.triangles = newTrianglesVector;
  71134. }
  71135. for (i = 0; i < this.vertices.length; ++i) {
  71136. this.vertices[i].triangleCount = 0;
  71137. this.vertices[i].triangleStart = 0;
  71138. }
  71139. var t;
  71140. var j;
  71141. var v;
  71142. for (i = 0; i < this.triangles.length; ++i) {
  71143. t = this.triangles[i];
  71144. for (j = 0; j < 3; ++j) {
  71145. v = t.vertices[j];
  71146. v.triangleCount++;
  71147. }
  71148. }
  71149. var tStart = 0;
  71150. for (i = 0; i < this.vertices.length; ++i) {
  71151. this.vertices[i].triangleStart = tStart;
  71152. tStart += this.vertices[i].triangleCount;
  71153. this.vertices[i].triangleCount = 0;
  71154. }
  71155. var newReferences = new Array(this.triangles.length * 3);
  71156. for (i = 0; i < this.triangles.length; ++i) {
  71157. t = this.triangles[i];
  71158. for (j = 0; j < 3; ++j) {
  71159. v = t.vertices[j];
  71160. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  71161. v.triangleCount++;
  71162. }
  71163. }
  71164. this.references = newReferences;
  71165. if (identifyBorders) {
  71166. this.identifyBorder();
  71167. }
  71168. };
  71169. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  71170. var x = point.x;
  71171. var y = point.y;
  71172. var z = point.z;
  71173. 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
  71174. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  71175. };
  71176. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  71177. var q = vertex1.q.add(vertex2.q);
  71178. var border = vertex1.isBorder && vertex2.isBorder;
  71179. var error = 0;
  71180. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  71181. if (qDet !== 0 && !border) {
  71182. if (!pointResult) {
  71183. pointResult = BABYLON.Vector3.Zero();
  71184. }
  71185. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  71186. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  71187. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  71188. error = this.vertexError(q, pointResult);
  71189. }
  71190. else {
  71191. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  71192. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  71193. var error1 = this.vertexError(q, vertex1.position);
  71194. var error2 = this.vertexError(q, vertex2.position);
  71195. var error3 = this.vertexError(q, p3);
  71196. error = Math.min(error1, error2, error3);
  71197. if (error === error1) {
  71198. if (pointResult) {
  71199. pointResult.copyFrom(vertex1.position);
  71200. }
  71201. }
  71202. else if (error === error2) {
  71203. if (pointResult) {
  71204. pointResult.copyFrom(vertex2.position);
  71205. }
  71206. }
  71207. else {
  71208. if (pointResult) {
  71209. pointResult.copyFrom(p3);
  71210. }
  71211. }
  71212. }
  71213. return error;
  71214. };
  71215. return QuadraticErrorSimplification;
  71216. }());
  71217. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  71218. })(BABYLON || (BABYLON = {}));
  71219. //# sourceMappingURL=babylon.meshSimplification.js.map
  71220. var BABYLON;
  71221. (function (BABYLON) {
  71222. var Internals;
  71223. (function (Internals) {
  71224. var MeshLODLevel = /** @class */ (function () {
  71225. function MeshLODLevel(distance, mesh) {
  71226. this.distance = distance;
  71227. this.mesh = mesh;
  71228. }
  71229. return MeshLODLevel;
  71230. }());
  71231. Internals.MeshLODLevel = MeshLODLevel;
  71232. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  71233. })(BABYLON || (BABYLON = {}));
  71234. //# sourceMappingURL=babylon.meshLODLevel.js.map
  71235. var BABYLON;
  71236. (function (BABYLON) {
  71237. // Standard optimizations
  71238. var SceneOptimization = /** @class */ (function () {
  71239. function SceneOptimization(priority) {
  71240. if (priority === void 0) { priority = 0; }
  71241. this.priority = priority;
  71242. this.apply = function (scene) {
  71243. return true; // Return true if everything that can be done was applied
  71244. };
  71245. }
  71246. return SceneOptimization;
  71247. }());
  71248. BABYLON.SceneOptimization = SceneOptimization;
  71249. var TextureOptimization = /** @class */ (function (_super) {
  71250. __extends(TextureOptimization, _super);
  71251. function TextureOptimization(priority, maximumSize) {
  71252. if (priority === void 0) { priority = 0; }
  71253. if (maximumSize === void 0) { maximumSize = 1024; }
  71254. var _this = _super.call(this, priority) || this;
  71255. _this.priority = priority;
  71256. _this.maximumSize = maximumSize;
  71257. _this.apply = function (scene) {
  71258. var allDone = true;
  71259. for (var index = 0; index < scene.textures.length; index++) {
  71260. var texture = scene.textures[index];
  71261. if (!texture.canRescale || texture.getContext) {
  71262. continue;
  71263. }
  71264. var currentSize = texture.getSize();
  71265. var maxDimension = Math.max(currentSize.width, currentSize.height);
  71266. if (maxDimension > _this.maximumSize) {
  71267. texture.scale(0.5);
  71268. allDone = false;
  71269. }
  71270. }
  71271. return allDone;
  71272. };
  71273. return _this;
  71274. }
  71275. return TextureOptimization;
  71276. }(SceneOptimization));
  71277. BABYLON.TextureOptimization = TextureOptimization;
  71278. var HardwareScalingOptimization = /** @class */ (function (_super) {
  71279. __extends(HardwareScalingOptimization, _super);
  71280. function HardwareScalingOptimization(priority, maximumScale) {
  71281. if (priority === void 0) { priority = 0; }
  71282. if (maximumScale === void 0) { maximumScale = 2; }
  71283. var _this = _super.call(this, priority) || this;
  71284. _this.priority = priority;
  71285. _this.maximumScale = maximumScale;
  71286. _this._currentScale = 1;
  71287. _this.apply = function (scene) {
  71288. _this._currentScale++;
  71289. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  71290. return _this._currentScale >= _this.maximumScale;
  71291. };
  71292. return _this;
  71293. }
  71294. return HardwareScalingOptimization;
  71295. }(SceneOptimization));
  71296. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  71297. var ShadowsOptimization = /** @class */ (function (_super) {
  71298. __extends(ShadowsOptimization, _super);
  71299. function ShadowsOptimization() {
  71300. var _this = _super !== null && _super.apply(this, arguments) || this;
  71301. _this.apply = function (scene) {
  71302. scene.shadowsEnabled = false;
  71303. return true;
  71304. };
  71305. return _this;
  71306. }
  71307. return ShadowsOptimization;
  71308. }(SceneOptimization));
  71309. BABYLON.ShadowsOptimization = ShadowsOptimization;
  71310. var PostProcessesOptimization = /** @class */ (function (_super) {
  71311. __extends(PostProcessesOptimization, _super);
  71312. function PostProcessesOptimization() {
  71313. var _this = _super !== null && _super.apply(this, arguments) || this;
  71314. _this.apply = function (scene) {
  71315. scene.postProcessesEnabled = false;
  71316. return true;
  71317. };
  71318. return _this;
  71319. }
  71320. return PostProcessesOptimization;
  71321. }(SceneOptimization));
  71322. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  71323. var LensFlaresOptimization = /** @class */ (function (_super) {
  71324. __extends(LensFlaresOptimization, _super);
  71325. function LensFlaresOptimization() {
  71326. var _this = _super !== null && _super.apply(this, arguments) || this;
  71327. _this.apply = function (scene) {
  71328. scene.lensFlaresEnabled = false;
  71329. return true;
  71330. };
  71331. return _this;
  71332. }
  71333. return LensFlaresOptimization;
  71334. }(SceneOptimization));
  71335. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  71336. var ParticlesOptimization = /** @class */ (function (_super) {
  71337. __extends(ParticlesOptimization, _super);
  71338. function ParticlesOptimization() {
  71339. var _this = _super !== null && _super.apply(this, arguments) || this;
  71340. _this.apply = function (scene) {
  71341. scene.particlesEnabled = false;
  71342. return true;
  71343. };
  71344. return _this;
  71345. }
  71346. return ParticlesOptimization;
  71347. }(SceneOptimization));
  71348. BABYLON.ParticlesOptimization = ParticlesOptimization;
  71349. var RenderTargetsOptimization = /** @class */ (function (_super) {
  71350. __extends(RenderTargetsOptimization, _super);
  71351. function RenderTargetsOptimization() {
  71352. var _this = _super !== null && _super.apply(this, arguments) || this;
  71353. _this.apply = function (scene) {
  71354. scene.renderTargetsEnabled = false;
  71355. return true;
  71356. };
  71357. return _this;
  71358. }
  71359. return RenderTargetsOptimization;
  71360. }(SceneOptimization));
  71361. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71362. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71363. __extends(MergeMeshesOptimization, _super);
  71364. function MergeMeshesOptimization() {
  71365. var _this = _super !== null && _super.apply(this, arguments) || this;
  71366. _this._canBeMerged = function (abstractMesh) {
  71367. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71368. return false;
  71369. }
  71370. var mesh = abstractMesh;
  71371. if (!mesh.isVisible || !mesh.isEnabled()) {
  71372. return false;
  71373. }
  71374. if (mesh.instances.length > 0) {
  71375. return false;
  71376. }
  71377. if (mesh.skeleton || mesh.hasLODLevels) {
  71378. return false;
  71379. }
  71380. if (mesh.parent) {
  71381. return false;
  71382. }
  71383. return true;
  71384. };
  71385. _this.apply = function (scene, updateSelectionTree) {
  71386. var globalPool = scene.meshes.slice(0);
  71387. var globalLength = globalPool.length;
  71388. for (var index = 0; index < globalLength; index++) {
  71389. var currentPool = new Array();
  71390. var current = globalPool[index];
  71391. // Checks
  71392. if (!_this._canBeMerged(current)) {
  71393. continue;
  71394. }
  71395. currentPool.push(current);
  71396. // Find compatible meshes
  71397. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71398. var otherMesh = globalPool[subIndex];
  71399. if (!_this._canBeMerged(otherMesh)) {
  71400. continue;
  71401. }
  71402. if (otherMesh.material !== current.material) {
  71403. continue;
  71404. }
  71405. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71406. continue;
  71407. }
  71408. currentPool.push(otherMesh);
  71409. globalLength--;
  71410. globalPool.splice(subIndex, 1);
  71411. subIndex--;
  71412. }
  71413. if (currentPool.length < 2) {
  71414. continue;
  71415. }
  71416. // Merge meshes
  71417. BABYLON.Mesh.MergeMeshes(currentPool);
  71418. }
  71419. if (updateSelectionTree != undefined) {
  71420. if (updateSelectionTree) {
  71421. scene.createOrUpdateSelectionOctree();
  71422. }
  71423. }
  71424. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71425. scene.createOrUpdateSelectionOctree();
  71426. }
  71427. return true;
  71428. };
  71429. return _this;
  71430. }
  71431. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71432. get: function () {
  71433. return MergeMeshesOptimization._UpdateSelectionTree;
  71434. },
  71435. set: function (value) {
  71436. MergeMeshesOptimization._UpdateSelectionTree = value;
  71437. },
  71438. enumerable: true,
  71439. configurable: true
  71440. });
  71441. MergeMeshesOptimization._UpdateSelectionTree = false;
  71442. return MergeMeshesOptimization;
  71443. }(SceneOptimization));
  71444. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71445. // Options
  71446. var SceneOptimizerOptions = /** @class */ (function () {
  71447. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71448. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71449. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71450. this.targetFrameRate = targetFrameRate;
  71451. this.trackerDuration = trackerDuration;
  71452. this.optimizations = new Array();
  71453. }
  71454. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71455. var result = new SceneOptimizerOptions(targetFrameRate);
  71456. var priority = 0;
  71457. result.optimizations.push(new MergeMeshesOptimization(priority));
  71458. result.optimizations.push(new ShadowsOptimization(priority));
  71459. result.optimizations.push(new LensFlaresOptimization(priority));
  71460. // Next priority
  71461. priority++;
  71462. result.optimizations.push(new PostProcessesOptimization(priority));
  71463. result.optimizations.push(new ParticlesOptimization(priority));
  71464. // Next priority
  71465. priority++;
  71466. result.optimizations.push(new TextureOptimization(priority, 1024));
  71467. return result;
  71468. };
  71469. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71470. var result = new SceneOptimizerOptions(targetFrameRate);
  71471. var priority = 0;
  71472. result.optimizations.push(new MergeMeshesOptimization(priority));
  71473. result.optimizations.push(new ShadowsOptimization(priority));
  71474. result.optimizations.push(new LensFlaresOptimization(priority));
  71475. // Next priority
  71476. priority++;
  71477. result.optimizations.push(new PostProcessesOptimization(priority));
  71478. result.optimizations.push(new ParticlesOptimization(priority));
  71479. // Next priority
  71480. priority++;
  71481. result.optimizations.push(new TextureOptimization(priority, 512));
  71482. // Next priority
  71483. priority++;
  71484. result.optimizations.push(new RenderTargetsOptimization(priority));
  71485. // Next priority
  71486. priority++;
  71487. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71488. return result;
  71489. };
  71490. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71491. var result = new SceneOptimizerOptions(targetFrameRate);
  71492. var priority = 0;
  71493. result.optimizations.push(new MergeMeshesOptimization(priority));
  71494. result.optimizations.push(new ShadowsOptimization(priority));
  71495. result.optimizations.push(new LensFlaresOptimization(priority));
  71496. // Next priority
  71497. priority++;
  71498. result.optimizations.push(new PostProcessesOptimization(priority));
  71499. result.optimizations.push(new ParticlesOptimization(priority));
  71500. // Next priority
  71501. priority++;
  71502. result.optimizations.push(new TextureOptimization(priority, 256));
  71503. // Next priority
  71504. priority++;
  71505. result.optimizations.push(new RenderTargetsOptimization(priority));
  71506. // Next priority
  71507. priority++;
  71508. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71509. return result;
  71510. };
  71511. return SceneOptimizerOptions;
  71512. }());
  71513. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71514. // Scene optimizer tool
  71515. var SceneOptimizer = /** @class */ (function () {
  71516. function SceneOptimizer() {
  71517. }
  71518. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71519. // TODO: add an epsilon
  71520. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71521. if (onSuccess) {
  71522. onSuccess();
  71523. }
  71524. return;
  71525. }
  71526. // Apply current level of optimizations
  71527. var allDone = true;
  71528. var noOptimizationApplied = true;
  71529. for (var index = 0; index < options.optimizations.length; index++) {
  71530. var optimization = options.optimizations[index];
  71531. if (optimization.priority === currentPriorityLevel) {
  71532. noOptimizationApplied = false;
  71533. allDone = allDone && optimization.apply(scene);
  71534. }
  71535. }
  71536. // If no optimization was applied, this is a failure :(
  71537. if (noOptimizationApplied) {
  71538. if (onFailure) {
  71539. onFailure();
  71540. }
  71541. return;
  71542. }
  71543. // If all optimizations were done, move to next level
  71544. if (allDone) {
  71545. currentPriorityLevel++;
  71546. }
  71547. // Let's the system running for a specific amount of time before checking FPS
  71548. scene.executeWhenReady(function () {
  71549. setTimeout(function () {
  71550. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71551. }, options.trackerDuration);
  71552. });
  71553. };
  71554. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71555. if (!options) {
  71556. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71557. }
  71558. // Let's the system running for a specific amount of time before checking FPS
  71559. scene.executeWhenReady(function () {
  71560. setTimeout(function () {
  71561. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71562. }, options.trackerDuration);
  71563. });
  71564. };
  71565. return SceneOptimizer;
  71566. }());
  71567. BABYLON.SceneOptimizer = SceneOptimizer;
  71568. })(BABYLON || (BABYLON = {}));
  71569. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71570. var BABYLON;
  71571. (function (BABYLON) {
  71572. var OutlineRenderer = /** @class */ (function () {
  71573. function OutlineRenderer(scene) {
  71574. this.zOffset = 1;
  71575. this._scene = scene;
  71576. }
  71577. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71578. var _this = this;
  71579. if (useOverlay === void 0) { useOverlay = false; }
  71580. var scene = this._scene;
  71581. var engine = this._scene.getEngine();
  71582. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71583. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71584. return;
  71585. }
  71586. var mesh = subMesh.getRenderingMesh();
  71587. var material = subMesh.getMaterial();
  71588. if (!material || !scene.activeCamera) {
  71589. return;
  71590. }
  71591. engine.enableEffect(this._effect);
  71592. // Logarithmic depth
  71593. if (material.useLogarithmicDepth) {
  71594. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71595. }
  71596. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71597. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71598. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71599. // Bones
  71600. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71601. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71602. }
  71603. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71604. // Alpha test
  71605. if (material && material.needAlphaTesting()) {
  71606. var alphaTexture = material.getAlphaTestTexture();
  71607. if (alphaTexture) {
  71608. this._effect.setTexture("diffuseSampler", alphaTexture);
  71609. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71610. }
  71611. }
  71612. engine.setZOffset(-this.zOffset);
  71613. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71614. engine.setZOffset(0);
  71615. };
  71616. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71617. var defines = [];
  71618. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71619. var mesh = subMesh.getMesh();
  71620. var material = subMesh.getMaterial();
  71621. if (material) {
  71622. // Alpha test
  71623. if (material.needAlphaTesting()) {
  71624. defines.push("#define ALPHATEST");
  71625. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71626. attribs.push(BABYLON.VertexBuffer.UVKind);
  71627. defines.push("#define UV1");
  71628. }
  71629. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71630. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71631. defines.push("#define UV2");
  71632. }
  71633. }
  71634. //Logarithmic depth
  71635. if (material.useLogarithmicDepth) {
  71636. defines.push("#define LOGARITHMICDEPTH");
  71637. }
  71638. }
  71639. // Bones
  71640. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71641. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71642. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71643. if (mesh.numBoneInfluencers > 4) {
  71644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71646. }
  71647. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71648. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71649. }
  71650. else {
  71651. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71652. }
  71653. // Instances
  71654. if (useInstances) {
  71655. defines.push("#define INSTANCES");
  71656. attribs.push("world0");
  71657. attribs.push("world1");
  71658. attribs.push("world2");
  71659. attribs.push("world3");
  71660. }
  71661. // Get correct effect
  71662. var join = defines.join("\n");
  71663. if (this._cachedDefines !== join) {
  71664. this._cachedDefines = join;
  71665. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71666. }
  71667. return this._effect.isReady();
  71668. };
  71669. return OutlineRenderer;
  71670. }());
  71671. BABYLON.OutlineRenderer = OutlineRenderer;
  71672. })(BABYLON || (BABYLON = {}));
  71673. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71674. var BABYLON;
  71675. (function (BABYLON) {
  71676. var FaceAdjacencies = /** @class */ (function () {
  71677. function FaceAdjacencies() {
  71678. this.edges = new Array();
  71679. this.edgesConnectedCount = 0;
  71680. }
  71681. return FaceAdjacencies;
  71682. }());
  71683. var EdgesRenderer = /** @class */ (function () {
  71684. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71685. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71686. if (epsilon === void 0) { epsilon = 0.95; }
  71687. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71688. this.edgesWidthScalerForOrthographic = 1000.0;
  71689. this.edgesWidthScalerForPerspective = 50.0;
  71690. this._linesPositions = new Array();
  71691. this._linesNormals = new Array();
  71692. this._linesIndices = new Array();
  71693. this._buffers = {};
  71694. this._checkVerticesInsteadOfIndices = false;
  71695. this._source = source;
  71696. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71697. this._epsilon = epsilon;
  71698. this._prepareRessources();
  71699. this._generateEdgesLines();
  71700. }
  71701. EdgesRenderer.prototype._prepareRessources = function () {
  71702. if (this._lineShader) {
  71703. return;
  71704. }
  71705. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71706. attributes: ["position", "normal"],
  71707. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71708. });
  71709. this._lineShader.disableDepthWrite = true;
  71710. this._lineShader.backFaceCulling = false;
  71711. };
  71712. EdgesRenderer.prototype._rebuild = function () {
  71713. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71714. if (buffer) {
  71715. buffer._rebuild();
  71716. }
  71717. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71718. if (buffer) {
  71719. buffer._rebuild();
  71720. }
  71721. var scene = this._source.getScene();
  71722. var engine = scene.getEngine();
  71723. this._ib = engine.createIndexBuffer(this._linesIndices);
  71724. };
  71725. EdgesRenderer.prototype.dispose = function () {
  71726. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71727. if (buffer) {
  71728. buffer.dispose();
  71729. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71730. }
  71731. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71732. if (buffer) {
  71733. buffer.dispose();
  71734. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71735. }
  71736. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71737. this._lineShader.dispose();
  71738. };
  71739. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71740. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71741. return 0;
  71742. }
  71743. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71744. return 1;
  71745. }
  71746. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71747. return 2;
  71748. }
  71749. return -1;
  71750. };
  71751. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71752. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71753. return 0;
  71754. }
  71755. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71756. return 1;
  71757. }
  71758. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71759. return 2;
  71760. }
  71761. return -1;
  71762. };
  71763. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71764. var needToCreateLine;
  71765. if (edge === undefined) {
  71766. needToCreateLine = true;
  71767. }
  71768. else {
  71769. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71770. needToCreateLine = dotProduct < this._epsilon;
  71771. }
  71772. if (needToCreateLine) {
  71773. var offset = this._linesPositions.length / 3;
  71774. var normal = p0.subtract(p1);
  71775. normal.normalize();
  71776. // Positions
  71777. this._linesPositions.push(p0.x);
  71778. this._linesPositions.push(p0.y);
  71779. this._linesPositions.push(p0.z);
  71780. this._linesPositions.push(p0.x);
  71781. this._linesPositions.push(p0.y);
  71782. this._linesPositions.push(p0.z);
  71783. this._linesPositions.push(p1.x);
  71784. this._linesPositions.push(p1.y);
  71785. this._linesPositions.push(p1.z);
  71786. this._linesPositions.push(p1.x);
  71787. this._linesPositions.push(p1.y);
  71788. this._linesPositions.push(p1.z);
  71789. // Normals
  71790. this._linesNormals.push(p1.x);
  71791. this._linesNormals.push(p1.y);
  71792. this._linesNormals.push(p1.z);
  71793. this._linesNormals.push(-1);
  71794. this._linesNormals.push(p1.x);
  71795. this._linesNormals.push(p1.y);
  71796. this._linesNormals.push(p1.z);
  71797. this._linesNormals.push(1);
  71798. this._linesNormals.push(p0.x);
  71799. this._linesNormals.push(p0.y);
  71800. this._linesNormals.push(p0.z);
  71801. this._linesNormals.push(-1);
  71802. this._linesNormals.push(p0.x);
  71803. this._linesNormals.push(p0.y);
  71804. this._linesNormals.push(p0.z);
  71805. this._linesNormals.push(1);
  71806. // Indices
  71807. this._linesIndices.push(offset);
  71808. this._linesIndices.push(offset + 1);
  71809. this._linesIndices.push(offset + 2);
  71810. this._linesIndices.push(offset);
  71811. this._linesIndices.push(offset + 2);
  71812. this._linesIndices.push(offset + 3);
  71813. }
  71814. };
  71815. EdgesRenderer.prototype._generateEdgesLines = function () {
  71816. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71817. var indices = this._source.getIndices();
  71818. if (!indices || !positions) {
  71819. return;
  71820. }
  71821. // First let's find adjacencies
  71822. var adjacencies = new Array();
  71823. var faceNormals = new Array();
  71824. var index;
  71825. var faceAdjacencies;
  71826. // Prepare faces
  71827. for (index = 0; index < indices.length; index += 3) {
  71828. faceAdjacencies = new FaceAdjacencies();
  71829. var p0Index = indices[index];
  71830. var p1Index = indices[index + 1];
  71831. var p2Index = indices[index + 2];
  71832. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71833. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71834. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71835. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71836. faceNormal.normalize();
  71837. faceNormals.push(faceNormal);
  71838. adjacencies.push(faceAdjacencies);
  71839. }
  71840. // Scan
  71841. for (index = 0; index < adjacencies.length; index++) {
  71842. faceAdjacencies = adjacencies[index];
  71843. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71844. var otherFaceAdjacencies = adjacencies[otherIndex];
  71845. if (faceAdjacencies.edgesConnectedCount === 3) {
  71846. break;
  71847. }
  71848. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  71849. continue;
  71850. }
  71851. var otherP0 = indices[otherIndex * 3];
  71852. var otherP1 = indices[otherIndex * 3 + 1];
  71853. var otherP2 = indices[otherIndex * 3 + 2];
  71854. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  71855. var otherEdgeIndex = 0;
  71856. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  71857. continue;
  71858. }
  71859. switch (edgeIndex) {
  71860. case 0:
  71861. if (this._checkVerticesInsteadOfIndices) {
  71862. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71863. }
  71864. else {
  71865. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  71866. }
  71867. break;
  71868. case 1:
  71869. if (this._checkVerticesInsteadOfIndices) {
  71870. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71871. }
  71872. else {
  71873. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  71874. }
  71875. break;
  71876. case 2:
  71877. if (this._checkVerticesInsteadOfIndices) {
  71878. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71879. }
  71880. else {
  71881. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  71882. }
  71883. break;
  71884. }
  71885. if (otherEdgeIndex === -1) {
  71886. continue;
  71887. }
  71888. faceAdjacencies.edges[edgeIndex] = otherIndex;
  71889. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  71890. faceAdjacencies.edgesConnectedCount++;
  71891. otherFaceAdjacencies.edgesConnectedCount++;
  71892. if (faceAdjacencies.edgesConnectedCount === 3) {
  71893. break;
  71894. }
  71895. }
  71896. }
  71897. }
  71898. // Create lines
  71899. for (index = 0; index < adjacencies.length; index++) {
  71900. // 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
  71901. var current = adjacencies[index];
  71902. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  71903. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  71904. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  71905. }
  71906. // Merge into a single mesh
  71907. var engine = this._source.getScene().getEngine();
  71908. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  71909. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  71910. this._ib = engine.createIndexBuffer(this._linesIndices);
  71911. this._indicesCount = this._linesIndices.length;
  71912. };
  71913. EdgesRenderer.prototype.render = function () {
  71914. var scene = this._source.getScene();
  71915. if (!this._lineShader.isReady() || !scene.activeCamera) {
  71916. return;
  71917. }
  71918. var engine = scene.getEngine();
  71919. this._lineShader._preBind();
  71920. // VBOs
  71921. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  71922. scene.resetCachedMaterial();
  71923. this._lineShader.setColor4("color", this._source.edgesColor);
  71924. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  71925. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  71926. }
  71927. else {
  71928. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  71929. }
  71930. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  71931. this._lineShader.bind(this._source.getWorldMatrix());
  71932. // Draw order
  71933. engine.draw(true, 0, this._indicesCount);
  71934. this._lineShader.unbind();
  71935. engine.setDepthWrite(true);
  71936. };
  71937. return EdgesRenderer;
  71938. }());
  71939. BABYLON.EdgesRenderer = EdgesRenderer;
  71940. })(BABYLON || (BABYLON = {}));
  71941. //# sourceMappingURL=babylon.edgesRenderer.js.map
  71942. var BABYLON;
  71943. (function (BABYLON) {
  71944. /**
  71945. * Special Glow Blur post process only blurring the alpha channel
  71946. * It enforces keeping the most luminous color in the color channel.
  71947. */
  71948. var GlowBlurPostProcess = /** @class */ (function (_super) {
  71949. __extends(GlowBlurPostProcess, _super);
  71950. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  71951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71952. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  71953. _this.direction = direction;
  71954. _this.kernel = kernel;
  71955. _this.onApplyObservable.add(function (effect) {
  71956. effect.setFloat2("screenSize", _this.width, _this.height);
  71957. effect.setVector2("direction", _this.direction);
  71958. effect.setFloat("blurWidth", _this.kernel);
  71959. });
  71960. return _this;
  71961. }
  71962. return GlowBlurPostProcess;
  71963. }(BABYLON.PostProcess));
  71964. /**
  71965. * The highlight layer Helps adding a glow effect around a mesh.
  71966. *
  71967. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  71968. * glowy meshes to your scene.
  71969. *
  71970. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  71971. */
  71972. var HighlightLayer = /** @class */ (function () {
  71973. /**
  71974. * Instantiates a new highlight Layer and references it to the scene..
  71975. * @param name The name of the layer
  71976. * @param scene The scene to use the layer in
  71977. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  71978. */
  71979. function HighlightLayer(name, scene, options) {
  71980. this.name = name;
  71981. this._vertexBuffers = {};
  71982. this._mainTextureDesiredSize = { width: 0, height: 0 };
  71983. this._meshes = {};
  71984. this._maxSize = 0;
  71985. this._shouldRender = false;
  71986. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  71987. this._excludedMeshes = {};
  71988. /**
  71989. * Specifies whether or not the inner glow is ACTIVE in the layer.
  71990. */
  71991. this.innerGlow = true;
  71992. /**
  71993. * Specifies whether or not the outer glow is ACTIVE in the layer.
  71994. */
  71995. this.outerGlow = true;
  71996. /**
  71997. * Specifies wether the highlight layer is enabled or not.
  71998. */
  71999. this.isEnabled = true;
  72000. /**
  72001. * An event triggered when the highlight layer has been disposed.
  72002. * @type {BABYLON.Observable}
  72003. */
  72004. this.onDisposeObservable = new BABYLON.Observable();
  72005. /**
  72006. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  72007. * @type {BABYLON.Observable}
  72008. */
  72009. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  72010. /**
  72011. * An event triggered when the highlight layer is being blurred.
  72012. * @type {BABYLON.Observable}
  72013. */
  72014. this.onBeforeBlurObservable = new BABYLON.Observable();
  72015. /**
  72016. * An event triggered when the highlight layer has been blurred.
  72017. * @type {BABYLON.Observable}
  72018. */
  72019. this.onAfterBlurObservable = new BABYLON.Observable();
  72020. /**
  72021. * An event triggered when the glowing blurred texture is being merged in the scene.
  72022. * @type {BABYLON.Observable}
  72023. */
  72024. this.onBeforeComposeObservable = new BABYLON.Observable();
  72025. /**
  72026. * An event triggered when the glowing blurred texture has been merged in the scene.
  72027. * @type {BABYLON.Observable}
  72028. */
  72029. this.onAfterComposeObservable = new BABYLON.Observable();
  72030. /**
  72031. * An event triggered when the highlight layer changes its size.
  72032. * @type {BABYLON.Observable}
  72033. */
  72034. this.onSizeChangedObservable = new BABYLON.Observable();
  72035. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72036. var engine = scene.getEngine();
  72037. this._engine = engine;
  72038. this._maxSize = this._engine.getCaps().maxTextureSize;
  72039. this._scene.highlightLayers.push(this);
  72040. // Warn on stencil.
  72041. if (!this._engine.isStencilEnable) {
  72042. 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 }");
  72043. }
  72044. // Adapt options
  72045. this._options = options || {
  72046. mainTextureRatio: 0.5,
  72047. blurTextureSizeRatio: 0.5,
  72048. blurHorizontalSize: 1.0,
  72049. blurVerticalSize: 1.0,
  72050. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  72051. camera: null
  72052. };
  72053. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  72054. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  72055. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  72056. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  72057. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  72058. // VBO
  72059. var vertices = [];
  72060. vertices.push(1, 1);
  72061. vertices.push(-1, 1);
  72062. vertices.push(-1, -1);
  72063. vertices.push(1, -1);
  72064. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72065. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  72066. this._createIndexBuffer();
  72067. // Effect
  72068. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  72069. // Render target
  72070. this.setMainTextureSize();
  72071. // Create Textures and post processes
  72072. this.createTextureAndPostProcesses();
  72073. }
  72074. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  72075. /**
  72076. * Gets the horizontal size of the blur.
  72077. */
  72078. get: function () {
  72079. return this._horizontalBlurPostprocess.kernel;
  72080. },
  72081. /**
  72082. * Specifies the horizontal size of the blur.
  72083. */
  72084. set: function (value) {
  72085. this._horizontalBlurPostprocess.kernel = value;
  72086. },
  72087. enumerable: true,
  72088. configurable: true
  72089. });
  72090. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  72091. /**
  72092. * Gets the vertical size of the blur.
  72093. */
  72094. get: function () {
  72095. return this._verticalBlurPostprocess.kernel;
  72096. },
  72097. /**
  72098. * Specifies the vertical size of the blur.
  72099. */
  72100. set: function (value) {
  72101. this._verticalBlurPostprocess.kernel = value;
  72102. },
  72103. enumerable: true,
  72104. configurable: true
  72105. });
  72106. Object.defineProperty(HighlightLayer.prototype, "camera", {
  72107. /**
  72108. * Gets the camera attached to the layer.
  72109. */
  72110. get: function () {
  72111. return this._options.camera;
  72112. },
  72113. enumerable: true,
  72114. configurable: true
  72115. });
  72116. HighlightLayer.prototype._createIndexBuffer = function () {
  72117. var engine = this._scene.getEngine();
  72118. // Indices
  72119. var indices = [];
  72120. indices.push(0);
  72121. indices.push(1);
  72122. indices.push(2);
  72123. indices.push(0);
  72124. indices.push(2);
  72125. indices.push(3);
  72126. this._indexBuffer = engine.createIndexBuffer(indices);
  72127. };
  72128. HighlightLayer.prototype._rebuild = function () {
  72129. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72130. if (vb) {
  72131. vb._rebuild();
  72132. }
  72133. this._createIndexBuffer();
  72134. };
  72135. /**
  72136. * Creates the render target textures and post processes used in the highlight layer.
  72137. */
  72138. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  72139. var _this = this;
  72140. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  72141. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  72142. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  72143. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  72144. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  72145. width: this._mainTextureDesiredSize.width,
  72146. height: this._mainTextureDesiredSize.height
  72147. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72148. this._mainTexture.activeCamera = this._options.camera;
  72149. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72150. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72151. this._mainTexture.anisotropicFilteringLevel = 1;
  72152. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72153. this._mainTexture.renderParticles = false;
  72154. this._mainTexture.renderList = null;
  72155. this._mainTexture.ignoreCameraViewport = true;
  72156. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  72157. width: blurTextureWidth,
  72158. height: blurTextureHeight
  72159. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72160. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72161. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72162. this._blurTexture.anisotropicFilteringLevel = 16;
  72163. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72164. this._blurTexture.renderParticles = false;
  72165. this._blurTexture.ignoreCameraViewport = true;
  72166. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72167. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  72168. effect.setTexture("textureSampler", _this._mainTexture);
  72169. });
  72170. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  72171. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72172. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72173. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72174. });
  72175. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72176. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72177. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72178. });
  72179. }
  72180. else {
  72181. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72182. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72183. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72184. });
  72185. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72186. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72187. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72188. });
  72189. }
  72190. this._mainTexture.onAfterUnbindObservable.add(function () {
  72191. _this.onBeforeBlurObservable.notifyObservers(_this);
  72192. var internalTexture = _this._blurTexture.getInternalTexture();
  72193. if (internalTexture) {
  72194. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  72195. }
  72196. _this.onAfterBlurObservable.notifyObservers(_this);
  72197. });
  72198. // Custom render function
  72199. var renderSubMesh = function (subMesh) {
  72200. if (!_this._meshes) {
  72201. return;
  72202. }
  72203. var material = subMesh.getMaterial();
  72204. var mesh = subMesh.getRenderingMesh();
  72205. var scene = _this._scene;
  72206. var engine = scene.getEngine();
  72207. if (!material) {
  72208. return;
  72209. }
  72210. // Culling
  72211. engine.setState(material.backFaceCulling);
  72212. // Managing instances
  72213. var batch = mesh._getInstancesRenderList(subMesh._id);
  72214. if (batch.mustReturn) {
  72215. return;
  72216. }
  72217. // Excluded Mesh
  72218. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72219. return;
  72220. }
  72221. ;
  72222. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72223. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  72224. var emissiveTexture = null;
  72225. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  72226. emissiveTexture = material.emissiveTexture;
  72227. }
  72228. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  72229. engine.enableEffect(_this._glowMapGenerationEffect);
  72230. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  72231. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  72232. if (highlightLayerMesh) {
  72233. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  72234. }
  72235. else {
  72236. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  72237. }
  72238. // Alpha test
  72239. if (material && material.needAlphaTesting()) {
  72240. var alphaTexture = material.getAlphaTestTexture();
  72241. if (alphaTexture) {
  72242. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  72243. var textureMatrix = alphaTexture.getTextureMatrix();
  72244. if (textureMatrix) {
  72245. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  72246. }
  72247. }
  72248. }
  72249. // Glow emissive only
  72250. if (emissiveTexture) {
  72251. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  72252. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  72253. }
  72254. // Bones
  72255. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72256. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72257. }
  72258. // Draw
  72259. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  72260. }
  72261. else {
  72262. // Need to reset refresh rate of the shadowMap
  72263. _this._mainTexture.resetRefreshCounter();
  72264. }
  72265. };
  72266. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72267. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  72268. var index;
  72269. var engine = _this._scene.getEngine();
  72270. if (depthOnlySubMeshes.length) {
  72271. engine.setColorWrite(false);
  72272. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72273. renderSubMesh(depthOnlySubMeshes.data[index]);
  72274. }
  72275. engine.setColorWrite(true);
  72276. }
  72277. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72278. renderSubMesh(opaqueSubMeshes.data[index]);
  72279. }
  72280. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72281. renderSubMesh(alphaTestSubMeshes.data[index]);
  72282. }
  72283. for (index = 0; index < transparentSubMeshes.length; index++) {
  72284. renderSubMesh(transparentSubMeshes.data[index]);
  72285. }
  72286. };
  72287. this._mainTexture.onClearObservable.add(function (engine) {
  72288. engine.clear(HighlightLayer.neutralColor, true, true, true);
  72289. });
  72290. };
  72291. /**
  72292. * Checks for the readiness of the element composing the layer.
  72293. * @param subMesh the mesh to check for
  72294. * @param useInstances specify wether or not to use instances to render the mesh
  72295. * @param emissiveTexture the associated emissive texture used to generate the glow
  72296. * @return true if ready otherwise, false
  72297. */
  72298. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  72299. var material = subMesh.getMaterial();
  72300. if (!material) {
  72301. return false;
  72302. }
  72303. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  72304. return false;
  72305. }
  72306. var defines = [];
  72307. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72308. var mesh = subMesh.getMesh();
  72309. var uv1 = false;
  72310. var uv2 = false;
  72311. // Alpha test
  72312. if (material && material.needAlphaTesting()) {
  72313. var alphaTexture = material.getAlphaTestTexture();
  72314. if (alphaTexture) {
  72315. defines.push("#define ALPHATEST");
  72316. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72317. alphaTexture.coordinatesIndex === 1) {
  72318. defines.push("#define DIFFUSEUV2");
  72319. uv2 = true;
  72320. }
  72321. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72322. defines.push("#define DIFFUSEUV1");
  72323. uv1 = true;
  72324. }
  72325. }
  72326. }
  72327. // Emissive
  72328. if (emissiveTexture) {
  72329. defines.push("#define EMISSIVE");
  72330. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72331. emissiveTexture.coordinatesIndex === 1) {
  72332. defines.push("#define EMISSIVEUV2");
  72333. uv2 = true;
  72334. }
  72335. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72336. defines.push("#define EMISSIVEUV1");
  72337. uv1 = true;
  72338. }
  72339. }
  72340. if (uv1) {
  72341. attribs.push(BABYLON.VertexBuffer.UVKind);
  72342. defines.push("#define UV1");
  72343. }
  72344. if (uv2) {
  72345. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72346. defines.push("#define UV2");
  72347. }
  72348. // Bones
  72349. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72350. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72351. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72352. if (mesh.numBoneInfluencers > 4) {
  72353. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72354. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72355. }
  72356. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72357. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72358. }
  72359. else {
  72360. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72361. }
  72362. // Instances
  72363. if (useInstances) {
  72364. defines.push("#define INSTANCES");
  72365. attribs.push("world0");
  72366. attribs.push("world1");
  72367. attribs.push("world2");
  72368. attribs.push("world3");
  72369. }
  72370. // Get correct effect
  72371. var join = defines.join("\n");
  72372. if (this._cachedDefines !== join) {
  72373. this._cachedDefines = join;
  72374. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72375. }
  72376. return this._glowMapGenerationEffect.isReady();
  72377. };
  72378. /**
  72379. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72380. */
  72381. HighlightLayer.prototype.render = function () {
  72382. var currentEffect = this._glowMapMergeEffect;
  72383. // Check
  72384. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72385. return;
  72386. var engine = this._scene.getEngine();
  72387. this.onBeforeComposeObservable.notifyObservers(this);
  72388. // Render
  72389. engine.enableEffect(currentEffect);
  72390. engine.setState(false);
  72391. // Cache
  72392. var previousStencilBuffer = engine.getStencilBuffer();
  72393. var previousStencilFunction = engine.getStencilFunction();
  72394. var previousStencilMask = engine.getStencilMask();
  72395. var previousStencilOperationPass = engine.getStencilOperationPass();
  72396. var previousStencilOperationFail = engine.getStencilOperationFail();
  72397. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72398. var previousAlphaMode = engine.getAlphaMode();
  72399. // Texture
  72400. currentEffect.setTexture("textureSampler", this._blurTexture);
  72401. // VBOs
  72402. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72403. // Stencil operations
  72404. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72405. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72406. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72407. // Draw order
  72408. engine.setAlphaMode(this._options.alphaBlendingMode);
  72409. engine.setStencilMask(0x00);
  72410. engine.setStencilBuffer(true);
  72411. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72412. if (this.outerGlow) {
  72413. currentEffect.setFloat("offset", 0);
  72414. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72415. engine.draw(true, 0, 6);
  72416. }
  72417. if (this.innerGlow) {
  72418. currentEffect.setFloat("offset", 1);
  72419. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72420. engine.draw(true, 0, 6);
  72421. }
  72422. // Restore Cache
  72423. engine.setStencilFunction(previousStencilFunction);
  72424. engine.setStencilMask(previousStencilMask);
  72425. engine.setAlphaMode(previousAlphaMode);
  72426. engine.setStencilBuffer(previousStencilBuffer);
  72427. engine.setStencilOperationPass(previousStencilOperationPass);
  72428. engine.setStencilOperationFail(previousStencilOperationFail);
  72429. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72430. engine._stencilState.reset();
  72431. this.onAfterComposeObservable.notifyObservers(this);
  72432. // Handle size changes.
  72433. var size = this._mainTexture.getSize();
  72434. this.setMainTextureSize();
  72435. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72436. // Recreate RTT and post processes on size change.
  72437. this.onSizeChangedObservable.notifyObservers(this);
  72438. this.disposeTextureAndPostProcesses();
  72439. this.createTextureAndPostProcesses();
  72440. }
  72441. };
  72442. /**
  72443. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72444. * @param mesh The mesh to exclude from the highlight layer
  72445. */
  72446. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72447. if (!this._excludedMeshes) {
  72448. return;
  72449. }
  72450. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72451. if (!meshExcluded) {
  72452. this._excludedMeshes[mesh.uniqueId] = {
  72453. mesh: mesh,
  72454. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72455. mesh.getEngine().setStencilBuffer(false);
  72456. }),
  72457. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72458. mesh.getEngine().setStencilBuffer(true);
  72459. }),
  72460. };
  72461. }
  72462. };
  72463. /**
  72464. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72465. * @param mesh The mesh to highlight
  72466. */
  72467. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72468. if (!this._excludedMeshes) {
  72469. return;
  72470. }
  72471. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72472. if (meshExcluded) {
  72473. if (meshExcluded.beforeRender) {
  72474. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72475. }
  72476. if (meshExcluded.afterRender) {
  72477. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72478. }
  72479. }
  72480. this._excludedMeshes[mesh.uniqueId] = null;
  72481. };
  72482. /**
  72483. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72484. * @param mesh The mesh to highlight
  72485. * @param color The color of the highlight
  72486. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72487. */
  72488. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72489. var _this = this;
  72490. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72491. if (!this._meshes) {
  72492. return;
  72493. }
  72494. var meshHighlight = this._meshes[mesh.uniqueId];
  72495. if (meshHighlight) {
  72496. meshHighlight.color = color;
  72497. }
  72498. else {
  72499. this._meshes[mesh.uniqueId] = {
  72500. mesh: mesh,
  72501. color: color,
  72502. // Lambda required for capture due to Observable this context
  72503. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72504. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72505. _this.defaultStencilReference(mesh);
  72506. }
  72507. else {
  72508. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72509. }
  72510. }),
  72511. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72512. glowEmissiveOnly: glowEmissiveOnly
  72513. };
  72514. }
  72515. this._shouldRender = true;
  72516. };
  72517. /**
  72518. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72519. * @param mesh The mesh to highlight
  72520. */
  72521. HighlightLayer.prototype.removeMesh = function (mesh) {
  72522. if (!this._meshes) {
  72523. return;
  72524. }
  72525. var meshHighlight = this._meshes[mesh.uniqueId];
  72526. if (meshHighlight) {
  72527. if (meshHighlight.observerHighlight) {
  72528. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72529. }
  72530. if (meshHighlight.observerDefault) {
  72531. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72532. }
  72533. }
  72534. this._meshes[mesh.uniqueId] = null;
  72535. this._shouldRender = false;
  72536. for (var meshHighlightToCheck in this._meshes) {
  72537. if (meshHighlightToCheck) {
  72538. this._shouldRender = true;
  72539. break;
  72540. }
  72541. }
  72542. };
  72543. /**
  72544. * Returns true if the layer contains information to display, otherwise false.
  72545. */
  72546. HighlightLayer.prototype.shouldRender = function () {
  72547. return this.isEnabled && this._shouldRender;
  72548. };
  72549. /**
  72550. * Sets the main texture desired size which is the closest power of two
  72551. * of the engine canvas size.
  72552. */
  72553. HighlightLayer.prototype.setMainTextureSize = function () {
  72554. if (this._options.mainTextureFixedSize) {
  72555. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72556. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72557. }
  72558. else {
  72559. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72560. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72561. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72562. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72563. }
  72564. };
  72565. /**
  72566. * Force the stencil to the normal expected value for none glowing parts
  72567. */
  72568. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72569. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72570. };
  72571. /**
  72572. * Dispose only the render target textures and post process.
  72573. */
  72574. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72575. this._blurTexture.dispose();
  72576. this._mainTexture.dispose();
  72577. this._downSamplePostprocess.dispose();
  72578. this._horizontalBlurPostprocess.dispose();
  72579. this._verticalBlurPostprocess.dispose();
  72580. };
  72581. /**
  72582. * Dispose the highlight layer and free resources.
  72583. */
  72584. HighlightLayer.prototype.dispose = function () {
  72585. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72586. if (vertexBuffer) {
  72587. vertexBuffer.dispose();
  72588. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72589. }
  72590. if (this._indexBuffer) {
  72591. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72592. this._indexBuffer = null;
  72593. }
  72594. // Clean textures and post processes
  72595. this.disposeTextureAndPostProcesses();
  72596. if (this._meshes) {
  72597. // Clean mesh references
  72598. for (var id in this._meshes) {
  72599. var meshHighlight = this._meshes[id];
  72600. if (meshHighlight && meshHighlight.mesh) {
  72601. if (meshHighlight.observerHighlight) {
  72602. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72603. }
  72604. if (meshHighlight.observerDefault) {
  72605. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72606. }
  72607. }
  72608. }
  72609. this._meshes = null;
  72610. }
  72611. if (this._excludedMeshes) {
  72612. for (var id in this._excludedMeshes) {
  72613. var meshHighlight = this._excludedMeshes[id];
  72614. if (meshHighlight) {
  72615. if (meshHighlight.beforeRender) {
  72616. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72617. }
  72618. if (meshHighlight.afterRender) {
  72619. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72620. }
  72621. }
  72622. }
  72623. this._excludedMeshes = null;
  72624. }
  72625. // Remove from scene
  72626. var index = this._scene.highlightLayers.indexOf(this, 0);
  72627. if (index > -1) {
  72628. this._scene.highlightLayers.splice(index, 1);
  72629. }
  72630. // Callback
  72631. this.onDisposeObservable.notifyObservers(this);
  72632. this.onDisposeObservable.clear();
  72633. this.onBeforeRenderMainTextureObservable.clear();
  72634. this.onBeforeBlurObservable.clear();
  72635. this.onBeforeComposeObservable.clear();
  72636. this.onAfterComposeObservable.clear();
  72637. this.onSizeChangedObservable.clear();
  72638. };
  72639. /**
  72640. * The neutral color used during the preparation of the glow effect.
  72641. * This is black by default as the blend operation is a blend operation.
  72642. */
  72643. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72644. /**
  72645. * Stencil value used for glowing meshes.
  72646. */
  72647. HighlightLayer.glowingMeshStencilReference = 0x02;
  72648. /**
  72649. * Stencil value used for the other meshes in the scene.
  72650. */
  72651. HighlightLayer.normalMeshStencilReference = 0x01;
  72652. return HighlightLayer;
  72653. }());
  72654. BABYLON.HighlightLayer = HighlightLayer;
  72655. })(BABYLON || (BABYLON = {}));
  72656. //# sourceMappingURL=babylon.highlightlayer.js.map
  72657. var BABYLON;
  72658. (function (BABYLON) {
  72659. var AssetTaskState;
  72660. (function (AssetTaskState) {
  72661. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72662. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72663. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72664. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72665. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72666. var AbstractAssetTask = /** @class */ (function () {
  72667. function AbstractAssetTask(name) {
  72668. this.name = name;
  72669. this.isCompleted = false;
  72670. this.taskState = AssetTaskState.INIT;
  72671. }
  72672. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72673. var _this = this;
  72674. this.taskState = AssetTaskState.RUNNING;
  72675. this.runTask(scene, function () {
  72676. _this.onDoneCallback(onSuccess, onError);
  72677. }, function (msg, exception) {
  72678. _this.onErrorCallback(onError, msg, exception);
  72679. });
  72680. };
  72681. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72682. throw new Error("runTask is not implemented");
  72683. };
  72684. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72685. this.taskState = AssetTaskState.ERROR;
  72686. this.errorObject = {
  72687. message: message,
  72688. exception: exception
  72689. };
  72690. if (this.onError) {
  72691. this.onError(this, message, exception);
  72692. }
  72693. onError();
  72694. };
  72695. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72696. try {
  72697. this.taskState = AssetTaskState.DONE;
  72698. this.isCompleted = true;
  72699. if (this.onSuccess) {
  72700. this.onSuccess(this);
  72701. }
  72702. onSuccess();
  72703. }
  72704. catch (e) {
  72705. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72706. }
  72707. };
  72708. return AbstractAssetTask;
  72709. }());
  72710. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72711. var AssetsProgressEvent = /** @class */ (function () {
  72712. function AssetsProgressEvent(remainingCount, totalCount, task) {
  72713. this.remainingCount = remainingCount;
  72714. this.totalCount = totalCount;
  72715. this.task = task;
  72716. }
  72717. return AssetsProgressEvent;
  72718. }());
  72719. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  72720. var MeshAssetTask = /** @class */ (function (_super) {
  72721. __extends(MeshAssetTask, _super);
  72722. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72723. var _this = _super.call(this, name) || this;
  72724. _this.name = name;
  72725. _this.meshesNames = meshesNames;
  72726. _this.rootUrl = rootUrl;
  72727. _this.sceneFilename = sceneFilename;
  72728. return _this;
  72729. }
  72730. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72731. var _this = this;
  72732. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72733. _this.loadedMeshes = meshes;
  72734. _this.loadedParticleSystems = particleSystems;
  72735. _this.loadedSkeletons = skeletons;
  72736. onSuccess();
  72737. }, null, function (scene, message, exception) {
  72738. onError(message, exception);
  72739. });
  72740. };
  72741. return MeshAssetTask;
  72742. }(AbstractAssetTask));
  72743. BABYLON.MeshAssetTask = MeshAssetTask;
  72744. var TextFileAssetTask = /** @class */ (function (_super) {
  72745. __extends(TextFileAssetTask, _super);
  72746. function TextFileAssetTask(name, url) {
  72747. var _this = _super.call(this, name) || this;
  72748. _this.name = name;
  72749. _this.url = url;
  72750. return _this;
  72751. }
  72752. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72753. var _this = this;
  72754. BABYLON.Tools.LoadFile(this.url, function (data) {
  72755. _this.text = data;
  72756. onSuccess();
  72757. }, undefined, scene.database, false, function (request, exception) {
  72758. if (request) {
  72759. onError(request.status + " " + request.statusText, exception);
  72760. }
  72761. });
  72762. };
  72763. return TextFileAssetTask;
  72764. }(AbstractAssetTask));
  72765. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72766. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72767. __extends(BinaryFileAssetTask, _super);
  72768. function BinaryFileAssetTask(name, url) {
  72769. var _this = _super.call(this, name) || this;
  72770. _this.name = name;
  72771. _this.url = url;
  72772. return _this;
  72773. }
  72774. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72775. var _this = this;
  72776. BABYLON.Tools.LoadFile(this.url, function (data) {
  72777. _this.data = data;
  72778. onSuccess();
  72779. }, undefined, scene.database, true, function (request, exception) {
  72780. if (request) {
  72781. onError(request.status + " " + request.statusText, exception);
  72782. }
  72783. });
  72784. };
  72785. return BinaryFileAssetTask;
  72786. }(AbstractAssetTask));
  72787. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72788. var ImageAssetTask = /** @class */ (function (_super) {
  72789. __extends(ImageAssetTask, _super);
  72790. function ImageAssetTask(name, url) {
  72791. var _this = _super.call(this, name) || this;
  72792. _this.name = name;
  72793. _this.url = url;
  72794. return _this;
  72795. }
  72796. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72797. var _this = this;
  72798. var img = new Image();
  72799. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72800. img.onload = function () {
  72801. _this.image = img;
  72802. onSuccess();
  72803. };
  72804. img.onerror = function (err) {
  72805. onError("Error loading image", err);
  72806. };
  72807. img.src = this.url;
  72808. };
  72809. return ImageAssetTask;
  72810. }(AbstractAssetTask));
  72811. BABYLON.ImageAssetTask = ImageAssetTask;
  72812. var TextureAssetTask = /** @class */ (function (_super) {
  72813. __extends(TextureAssetTask, _super);
  72814. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72816. var _this = _super.call(this, name) || this;
  72817. _this.name = name;
  72818. _this.url = url;
  72819. _this.noMipmap = noMipmap;
  72820. _this.invertY = invertY;
  72821. _this.samplingMode = samplingMode;
  72822. return _this;
  72823. }
  72824. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72825. var onload = function () {
  72826. onSuccess();
  72827. };
  72828. var onerror = function (msg, exception) {
  72829. onError(msg, exception);
  72830. };
  72831. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72832. };
  72833. return TextureAssetTask;
  72834. }(AbstractAssetTask));
  72835. BABYLON.TextureAssetTask = TextureAssetTask;
  72836. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72837. __extends(CubeTextureAssetTask, _super);
  72838. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72839. var _this = _super.call(this, name) || this;
  72840. _this.name = name;
  72841. _this.url = url;
  72842. _this.extensions = extensions;
  72843. _this.noMipmap = noMipmap;
  72844. _this.files = files;
  72845. return _this;
  72846. }
  72847. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72848. var onload = function () {
  72849. onSuccess();
  72850. };
  72851. var onerror = function (msg, exception) {
  72852. onError(msg, exception);
  72853. };
  72854. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  72855. };
  72856. return CubeTextureAssetTask;
  72857. }(AbstractAssetTask));
  72858. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  72859. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  72860. __extends(HDRCubeTextureAssetTask, _super);
  72861. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72862. if (noMipmap === void 0) { noMipmap = false; }
  72863. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72864. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72865. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72866. var _this = _super.call(this, name) || this;
  72867. _this.name = name;
  72868. _this.url = url;
  72869. _this.size = size;
  72870. _this.noMipmap = noMipmap;
  72871. _this.generateHarmonics = generateHarmonics;
  72872. _this.useInGammaSpace = useInGammaSpace;
  72873. _this.usePMREMGenerator = usePMREMGenerator;
  72874. return _this;
  72875. }
  72876. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72877. var onload = function () {
  72878. onSuccess();
  72879. };
  72880. var onerror = function (message, exception) {
  72881. onError(message, exception);
  72882. };
  72883. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  72884. };
  72885. return HDRCubeTextureAssetTask;
  72886. }(AbstractAssetTask));
  72887. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  72888. var AssetsManager = /** @class */ (function () {
  72889. function AssetsManager(scene) {
  72890. this.tasks = new Array();
  72891. this.waitingTasksCount = 0;
  72892. //Observables
  72893. this.onTaskSuccessObservable = new BABYLON.Observable();
  72894. this.onTaskErrorObservable = new BABYLON.Observable();
  72895. this.onTasksDoneObservable = new BABYLON.Observable();
  72896. this.onProgressObservable = new BABYLON.Observable();
  72897. this.useDefaultLoadingScreen = true;
  72898. this._scene = scene;
  72899. }
  72900. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  72901. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  72902. this.tasks.push(task);
  72903. return task;
  72904. };
  72905. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  72906. var task = new TextFileAssetTask(taskName, url);
  72907. this.tasks.push(task);
  72908. return task;
  72909. };
  72910. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  72911. var task = new BinaryFileAssetTask(taskName, url);
  72912. this.tasks.push(task);
  72913. return task;
  72914. };
  72915. AssetsManager.prototype.addImageTask = function (taskName, url) {
  72916. var task = new ImageAssetTask(taskName, url);
  72917. this.tasks.push(task);
  72918. return task;
  72919. };
  72920. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  72921. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72922. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  72923. this.tasks.push(task);
  72924. return task;
  72925. };
  72926. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  72927. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  72928. this.tasks.push(task);
  72929. return task;
  72930. };
  72931. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72932. if (noMipmap === void 0) { noMipmap = false; }
  72933. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72934. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72935. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72936. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  72937. this.tasks.push(task);
  72938. return task;
  72939. };
  72940. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  72941. this.waitingTasksCount--;
  72942. try {
  72943. if (this.onProgress) {
  72944. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  72945. }
  72946. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  72947. }
  72948. catch (e) {
  72949. BABYLON.Tools.Error("Error running progress callbacks.");
  72950. console.log(e);
  72951. }
  72952. if (this.waitingTasksCount === 0) {
  72953. try {
  72954. if (this.onFinish) {
  72955. this.onFinish(this.tasks);
  72956. }
  72957. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72958. }
  72959. catch (e) {
  72960. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  72961. console.log(e);
  72962. }
  72963. this._scene.getEngine().hideLoadingUI();
  72964. }
  72965. };
  72966. AssetsManager.prototype._runTask = function (task) {
  72967. var _this = this;
  72968. var done = function () {
  72969. try {
  72970. if (_this.onTaskSuccess) {
  72971. _this.onTaskSuccess(task);
  72972. }
  72973. _this.onTaskSuccessObservable.notifyObservers(task);
  72974. _this._decreaseWaitingTasksCount(task);
  72975. }
  72976. catch (e) {
  72977. error("Error executing task success callbacks", e);
  72978. }
  72979. };
  72980. var error = function (message, exception) {
  72981. task.errorObject = task.errorObject || {
  72982. message: message,
  72983. exception: exception
  72984. };
  72985. if (_this.onTaskError) {
  72986. _this.onTaskError(task);
  72987. }
  72988. _this.onTaskErrorObservable.notifyObservers(task);
  72989. _this._decreaseWaitingTasksCount(task);
  72990. };
  72991. task.run(this._scene, done, error);
  72992. };
  72993. AssetsManager.prototype.reset = function () {
  72994. this.tasks = new Array();
  72995. return this;
  72996. };
  72997. AssetsManager.prototype.load = function () {
  72998. this.waitingTasksCount = this.tasks.length;
  72999. if (this.waitingTasksCount === 0) {
  73000. if (this.onFinish) {
  73001. this.onFinish(this.tasks);
  73002. }
  73003. this.onTasksDoneObservable.notifyObservers(this.tasks);
  73004. return this;
  73005. }
  73006. if (this.useDefaultLoadingScreen) {
  73007. this._scene.getEngine().displayLoadingUI();
  73008. }
  73009. for (var index = 0; index < this.tasks.length; index++) {
  73010. var task = this.tasks[index];
  73011. this._runTask(task);
  73012. }
  73013. return this;
  73014. };
  73015. return AssetsManager;
  73016. }());
  73017. BABYLON.AssetsManager = AssetsManager;
  73018. })(BABYLON || (BABYLON = {}));
  73019. //# sourceMappingURL=babylon.assetsManager.js.map
  73020. var BABYLON;
  73021. (function (BABYLON) {
  73022. var serializedGeometries = [];
  73023. var serializeGeometry = function (geometry, serializationGeometries) {
  73024. if (serializedGeometries[geometry.id]) {
  73025. return;
  73026. }
  73027. if (geometry.doNotSerialize) {
  73028. return;
  73029. }
  73030. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  73031. serializationGeometries.boxes.push(geometry.serialize());
  73032. }
  73033. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  73034. serializationGeometries.spheres.push(geometry.serialize());
  73035. }
  73036. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  73037. serializationGeometries.cylinders.push(geometry.serialize());
  73038. }
  73039. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  73040. serializationGeometries.toruses.push(geometry.serialize());
  73041. }
  73042. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  73043. serializationGeometries.grounds.push(geometry.serialize());
  73044. }
  73045. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  73046. serializationGeometries.planes.push(geometry.serialize());
  73047. }
  73048. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  73049. serializationGeometries.torusKnots.push(geometry.serialize());
  73050. }
  73051. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  73052. throw new Error("Unknown primitive type");
  73053. }
  73054. else {
  73055. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  73056. }
  73057. serializedGeometries[geometry.id] = true;
  73058. };
  73059. var serializeMesh = function (mesh, serializationScene) {
  73060. var serializationObject = {};
  73061. // Geometry
  73062. var geometry = mesh._geometry;
  73063. if (geometry) {
  73064. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  73065. // 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
  73066. serializeGeometry(geometry, serializationScene.geometries);
  73067. }
  73068. }
  73069. // Custom
  73070. if (mesh.serialize) {
  73071. mesh.serialize(serializationObject);
  73072. }
  73073. return serializationObject;
  73074. };
  73075. var finalizeSingleMesh = function (mesh, serializationObject) {
  73076. //only works if the mesh is already loaded
  73077. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73078. //serialize material
  73079. if (mesh.material) {
  73080. if (mesh.material instanceof BABYLON.StandardMaterial) {
  73081. serializationObject.materials = serializationObject.materials || [];
  73082. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  73083. serializationObject.materials.push(mesh.material.serialize());
  73084. }
  73085. }
  73086. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  73087. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  73088. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  73089. serializationObject.multiMaterials.push(mesh.material.serialize());
  73090. }
  73091. }
  73092. }
  73093. //serialize geometry
  73094. var geometry = mesh._geometry;
  73095. if (geometry) {
  73096. if (!serializationObject.geometries) {
  73097. serializationObject.geometries = {};
  73098. serializationObject.geometries.boxes = [];
  73099. serializationObject.geometries.spheres = [];
  73100. serializationObject.geometries.cylinders = [];
  73101. serializationObject.geometries.toruses = [];
  73102. serializationObject.geometries.grounds = [];
  73103. serializationObject.geometries.planes = [];
  73104. serializationObject.geometries.torusKnots = [];
  73105. serializationObject.geometries.vertexData = [];
  73106. }
  73107. serializeGeometry(geometry, serializationObject.geometries);
  73108. }
  73109. // Skeletons
  73110. if (mesh.skeleton) {
  73111. serializationObject.skeletons = serializationObject.skeletons || [];
  73112. serializationObject.skeletons.push(mesh.skeleton.serialize());
  73113. }
  73114. //serialize the actual mesh
  73115. serializationObject.meshes = serializationObject.meshes || [];
  73116. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73117. }
  73118. };
  73119. var SceneSerializer = /** @class */ (function () {
  73120. function SceneSerializer() {
  73121. }
  73122. SceneSerializer.ClearCache = function () {
  73123. serializedGeometries = [];
  73124. };
  73125. SceneSerializer.Serialize = function (scene) {
  73126. var serializationObject = {};
  73127. SceneSerializer.ClearCache();
  73128. // Scene
  73129. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  73130. serializationObject.autoClear = scene.autoClear;
  73131. serializationObject.clearColor = scene.clearColor.asArray();
  73132. serializationObject.ambientColor = scene.ambientColor.asArray();
  73133. serializationObject.gravity = scene.gravity.asArray();
  73134. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  73135. serializationObject.workerCollisions = scene.workerCollisions;
  73136. // Fog
  73137. if (scene.fogMode && scene.fogMode !== 0) {
  73138. serializationObject.fogMode = scene.fogMode;
  73139. serializationObject.fogColor = scene.fogColor.asArray();
  73140. serializationObject.fogStart = scene.fogStart;
  73141. serializationObject.fogEnd = scene.fogEnd;
  73142. serializationObject.fogDensity = scene.fogDensity;
  73143. }
  73144. //Physics
  73145. if (scene.isPhysicsEnabled()) {
  73146. var physicEngine = scene.getPhysicsEngine();
  73147. if (physicEngine) {
  73148. serializationObject.physicsEnabled = true;
  73149. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  73150. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  73151. }
  73152. }
  73153. // Metadata
  73154. if (scene.metadata) {
  73155. serializationObject.metadata = scene.metadata;
  73156. }
  73157. // Morph targets
  73158. serializationObject.morphTargetManagers = [];
  73159. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  73160. var abstractMesh = _a[_i];
  73161. var manager = abstractMesh.morphTargetManager;
  73162. if (manager) {
  73163. serializationObject.morphTargetManagers.push(manager.serialize());
  73164. }
  73165. }
  73166. // Lights
  73167. serializationObject.lights = [];
  73168. var index;
  73169. var light;
  73170. for (index = 0; index < scene.lights.length; index++) {
  73171. light = scene.lights[index];
  73172. if (!light.doNotSerialize) {
  73173. serializationObject.lights.push(light.serialize());
  73174. }
  73175. }
  73176. // Cameras
  73177. serializationObject.cameras = [];
  73178. for (index = 0; index < scene.cameras.length; index++) {
  73179. var camera = scene.cameras[index];
  73180. if (!camera.doNotSerialize) {
  73181. serializationObject.cameras.push(camera.serialize());
  73182. }
  73183. }
  73184. if (scene.activeCamera) {
  73185. serializationObject.activeCameraID = scene.activeCamera.id;
  73186. }
  73187. // Animations
  73188. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  73189. // Materials
  73190. serializationObject.materials = [];
  73191. serializationObject.multiMaterials = [];
  73192. var material;
  73193. for (index = 0; index < scene.materials.length; index++) {
  73194. material = scene.materials[index];
  73195. if (!material.doNotSerialize) {
  73196. serializationObject.materials.push(material.serialize());
  73197. }
  73198. }
  73199. // MultiMaterials
  73200. serializationObject.multiMaterials = [];
  73201. for (index = 0; index < scene.multiMaterials.length; index++) {
  73202. var multiMaterial = scene.multiMaterials[index];
  73203. serializationObject.multiMaterials.push(multiMaterial.serialize());
  73204. }
  73205. // Skeletons
  73206. serializationObject.skeletons = [];
  73207. for (index = 0; index < scene.skeletons.length; index++) {
  73208. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  73209. }
  73210. // Geometries
  73211. serializationObject.geometries = {};
  73212. serializationObject.geometries.boxes = [];
  73213. serializationObject.geometries.spheres = [];
  73214. serializationObject.geometries.cylinders = [];
  73215. serializationObject.geometries.toruses = [];
  73216. serializationObject.geometries.grounds = [];
  73217. serializationObject.geometries.planes = [];
  73218. serializationObject.geometries.torusKnots = [];
  73219. serializationObject.geometries.vertexData = [];
  73220. serializedGeometries = [];
  73221. var geometries = scene.getGeometries();
  73222. for (index = 0; index < geometries.length; index++) {
  73223. var geometry = geometries[index];
  73224. if (geometry.isReady()) {
  73225. serializeGeometry(geometry, serializationObject.geometries);
  73226. }
  73227. }
  73228. // Meshes
  73229. serializationObject.meshes = [];
  73230. for (index = 0; index < scene.meshes.length; index++) {
  73231. var abstractMesh = scene.meshes[index];
  73232. if (abstractMesh instanceof BABYLON.Mesh) {
  73233. var mesh = abstractMesh;
  73234. if (!mesh.doNotSerialize) {
  73235. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73236. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73237. }
  73238. }
  73239. }
  73240. }
  73241. // Particles Systems
  73242. serializationObject.particleSystems = [];
  73243. for (index = 0; index < scene.particleSystems.length; index++) {
  73244. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  73245. }
  73246. // Lens flares
  73247. serializationObject.lensFlareSystems = [];
  73248. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  73249. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  73250. }
  73251. // Shadows
  73252. serializationObject.shadowGenerators = [];
  73253. for (index = 0; index < scene.lights.length; index++) {
  73254. light = scene.lights[index];
  73255. var shadowGenerator = light.getShadowGenerator();
  73256. if (shadowGenerator) {
  73257. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73258. }
  73259. }
  73260. // Action Manager
  73261. if (scene.actionManager) {
  73262. serializationObject.actions = scene.actionManager.serialize("scene");
  73263. }
  73264. // Audio
  73265. serializationObject.sounds = [];
  73266. for (index = 0; index < scene.soundTracks.length; index++) {
  73267. var soundtrack = scene.soundTracks[index];
  73268. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  73269. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  73270. }
  73271. }
  73272. return serializationObject;
  73273. };
  73274. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  73275. if (withParents === void 0) { withParents = false; }
  73276. if (withChildren === void 0) { withChildren = false; }
  73277. var serializationObject = {};
  73278. SceneSerializer.ClearCache();
  73279. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  73280. if (withParents || withChildren) {
  73281. //deliberate for loop! not for each, appended should be processed as well.
  73282. for (var i = 0; i < toSerialize.length; ++i) {
  73283. if (withChildren) {
  73284. toSerialize[i].getDescendants().forEach(function (node) {
  73285. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  73286. toSerialize.push(node);
  73287. }
  73288. });
  73289. }
  73290. //make sure the array doesn't contain the object already
  73291. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  73292. toSerialize.push(toSerialize[i].parent);
  73293. }
  73294. }
  73295. }
  73296. toSerialize.forEach(function (mesh) {
  73297. finalizeSingleMesh(mesh, serializationObject);
  73298. });
  73299. return serializationObject;
  73300. };
  73301. return SceneSerializer;
  73302. }());
  73303. BABYLON.SceneSerializer = SceneSerializer;
  73304. })(BABYLON || (BABYLON = {}));
  73305. //# sourceMappingURL=babylon.sceneSerializer.js.map
  73306. var BABYLON;
  73307. (function (BABYLON) {
  73308. var ReflectionProbe = /** @class */ (function () {
  73309. function ReflectionProbe(name, size, scene, generateMipMaps) {
  73310. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73311. var _this = this;
  73312. this.name = name;
  73313. this._viewMatrix = BABYLON.Matrix.Identity();
  73314. this._target = BABYLON.Vector3.Zero();
  73315. this._add = BABYLON.Vector3.Zero();
  73316. this.invertYAxis = false;
  73317. this.position = BABYLON.Vector3.Zero();
  73318. this._scene = scene;
  73319. this._scene.reflectionProbes.push(this);
  73320. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  73321. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  73322. switch (faceIndex) {
  73323. case 0:
  73324. _this._add.copyFromFloats(1, 0, 0);
  73325. break;
  73326. case 1:
  73327. _this._add.copyFromFloats(-1, 0, 0);
  73328. break;
  73329. case 2:
  73330. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  73331. break;
  73332. case 3:
  73333. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  73334. break;
  73335. case 4:
  73336. _this._add.copyFromFloats(0, 0, 1);
  73337. break;
  73338. case 5:
  73339. _this._add.copyFromFloats(0, 0, -1);
  73340. break;
  73341. }
  73342. if (_this._attachedMesh) {
  73343. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  73344. }
  73345. _this.position.addToRef(_this._add, _this._target);
  73346. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  73347. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  73348. scene._forcedViewPosition = _this.position;
  73349. });
  73350. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  73351. scene._forcedViewPosition = null;
  73352. scene.updateTransformMatrix(true);
  73353. });
  73354. if (scene.activeCamera) {
  73355. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73356. }
  73357. }
  73358. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73359. get: function () {
  73360. return this._renderTargetTexture.samples;
  73361. },
  73362. set: function (value) {
  73363. this._renderTargetTexture.samples = value;
  73364. },
  73365. enumerable: true,
  73366. configurable: true
  73367. });
  73368. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73369. get: function () {
  73370. return this._renderTargetTexture.refreshRate;
  73371. },
  73372. set: function (value) {
  73373. this._renderTargetTexture.refreshRate = value;
  73374. },
  73375. enumerable: true,
  73376. configurable: true
  73377. });
  73378. ReflectionProbe.prototype.getScene = function () {
  73379. return this._scene;
  73380. };
  73381. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73382. get: function () {
  73383. return this._renderTargetTexture;
  73384. },
  73385. enumerable: true,
  73386. configurable: true
  73387. });
  73388. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73389. get: function () {
  73390. return this._renderTargetTexture.renderList;
  73391. },
  73392. enumerable: true,
  73393. configurable: true
  73394. });
  73395. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73396. this._attachedMesh = mesh;
  73397. };
  73398. /**
  73399. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73400. *
  73401. * @param renderingGroupId The rendering group id corresponding to its index
  73402. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73403. */
  73404. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73405. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73406. };
  73407. ReflectionProbe.prototype.dispose = function () {
  73408. var index = this._scene.reflectionProbes.indexOf(this);
  73409. if (index !== -1) {
  73410. // Remove from the scene if found
  73411. this._scene.reflectionProbes.splice(index, 1);
  73412. }
  73413. if (this._renderTargetTexture) {
  73414. this._renderTargetTexture.dispose();
  73415. this._renderTargetTexture = null;
  73416. }
  73417. };
  73418. return ReflectionProbe;
  73419. }());
  73420. BABYLON.ReflectionProbe = ReflectionProbe;
  73421. })(BABYLON || (BABYLON = {}));
  73422. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73423. var BABYLON;
  73424. (function (BABYLON) {
  73425. var Layer = /** @class */ (function () {
  73426. function Layer(name, imgUrl, scene, isBackground, color) {
  73427. this.name = name;
  73428. this.scale = new BABYLON.Vector2(1, 1);
  73429. this.offset = new BABYLON.Vector2(0, 0);
  73430. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73431. this.layerMask = 0x0FFFFFFF;
  73432. this._vertexBuffers = {};
  73433. // Events
  73434. /**
  73435. * An event triggered when the layer is disposed.
  73436. * @type {BABYLON.Observable}
  73437. */
  73438. this.onDisposeObservable = new BABYLON.Observable();
  73439. /**
  73440. * An event triggered before rendering the scene
  73441. * @type {BABYLON.Observable}
  73442. */
  73443. this.onBeforeRenderObservable = new BABYLON.Observable();
  73444. /**
  73445. * An event triggered after rendering the scene
  73446. * @type {BABYLON.Observable}
  73447. */
  73448. this.onAfterRenderObservable = new BABYLON.Observable();
  73449. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73450. this.isBackground = isBackground === undefined ? true : isBackground;
  73451. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73452. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73453. this._scene.layers.push(this);
  73454. var engine = this._scene.getEngine();
  73455. // VBO
  73456. var vertices = [];
  73457. vertices.push(1, 1);
  73458. vertices.push(-1, 1);
  73459. vertices.push(-1, -1);
  73460. vertices.push(1, -1);
  73461. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73462. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73463. this._createIndexBuffer();
  73464. // Effects
  73465. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73466. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73467. }
  73468. Object.defineProperty(Layer.prototype, "onDispose", {
  73469. set: function (callback) {
  73470. if (this._onDisposeObserver) {
  73471. this.onDisposeObservable.remove(this._onDisposeObserver);
  73472. }
  73473. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73474. },
  73475. enumerable: true,
  73476. configurable: true
  73477. });
  73478. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73479. set: function (callback) {
  73480. if (this._onBeforeRenderObserver) {
  73481. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73482. }
  73483. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73484. },
  73485. enumerable: true,
  73486. configurable: true
  73487. });
  73488. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73489. set: function (callback) {
  73490. if (this._onAfterRenderObserver) {
  73491. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73492. }
  73493. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73494. },
  73495. enumerable: true,
  73496. configurable: true
  73497. });
  73498. Layer.prototype._createIndexBuffer = function () {
  73499. var engine = this._scene.getEngine();
  73500. // Indices
  73501. var indices = [];
  73502. indices.push(0);
  73503. indices.push(1);
  73504. indices.push(2);
  73505. indices.push(0);
  73506. indices.push(2);
  73507. indices.push(3);
  73508. this._indexBuffer = engine.createIndexBuffer(indices);
  73509. };
  73510. Layer.prototype._rebuild = function () {
  73511. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73512. if (vb) {
  73513. vb._rebuild();
  73514. }
  73515. this._createIndexBuffer();
  73516. };
  73517. Layer.prototype.render = function () {
  73518. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73519. // Check
  73520. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73521. return;
  73522. var engine = this._scene.getEngine();
  73523. this.onBeforeRenderObservable.notifyObservers(this);
  73524. // Render
  73525. engine.enableEffect(currentEffect);
  73526. engine.setState(false);
  73527. // Texture
  73528. currentEffect.setTexture("textureSampler", this.texture);
  73529. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73530. // Color
  73531. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73532. // Scale / offset
  73533. currentEffect.setVector2("offset", this.offset);
  73534. currentEffect.setVector2("scale", this.scale);
  73535. // VBOs
  73536. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73537. // Draw order
  73538. if (!this.alphaTest) {
  73539. engine.setAlphaMode(this.alphaBlendingMode);
  73540. engine.draw(true, 0, 6);
  73541. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73542. }
  73543. else {
  73544. engine.draw(true, 0, 6);
  73545. }
  73546. this.onAfterRenderObservable.notifyObservers(this);
  73547. };
  73548. Layer.prototype.dispose = function () {
  73549. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73550. if (vertexBuffer) {
  73551. vertexBuffer.dispose();
  73552. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73553. }
  73554. if (this._indexBuffer) {
  73555. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73556. this._indexBuffer = null;
  73557. }
  73558. if (this.texture) {
  73559. this.texture.dispose();
  73560. this.texture = null;
  73561. }
  73562. // Remove from scene
  73563. var index = this._scene.layers.indexOf(this);
  73564. this._scene.layers.splice(index, 1);
  73565. // Callback
  73566. this.onDisposeObservable.notifyObservers(this);
  73567. this.onDisposeObservable.clear();
  73568. this.onAfterRenderObservable.clear();
  73569. this.onBeforeRenderObservable.clear();
  73570. };
  73571. return Layer;
  73572. }());
  73573. BABYLON.Layer = Layer;
  73574. })(BABYLON || (BABYLON = {}));
  73575. //# sourceMappingURL=babylon.layer.js.map
  73576. var BABYLON;
  73577. (function (BABYLON) {
  73578. var TextureTools = /** @class */ (function () {
  73579. function TextureTools() {
  73580. }
  73581. /**
  73582. * Uses the GPU to create a copy texture rescaled at a given size
  73583. * @param texture Texture to copy from
  73584. * @param width Desired width
  73585. * @param height Desired height
  73586. * @return Generated texture
  73587. */
  73588. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73589. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73590. var scene = texture.getScene();
  73591. var engine = scene.getEngine();
  73592. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73593. rtt.wrapU = texture.wrapU;
  73594. rtt.wrapV = texture.wrapV;
  73595. rtt.uOffset = texture.uOffset;
  73596. rtt.vOffset = texture.vOffset;
  73597. rtt.uScale = texture.uScale;
  73598. rtt.vScale = texture.vScale;
  73599. rtt.uAng = texture.uAng;
  73600. rtt.vAng = texture.vAng;
  73601. rtt.wAng = texture.wAng;
  73602. rtt.coordinatesIndex = texture.coordinatesIndex;
  73603. rtt.level = texture.level;
  73604. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73605. rtt._texture.isReady = false;
  73606. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73607. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73608. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73609. passPostProcess.getEffect().executeWhenCompiled(function () {
  73610. passPostProcess.onApply = function (effect) {
  73611. effect.setTexture("textureSampler", texture);
  73612. };
  73613. var internalTexture = rtt.getInternalTexture();
  73614. if (internalTexture) {
  73615. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73616. engine.unBindFramebuffer(internalTexture);
  73617. rtt.disposeFramebufferObjects();
  73618. passPostProcess.dispose();
  73619. internalTexture.isReady = true;
  73620. }
  73621. });
  73622. return rtt;
  73623. };
  73624. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73625. if (!scene._environmentBRDFTexture) {
  73626. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73627. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73628. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73629. scene._environmentBRDFTexture = texture;
  73630. }
  73631. return scene._environmentBRDFTexture;
  73632. };
  73633. 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=";
  73634. return TextureTools;
  73635. }());
  73636. BABYLON.TextureTools = TextureTools;
  73637. })(BABYLON || (BABYLON = {}));
  73638. //# sourceMappingURL=babylon.textureTools.js.map
  73639. var BABYLON;
  73640. (function (BABYLON) {
  73641. var FramingBehavior = /** @class */ (function () {
  73642. function FramingBehavior() {
  73643. this._mode = FramingBehavior.FitFrustumSidesMode;
  73644. this._radiusScale = 1.0;
  73645. this._positionScale = 0.5;
  73646. this._defaultElevation = 0.3;
  73647. this._elevationReturnTime = 1500;
  73648. this._elevationReturnWaitTime = 1000;
  73649. this._zoomStopsAnimation = false;
  73650. this._framingTime = 1500;
  73651. this._isPointerDown = false;
  73652. this._lastInteractionTime = -Infinity;
  73653. // Framing control
  73654. this._animatables = new Array();
  73655. this._betaIsAnimating = false;
  73656. }
  73657. Object.defineProperty(FramingBehavior.prototype, "name", {
  73658. get: function () {
  73659. return "Framing";
  73660. },
  73661. enumerable: true,
  73662. configurable: true
  73663. });
  73664. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73665. /**
  73666. * Gets current mode used by the behavior.
  73667. */
  73668. get: function () {
  73669. return this._mode;
  73670. },
  73671. /**
  73672. * Sets the current mode used by the behavior
  73673. */
  73674. set: function (mode) {
  73675. this._mode = mode;
  73676. },
  73677. enumerable: true,
  73678. configurable: true
  73679. });
  73680. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73681. /**
  73682. * Gets the scale applied to the radius
  73683. */
  73684. get: function () {
  73685. return this._radiusScale;
  73686. },
  73687. /**
  73688. * Sets the scale applied to the radius (1 by default)
  73689. */
  73690. set: function (radius) {
  73691. this._radiusScale = radius;
  73692. },
  73693. enumerable: true,
  73694. configurable: true
  73695. });
  73696. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73697. /**
  73698. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73699. */
  73700. get: function () {
  73701. return this._positionScale;
  73702. },
  73703. /**
  73704. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73705. */
  73706. set: function (scale) {
  73707. this._positionScale = scale;
  73708. },
  73709. enumerable: true,
  73710. configurable: true
  73711. });
  73712. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73713. /**
  73714. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73715. * behaviour is triggered, in radians.
  73716. */
  73717. get: function () {
  73718. return this._defaultElevation;
  73719. },
  73720. /**
  73721. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73722. * behaviour is triggered, in radians.
  73723. */
  73724. set: function (elevation) {
  73725. this._defaultElevation = elevation;
  73726. },
  73727. enumerable: true,
  73728. configurable: true
  73729. });
  73730. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73731. /**
  73732. * Gets the time (in milliseconds) taken to return to the default beta position.
  73733. * Negative value indicates camera should not return to default.
  73734. */
  73735. get: function () {
  73736. return this._elevationReturnTime;
  73737. },
  73738. /**
  73739. * Sets the time (in milliseconds) taken to return to the default beta position.
  73740. * Negative value indicates camera should not return to default.
  73741. */
  73742. set: function (speed) {
  73743. this._elevationReturnTime = speed;
  73744. },
  73745. enumerable: true,
  73746. configurable: true
  73747. });
  73748. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73749. /**
  73750. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73751. */
  73752. get: function () {
  73753. return this._elevationReturnWaitTime;
  73754. },
  73755. /**
  73756. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73757. */
  73758. set: function (time) {
  73759. this._elevationReturnWaitTime = time;
  73760. },
  73761. enumerable: true,
  73762. configurable: true
  73763. });
  73764. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73765. /**
  73766. * Gets the flag that indicates if user zooming should stop animation.
  73767. */
  73768. get: function () {
  73769. return this._zoomStopsAnimation;
  73770. },
  73771. /**
  73772. * Sets the flag that indicates if user zooming should stop animation.
  73773. */
  73774. set: function (flag) {
  73775. this._zoomStopsAnimation = flag;
  73776. },
  73777. enumerable: true,
  73778. configurable: true
  73779. });
  73780. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73781. /**
  73782. * Gets the transition time when framing the mesh, in milliseconds
  73783. */
  73784. get: function () {
  73785. return this._framingTime;
  73786. },
  73787. /**
  73788. * Sets the transition time when framing the mesh, in milliseconds
  73789. */
  73790. set: function (time) {
  73791. this._framingTime = time;
  73792. },
  73793. enumerable: true,
  73794. configurable: true
  73795. });
  73796. FramingBehavior.prototype.init = function () {
  73797. // Do notihng
  73798. };
  73799. FramingBehavior.prototype.attach = function (camera) {
  73800. var _this = this;
  73801. this._attachedCamera = camera;
  73802. var scene = this._attachedCamera.getScene();
  73803. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73804. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73805. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73806. _this._isPointerDown = true;
  73807. return;
  73808. }
  73809. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73810. _this._isPointerDown = false;
  73811. }
  73812. });
  73813. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73814. if (mesh) {
  73815. _this.zoomOnMesh(mesh);
  73816. }
  73817. });
  73818. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73819. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73820. _this._applyUserInteraction();
  73821. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73822. // back to the default position after a given timeout
  73823. _this._maintainCameraAboveGround();
  73824. });
  73825. };
  73826. FramingBehavior.prototype.detach = function () {
  73827. if (!this._attachedCamera) {
  73828. return;
  73829. }
  73830. var scene = this._attachedCamera.getScene();
  73831. if (this._onPrePointerObservableObserver) {
  73832. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73833. }
  73834. if (this._onAfterCheckInputsObserver) {
  73835. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73836. }
  73837. if (this._onMeshTargetChangedObserver) {
  73838. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73839. }
  73840. this._attachedCamera = null;
  73841. };
  73842. /**
  73843. * Targets the given mesh and updates zoom level accordingly.
  73844. * @param mesh The mesh to target.
  73845. * @param radius Optional. If a cached radius position already exists, overrides default.
  73846. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73847. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73848. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73849. */
  73850. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  73851. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73852. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73853. mesh.computeWorldMatrix(true);
  73854. var boundingBox = mesh.getBoundingInfo().boundingBox;
  73855. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  73856. };
  73857. /**
  73858. * Targets the given mesh and updates zoom level accordingly.
  73859. * @param mesh The mesh to target.
  73860. * @param radius Optional. If a cached radius position already exists, overrides default.
  73861. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73862. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73863. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73864. */
  73865. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  73866. var _this = this;
  73867. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73868. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73869. var zoomTarget;
  73870. if (!this._attachedCamera) {
  73871. return;
  73872. }
  73873. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  73874. var bottom = minimumWorld.y;
  73875. var top = maximumWorld.y;
  73876. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  73877. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  73878. if (focusOnOriginXZ) {
  73879. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  73880. }
  73881. else {
  73882. var centerWorld = minimumWorld.add(radiusWorld);
  73883. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  73884. }
  73885. if (!this._vectorTransition) {
  73886. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  73887. }
  73888. this._betaIsAnimating = true;
  73889. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  73890. if (animatable) {
  73891. this._animatables.push(animatable);
  73892. }
  73893. // sets the radius and lower radius bounds
  73894. // Small delta ensures camera is not always at lower zoom limit.
  73895. var radius = 0;
  73896. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  73897. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73898. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  73899. radius = position;
  73900. }
  73901. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73902. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73903. if (this._attachedCamera.lowerRadiusLimit === null) {
  73904. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  73905. }
  73906. }
  73907. // Set sensibilities
  73908. var extend = maximumWorld.subtract(minimumWorld).length();
  73909. this._attachedCamera.panningSensibility = 5000 / extend;
  73910. this._attachedCamera.wheelPrecision = 100 / radius;
  73911. // transition to new radius
  73912. if (!this._radiusTransition) {
  73913. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73914. }
  73915. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  73916. if (onAnimationEnd) {
  73917. onAnimationEnd();
  73918. }
  73919. if (_this._attachedCamera) {
  73920. _this._attachedCamera.storeState();
  73921. }
  73922. });
  73923. if (animatable) {
  73924. this._animatables.push(animatable);
  73925. }
  73926. };
  73927. /**
  73928. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  73929. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  73930. * frustum width.
  73931. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  73932. * to fully enclose the mesh in the viewing frustum.
  73933. */
  73934. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  73935. var size = maximumWorld.subtract(minimumWorld);
  73936. var boxVectorGlobalDiagonal = size.length();
  73937. var frustumSlope = this._getFrustumSlope();
  73938. // Formula for setting distance
  73939. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  73940. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  73941. // Horizon distance
  73942. var radius = radiusWithoutFraming * this._radiusScale;
  73943. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  73944. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  73945. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  73946. var camera = this._attachedCamera;
  73947. if (!camera) {
  73948. return 0;
  73949. }
  73950. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73951. // Don't exceed the requested limit
  73952. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  73953. }
  73954. // Don't exceed the upper radius limit
  73955. if (camera.upperRadiusLimit) {
  73956. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  73957. }
  73958. return distance;
  73959. };
  73960. /**
  73961. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  73962. * is automatically returned to its default position (expected to be above ground plane).
  73963. */
  73964. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  73965. var _this = this;
  73966. if (this._elevationReturnTime < 0) {
  73967. return;
  73968. }
  73969. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  73970. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  73971. var limitBeta = Math.PI * 0.5;
  73972. // Bring the camera back up if below the ground plane
  73973. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  73974. this._betaIsAnimating = true;
  73975. //Transition to new position
  73976. this.stopAllAnimations();
  73977. if (!this._betaTransition) {
  73978. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73979. }
  73980. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  73981. _this._clearAnimationLocks();
  73982. _this.stopAllAnimations();
  73983. });
  73984. if (animatabe) {
  73985. this._animatables.push(animatabe);
  73986. }
  73987. }
  73988. };
  73989. /**
  73990. * Returns the frustum slope based on the canvas ratio and camera FOV
  73991. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  73992. */
  73993. FramingBehavior.prototype._getFrustumSlope = function () {
  73994. // Calculate the viewport ratio
  73995. // Aspect Ratio is Height/Width.
  73996. var camera = this._attachedCamera;
  73997. if (!camera) {
  73998. return BABYLON.Vector2.Zero();
  73999. }
  74000. var engine = camera.getScene().getEngine();
  74001. var aspectRatio = engine.getAspectRatio(camera);
  74002. // Camera FOV is the vertical field of view (top-bottom) in radians.
  74003. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  74004. var frustumSlopeY = Math.tan(camera.fov / 2);
  74005. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  74006. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  74007. // along the forward vector.
  74008. var frustumSlopeX = frustumSlopeY * aspectRatio;
  74009. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  74010. };
  74011. /**
  74012. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  74013. */
  74014. FramingBehavior.prototype._clearAnimationLocks = function () {
  74015. this._betaIsAnimating = false;
  74016. };
  74017. /**
  74018. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74019. */
  74020. FramingBehavior.prototype._applyUserInteraction = function () {
  74021. if (this.isUserIsMoving) {
  74022. this._lastInteractionTime = BABYLON.Tools.Now;
  74023. this.stopAllAnimations();
  74024. this._clearAnimationLocks();
  74025. }
  74026. };
  74027. /**
  74028. * Stops and removes all animations that have been applied to the camera
  74029. */
  74030. FramingBehavior.prototype.stopAllAnimations = function () {
  74031. if (this._attachedCamera) {
  74032. this._attachedCamera.animations = [];
  74033. }
  74034. while (this._animatables.length) {
  74035. if (this._animatables[0]) {
  74036. this._animatables[0].onAnimationEnd = null;
  74037. this._animatables[0].stop();
  74038. }
  74039. this._animatables.shift();
  74040. }
  74041. };
  74042. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  74043. /**
  74044. * Gets a value indicating if the user is moving the camera
  74045. */
  74046. get: function () {
  74047. if (!this._attachedCamera) {
  74048. return false;
  74049. }
  74050. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74051. this._attachedCamera.inertialBetaOffset !== 0 ||
  74052. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74053. this._attachedCamera.inertialPanningX !== 0 ||
  74054. this._attachedCamera.inertialPanningY !== 0 ||
  74055. this._isPointerDown;
  74056. },
  74057. enumerable: true,
  74058. configurable: true
  74059. });
  74060. /**
  74061. * The easing function used by animations
  74062. */
  74063. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  74064. /**
  74065. * The easing mode used by animations
  74066. */
  74067. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  74068. // Statics
  74069. /**
  74070. * The camera can move all the way towards the mesh.
  74071. */
  74072. FramingBehavior.IgnoreBoundsSizeMode = 0;
  74073. /**
  74074. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  74075. */
  74076. FramingBehavior.FitFrustumSidesMode = 1;
  74077. return FramingBehavior;
  74078. }());
  74079. BABYLON.FramingBehavior = FramingBehavior;
  74080. })(BABYLON || (BABYLON = {}));
  74081. //# sourceMappingURL=babylon.framingBehavior.js.map
  74082. var BABYLON;
  74083. (function (BABYLON) {
  74084. /**
  74085. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  74086. */
  74087. var BouncingBehavior = /** @class */ (function () {
  74088. function BouncingBehavior() {
  74089. /**
  74090. * The duration of the animation, in milliseconds
  74091. */
  74092. this.transitionDuration = 450;
  74093. /**
  74094. * Length of the distance animated by the transition when lower radius is reached
  74095. */
  74096. this.lowerRadiusTransitionRange = 2;
  74097. /**
  74098. * Length of the distance animated by the transition when upper radius is reached
  74099. */
  74100. this.upperRadiusTransitionRange = -2;
  74101. this._autoTransitionRange = false;
  74102. // Animations
  74103. this._radiusIsAnimating = false;
  74104. this._radiusBounceTransition = null;
  74105. this._animatables = new Array();
  74106. }
  74107. Object.defineProperty(BouncingBehavior.prototype, "name", {
  74108. get: function () {
  74109. return "Bouncing";
  74110. },
  74111. enumerable: true,
  74112. configurable: true
  74113. });
  74114. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  74115. /**
  74116. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74117. */
  74118. get: function () {
  74119. return this._autoTransitionRange;
  74120. },
  74121. /**
  74122. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74123. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  74124. */
  74125. set: function (value) {
  74126. var _this = this;
  74127. if (this._autoTransitionRange === value) {
  74128. return;
  74129. }
  74130. this._autoTransitionRange = value;
  74131. var camera = this._attachedCamera;
  74132. if (!camera) {
  74133. return;
  74134. }
  74135. if (value) {
  74136. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  74137. if (!mesh) {
  74138. return;
  74139. }
  74140. mesh.computeWorldMatrix(true);
  74141. var diagonal = mesh.getBoundingInfo().diagonalLength;
  74142. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  74143. _this.upperRadiusTransitionRange = diagonal * 0.05;
  74144. });
  74145. }
  74146. else if (this._onMeshTargetChangedObserver) {
  74147. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74148. }
  74149. },
  74150. enumerable: true,
  74151. configurable: true
  74152. });
  74153. BouncingBehavior.prototype.init = function () {
  74154. // Do notihng
  74155. };
  74156. BouncingBehavior.prototype.attach = function (camera) {
  74157. var _this = this;
  74158. this._attachedCamera = camera;
  74159. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74160. if (!_this._attachedCamera) {
  74161. return;
  74162. }
  74163. // Add the bounce animation to the lower radius limit
  74164. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  74165. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  74166. }
  74167. // Add the bounce animation to the upper radius limit
  74168. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  74169. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  74170. }
  74171. });
  74172. };
  74173. BouncingBehavior.prototype.detach = function () {
  74174. if (!this._attachedCamera) {
  74175. return;
  74176. }
  74177. if (this._onAfterCheckInputsObserver) {
  74178. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74179. }
  74180. if (this._onMeshTargetChangedObserver) {
  74181. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74182. }
  74183. this._attachedCamera = null;
  74184. };
  74185. /**
  74186. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  74187. * @param radiusLimit The limit to check against.
  74188. * @return Bool to indicate if at limit.
  74189. */
  74190. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  74191. if (!this._attachedCamera) {
  74192. return false;
  74193. }
  74194. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  74195. return true;
  74196. }
  74197. return false;
  74198. };
  74199. /**
  74200. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  74201. * @param radiusDelta The delta by which to animate to. Can be negative.
  74202. */
  74203. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  74204. var _this = this;
  74205. if (!this._attachedCamera) {
  74206. return;
  74207. }
  74208. if (!this._radiusBounceTransition) {
  74209. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  74210. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  74211. }
  74212. // Prevent zoom until bounce has completed
  74213. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  74214. this._attachedCamera.wheelPrecision = Infinity;
  74215. this._attachedCamera.inertialRadiusOffset = 0;
  74216. // Animate to the radius limit
  74217. this.stopAllAnimations();
  74218. this._radiusIsAnimating = true;
  74219. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  74220. if (animatable) {
  74221. this._animatables.push(animatable);
  74222. }
  74223. };
  74224. /**
  74225. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  74226. */
  74227. BouncingBehavior.prototype._clearAnimationLocks = function () {
  74228. this._radiusIsAnimating = false;
  74229. if (this._attachedCamera) {
  74230. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  74231. }
  74232. };
  74233. /**
  74234. * Stops and removes all animations that have been applied to the camera
  74235. */
  74236. BouncingBehavior.prototype.stopAllAnimations = function () {
  74237. if (this._attachedCamera) {
  74238. this._attachedCamera.animations = [];
  74239. }
  74240. while (this._animatables.length) {
  74241. this._animatables[0].onAnimationEnd = null;
  74242. this._animatables[0].stop();
  74243. this._animatables.shift();
  74244. }
  74245. };
  74246. /**
  74247. * The easing function used by animations
  74248. */
  74249. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  74250. /**
  74251. * The easing mode used by animations
  74252. */
  74253. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  74254. return BouncingBehavior;
  74255. }());
  74256. BABYLON.BouncingBehavior = BouncingBehavior;
  74257. })(BABYLON || (BABYLON = {}));
  74258. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  74259. var BABYLON;
  74260. (function (BABYLON) {
  74261. var AutoRotationBehavior = /** @class */ (function () {
  74262. function AutoRotationBehavior() {
  74263. this._zoomStopsAnimation = false;
  74264. this._idleRotationSpeed = 0.05;
  74265. this._idleRotationWaitTime = 2000;
  74266. this._idleRotationSpinupTime = 2000;
  74267. this._isPointerDown = false;
  74268. this._lastFrameTime = null;
  74269. this._lastInteractionTime = -Infinity;
  74270. this._cameraRotationSpeed = 0;
  74271. this._lastFrameRadius = 0;
  74272. }
  74273. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  74274. get: function () {
  74275. return "AutoRotation";
  74276. },
  74277. enumerable: true,
  74278. configurable: true
  74279. });
  74280. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  74281. /**
  74282. * Gets the flag that indicates if user zooming should stop animation.
  74283. */
  74284. get: function () {
  74285. return this._zoomStopsAnimation;
  74286. },
  74287. /**
  74288. * Sets the flag that indicates if user zooming should stop animation.
  74289. */
  74290. set: function (flag) {
  74291. this._zoomStopsAnimation = flag;
  74292. },
  74293. enumerable: true,
  74294. configurable: true
  74295. });
  74296. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  74297. /**
  74298. * Gets the default speed at which the camera rotates around the model.
  74299. */
  74300. get: function () {
  74301. return this._idleRotationSpeed;
  74302. },
  74303. /**
  74304. * Sets the default speed at which the camera rotates around the model.
  74305. */
  74306. set: function (speed) {
  74307. this._idleRotationSpeed = speed;
  74308. },
  74309. enumerable: true,
  74310. configurable: true
  74311. });
  74312. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  74313. /**
  74314. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  74315. */
  74316. get: function () {
  74317. return this._idleRotationWaitTime;
  74318. },
  74319. /**
  74320. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  74321. */
  74322. set: function (time) {
  74323. this._idleRotationWaitTime = time;
  74324. },
  74325. enumerable: true,
  74326. configurable: true
  74327. });
  74328. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  74329. /**
  74330. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74331. */
  74332. get: function () {
  74333. return this._idleRotationSpinupTime;
  74334. },
  74335. /**
  74336. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74337. */
  74338. set: function (time) {
  74339. this._idleRotationSpinupTime = time;
  74340. },
  74341. enumerable: true,
  74342. configurable: true
  74343. });
  74344. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  74345. /**
  74346. * Gets a value indicating if the camera is currently rotating because of this behavior
  74347. */
  74348. get: function () {
  74349. return Math.abs(this._cameraRotationSpeed) > 0;
  74350. },
  74351. enumerable: true,
  74352. configurable: true
  74353. });
  74354. AutoRotationBehavior.prototype.init = function () {
  74355. // Do notihng
  74356. };
  74357. AutoRotationBehavior.prototype.attach = function (camera) {
  74358. var _this = this;
  74359. this._attachedCamera = camera;
  74360. var scene = this._attachedCamera.getScene();
  74361. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74362. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74363. _this._isPointerDown = true;
  74364. return;
  74365. }
  74366. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74367. _this._isPointerDown = false;
  74368. }
  74369. });
  74370. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74371. var now = BABYLON.Tools.Now;
  74372. var dt = 0;
  74373. if (_this._lastFrameTime != null) {
  74374. dt = now - _this._lastFrameTime;
  74375. }
  74376. _this._lastFrameTime = now;
  74377. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74378. _this._applyUserInteraction();
  74379. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74380. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74381. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74382. // Step camera rotation by rotation speed
  74383. if (_this._attachedCamera) {
  74384. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74385. }
  74386. });
  74387. };
  74388. AutoRotationBehavior.prototype.detach = function () {
  74389. if (!this._attachedCamera) {
  74390. return;
  74391. }
  74392. var scene = this._attachedCamera.getScene();
  74393. if (this._onPrePointerObservableObserver) {
  74394. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74395. }
  74396. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74397. this._attachedCamera = null;
  74398. };
  74399. /**
  74400. * Returns true if user is scrolling.
  74401. * @return true if user is scrolling.
  74402. */
  74403. AutoRotationBehavior.prototype._userIsZooming = function () {
  74404. if (!this._attachedCamera) {
  74405. return false;
  74406. }
  74407. return this._attachedCamera.inertialRadiusOffset !== 0;
  74408. };
  74409. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74410. if (!this._attachedCamera) {
  74411. return false;
  74412. }
  74413. var zoomHasHitLimit = false;
  74414. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74415. zoomHasHitLimit = true;
  74416. }
  74417. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74418. this._lastFrameRadius = this._attachedCamera.radius;
  74419. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74420. };
  74421. /**
  74422. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74423. */
  74424. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74425. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74426. this._lastInteractionTime = BABYLON.Tools.Now;
  74427. }
  74428. };
  74429. // Tools
  74430. AutoRotationBehavior.prototype._userIsMoving = function () {
  74431. if (!this._attachedCamera) {
  74432. return false;
  74433. }
  74434. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74435. this._attachedCamera.inertialBetaOffset !== 0 ||
  74436. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74437. this._attachedCamera.inertialPanningX !== 0 ||
  74438. this._attachedCamera.inertialPanningY !== 0 ||
  74439. this._isPointerDown;
  74440. };
  74441. return AutoRotationBehavior;
  74442. }());
  74443. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74444. })(BABYLON || (BABYLON = {}));
  74445. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74446. var BABYLON;
  74447. (function (BABYLON) {
  74448. /**
  74449. * This class can be used to get instrumentation data from a Babylon engine
  74450. */
  74451. var EngineInstrumentation = /** @class */ (function () {
  74452. function EngineInstrumentation(engine) {
  74453. this.engine = engine;
  74454. this._captureGPUFrameTime = false;
  74455. this._gpuFrameTime = new BABYLON.PerfCounter();
  74456. this._captureShaderCompilationTime = false;
  74457. this._shaderCompilationTime = new BABYLON.PerfCounter();
  74458. // Observers
  74459. this._onBeginFrameObserver = null;
  74460. this._onEndFrameObserver = null;
  74461. this._onBeforeShaderCompilationObserver = null;
  74462. this._onAfterShaderCompilationObserver = null;
  74463. }
  74464. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  74465. // Properties
  74466. /**
  74467. * Gets the perf counter used for GPU frame time
  74468. */
  74469. get: function () {
  74470. return this._gpuFrameTime;
  74471. },
  74472. enumerable: true,
  74473. configurable: true
  74474. });
  74475. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  74476. /**
  74477. * Gets the GPU frame time capture status
  74478. */
  74479. get: function () {
  74480. return this._captureGPUFrameTime;
  74481. },
  74482. /**
  74483. * Enable or disable the GPU frame time capture
  74484. */
  74485. set: function (value) {
  74486. var _this = this;
  74487. if (value === this._captureGPUFrameTime) {
  74488. return;
  74489. }
  74490. this._captureGPUFrameTime = value;
  74491. if (value) {
  74492. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  74493. if (!_this._gpuFrameTimeToken) {
  74494. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  74495. }
  74496. });
  74497. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  74498. if (!_this._gpuFrameTimeToken) {
  74499. return;
  74500. }
  74501. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  74502. if (time > -1) {
  74503. _this._gpuFrameTimeToken = null;
  74504. _this._gpuFrameTime.fetchNewFrame();
  74505. _this._gpuFrameTime.addCount(time, true);
  74506. }
  74507. });
  74508. }
  74509. else {
  74510. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74511. this._onBeginFrameObserver = null;
  74512. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74513. this._onEndFrameObserver = null;
  74514. }
  74515. },
  74516. enumerable: true,
  74517. configurable: true
  74518. });
  74519. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  74520. /**
  74521. * Gets the perf counter used for shader compilation time
  74522. */
  74523. get: function () {
  74524. return this._shaderCompilationTime;
  74525. },
  74526. enumerable: true,
  74527. configurable: true
  74528. });
  74529. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  74530. /**
  74531. * Gets the shader compilation time capture status
  74532. */
  74533. get: function () {
  74534. return this._captureShaderCompilationTime;
  74535. },
  74536. /**
  74537. * Enable or disable the shader compilation time capture
  74538. */
  74539. set: function (value) {
  74540. var _this = this;
  74541. if (value === this._captureShaderCompilationTime) {
  74542. return;
  74543. }
  74544. this._captureShaderCompilationTime = value;
  74545. if (value) {
  74546. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  74547. _this._shaderCompilationTime.fetchNewFrame();
  74548. _this._shaderCompilationTime.beginMonitoring();
  74549. });
  74550. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  74551. _this._shaderCompilationTime.endMonitoring();
  74552. });
  74553. }
  74554. else {
  74555. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74556. this._onBeforeShaderCompilationObserver = null;
  74557. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74558. this._onAfterShaderCompilationObserver = null;
  74559. }
  74560. },
  74561. enumerable: true,
  74562. configurable: true
  74563. });
  74564. EngineInstrumentation.prototype.dispose = function () {
  74565. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74566. this._onBeginFrameObserver = null;
  74567. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74568. this._onEndFrameObserver = null;
  74569. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74570. this._onBeforeShaderCompilationObserver = null;
  74571. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74572. this._onAfterShaderCompilationObserver = null;
  74573. this.engine = null;
  74574. };
  74575. return EngineInstrumentation;
  74576. }());
  74577. BABYLON.EngineInstrumentation = EngineInstrumentation;
  74578. })(BABYLON || (BABYLON = {}));
  74579. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  74580. var BABYLON;
  74581. (function (BABYLON) {
  74582. /**
  74583. * This class can be used to get instrumentation data from a Babylon engine
  74584. */
  74585. var SceneInstrumentation = /** @class */ (function () {
  74586. function SceneInstrumentation(scene) {
  74587. var _this = this;
  74588. this.scene = scene;
  74589. this._captureActiveMeshesEvaluationTime = false;
  74590. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  74591. this._captureRenderTargetsRenderTime = false;
  74592. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  74593. this._captureFrameTime = false;
  74594. this._frameTime = new BABYLON.PerfCounter();
  74595. this._captureRenderTime = false;
  74596. this._renderTime = new BABYLON.PerfCounter();
  74597. this._captureInterFrameTime = false;
  74598. this._interFrameTime = new BABYLON.PerfCounter();
  74599. this._captureParticlesRenderTime = false;
  74600. this._particlesRenderTime = new BABYLON.PerfCounter();
  74601. this._captureSpritesRenderTime = false;
  74602. this._spritesRenderTime = new BABYLON.PerfCounter();
  74603. this._capturePhysicsTime = false;
  74604. this._physicsTime = new BABYLON.PerfCounter();
  74605. this._captureAnimationsTime = false;
  74606. this._animationsTime = new BABYLON.PerfCounter();
  74607. // Observers
  74608. this._onBeforeActiveMeshesEvaluationObserver = null;
  74609. this._onAfterActiveMeshesEvaluationObserver = null;
  74610. this._onBeforeRenderTargetsRenderObserver = null;
  74611. this._onAfterRenderTargetsRenderObserver = null;
  74612. this._onAfterRenderObserver = null;
  74613. this._onBeforeDrawPhaseObserver = null;
  74614. this._onAfterDrawPhaseObserver = null;
  74615. this._onBeforeAnimationsObserver = null;
  74616. this._onBeforeParticlesRenderingObserver = null;
  74617. this._onAfterParticlesRenderingObserver = null;
  74618. this._onBeforeSpritesRenderingObserver = null;
  74619. this._onAfterSpritesRenderingObserver = null;
  74620. this._onBeforePhysicsObserver = null;
  74621. this._onAfterPhysicsObserver = null;
  74622. this._onAfterAnimationsObserver = null;
  74623. // Before render
  74624. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  74625. if (_this._captureActiveMeshesEvaluationTime) {
  74626. _this._activeMeshesEvaluationTime.fetchNewFrame();
  74627. }
  74628. if (_this._captureRenderTargetsRenderTime) {
  74629. _this._renderTargetsRenderTime.fetchNewFrame();
  74630. }
  74631. if (_this._captureFrameTime) {
  74632. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  74633. _this._frameTime.beginMonitoring();
  74634. }
  74635. if (_this._captureInterFrameTime) {
  74636. _this._interFrameTime.endMonitoring();
  74637. }
  74638. if (_this._captureParticlesRenderTime) {
  74639. _this._particlesRenderTime.fetchNewFrame();
  74640. }
  74641. if (_this._captureSpritesRenderTime) {
  74642. _this._spritesRenderTime.fetchNewFrame();
  74643. }
  74644. if (_this._captureAnimationsTime) {
  74645. _this._animationsTime.beginMonitoring();
  74646. }
  74647. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  74648. });
  74649. // After render
  74650. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  74651. if (_this._captureFrameTime) {
  74652. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  74653. _this._frameTime.endMonitoring();
  74654. }
  74655. if (_this._captureRenderTime) {
  74656. _this._renderTime.endMonitoring(false);
  74657. }
  74658. if (_this._captureInterFrameTime) {
  74659. _this._interFrameTime.beginMonitoring();
  74660. }
  74661. });
  74662. }
  74663. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  74664. // Properties
  74665. /**
  74666. * Gets the perf counter used for active meshes evaluation time
  74667. */
  74668. get: function () {
  74669. return this._activeMeshesEvaluationTime;
  74670. },
  74671. enumerable: true,
  74672. configurable: true
  74673. });
  74674. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  74675. /**
  74676. * Gets the active meshes evaluation time capture status
  74677. */
  74678. get: function () {
  74679. return this._captureActiveMeshesEvaluationTime;
  74680. },
  74681. /**
  74682. * Enable or disable the active meshes evaluation time capture
  74683. */
  74684. set: function (value) {
  74685. var _this = this;
  74686. if (value === this._captureActiveMeshesEvaluationTime) {
  74687. return;
  74688. }
  74689. this._captureActiveMeshesEvaluationTime = value;
  74690. if (value) {
  74691. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  74692. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  74693. _this._activeMeshesEvaluationTime.beginMonitoring();
  74694. });
  74695. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  74696. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  74697. _this._activeMeshesEvaluationTime.endMonitoring();
  74698. });
  74699. }
  74700. else {
  74701. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74702. this._onBeforeActiveMeshesEvaluationObserver = null;
  74703. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74704. this._onAfterActiveMeshesEvaluationObserver = null;
  74705. }
  74706. },
  74707. enumerable: true,
  74708. configurable: true
  74709. });
  74710. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  74711. /**
  74712. * Gets the perf counter used for render targets render time
  74713. */
  74714. get: function () {
  74715. return this._renderTargetsRenderTime;
  74716. },
  74717. enumerable: true,
  74718. configurable: true
  74719. });
  74720. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  74721. /**
  74722. * Gets the render targets render time capture status
  74723. */
  74724. get: function () {
  74725. return this._captureRenderTargetsRenderTime;
  74726. },
  74727. /**
  74728. * Enable or disable the render targets render time capture
  74729. */
  74730. set: function (value) {
  74731. var _this = this;
  74732. if (value === this._captureRenderTargetsRenderTime) {
  74733. return;
  74734. }
  74735. this._captureRenderTargetsRenderTime = value;
  74736. if (value) {
  74737. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  74738. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  74739. _this._renderTargetsRenderTime.beginMonitoring();
  74740. });
  74741. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  74742. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  74743. _this._renderTargetsRenderTime.endMonitoring(false);
  74744. });
  74745. }
  74746. else {
  74747. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74748. this._onBeforeRenderTargetsRenderObserver = null;
  74749. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74750. this._onAfterRenderTargetsRenderObserver = null;
  74751. }
  74752. },
  74753. enumerable: true,
  74754. configurable: true
  74755. });
  74756. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  74757. /**
  74758. * Gets the perf counter used for particles render time
  74759. */
  74760. get: function () {
  74761. return this._particlesRenderTime;
  74762. },
  74763. enumerable: true,
  74764. configurable: true
  74765. });
  74766. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  74767. /**
  74768. * Gets the particles render time capture status
  74769. */
  74770. get: function () {
  74771. return this._captureParticlesRenderTime;
  74772. },
  74773. /**
  74774. * Enable or disable the particles render time capture
  74775. */
  74776. set: function (value) {
  74777. var _this = this;
  74778. if (value === this._captureParticlesRenderTime) {
  74779. return;
  74780. }
  74781. this._captureParticlesRenderTime = value;
  74782. if (value) {
  74783. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  74784. BABYLON.Tools.StartPerformanceCounter("Particles");
  74785. _this._particlesRenderTime.beginMonitoring();
  74786. });
  74787. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  74788. BABYLON.Tools.EndPerformanceCounter("Particles");
  74789. _this._particlesRenderTime.endMonitoring(false);
  74790. });
  74791. }
  74792. else {
  74793. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  74794. this._onBeforeParticlesRenderingObserver = null;
  74795. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  74796. this._onAfterParticlesRenderingObserver = null;
  74797. }
  74798. },
  74799. enumerable: true,
  74800. configurable: true
  74801. });
  74802. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  74803. /**
  74804. * Gets the perf counter used for sprites render time
  74805. */
  74806. get: function () {
  74807. return this._spritesRenderTime;
  74808. },
  74809. enumerable: true,
  74810. configurable: true
  74811. });
  74812. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  74813. /**
  74814. * Gets the sprites render time capture status
  74815. */
  74816. get: function () {
  74817. return this._captureSpritesRenderTime;
  74818. },
  74819. /**
  74820. * Enable or disable the sprites render time capture
  74821. */
  74822. set: function (value) {
  74823. var _this = this;
  74824. if (value === this._captureSpritesRenderTime) {
  74825. return;
  74826. }
  74827. this._captureSpritesRenderTime = value;
  74828. if (value) {
  74829. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  74830. BABYLON.Tools.StartPerformanceCounter("Sprites");
  74831. _this._spritesRenderTime.beginMonitoring();
  74832. });
  74833. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  74834. BABYLON.Tools.EndPerformanceCounter("Sprites");
  74835. _this._spritesRenderTime.endMonitoring(false);
  74836. });
  74837. }
  74838. else {
  74839. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  74840. this._onBeforeSpritesRenderingObserver = null;
  74841. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  74842. this._onAfterSpritesRenderingObserver = null;
  74843. }
  74844. },
  74845. enumerable: true,
  74846. configurable: true
  74847. });
  74848. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  74849. /**
  74850. * Gets the perf counter used for physics time
  74851. */
  74852. get: function () {
  74853. return this._physicsTime;
  74854. },
  74855. enumerable: true,
  74856. configurable: true
  74857. });
  74858. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  74859. /**
  74860. * Gets the physics time capture status
  74861. */
  74862. get: function () {
  74863. return this._capturePhysicsTime;
  74864. },
  74865. /**
  74866. * Enable or disable the physics time capture
  74867. */
  74868. set: function (value) {
  74869. var _this = this;
  74870. if (value === this._capturePhysicsTime) {
  74871. return;
  74872. }
  74873. this._capturePhysicsTime = value;
  74874. if (value) {
  74875. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  74876. BABYLON.Tools.StartPerformanceCounter("Physics");
  74877. _this._physicsTime.beginMonitoring();
  74878. });
  74879. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  74880. BABYLON.Tools.EndPerformanceCounter("Physics");
  74881. _this._physicsTime.endMonitoring();
  74882. });
  74883. }
  74884. else {
  74885. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  74886. this._onBeforePhysicsObserver = null;
  74887. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  74888. this._onAfterPhysicsObserver = null;
  74889. }
  74890. },
  74891. enumerable: true,
  74892. configurable: true
  74893. });
  74894. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  74895. /**
  74896. * Gets the perf counter used for animations time
  74897. */
  74898. get: function () {
  74899. return this._animationsTime;
  74900. },
  74901. enumerable: true,
  74902. configurable: true
  74903. });
  74904. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  74905. /**
  74906. * Gets the animations time capture status
  74907. */
  74908. get: function () {
  74909. return this._captureAnimationsTime;
  74910. },
  74911. /**
  74912. * Enable or disable the animations time capture
  74913. */
  74914. set: function (value) {
  74915. var _this = this;
  74916. if (value === this._captureAnimationsTime) {
  74917. return;
  74918. }
  74919. this._captureAnimationsTime = value;
  74920. if (value) {
  74921. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  74922. _this._animationsTime.endMonitoring();
  74923. });
  74924. }
  74925. else {
  74926. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  74927. this._onAfterAnimationsObserver = null;
  74928. }
  74929. },
  74930. enumerable: true,
  74931. configurable: true
  74932. });
  74933. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  74934. /**
  74935. * Gets the perf counter used for frame time capture
  74936. */
  74937. get: function () {
  74938. return this._frameTime;
  74939. },
  74940. enumerable: true,
  74941. configurable: true
  74942. });
  74943. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  74944. /**
  74945. * Gets the frame time capture status
  74946. */
  74947. get: function () {
  74948. return this._captureFrameTime;
  74949. },
  74950. /**
  74951. * Enable or disable the frame time capture
  74952. */
  74953. set: function (value) {
  74954. this._captureFrameTime = value;
  74955. },
  74956. enumerable: true,
  74957. configurable: true
  74958. });
  74959. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  74960. /**
  74961. * Gets the perf counter used for inter-frames time capture
  74962. */
  74963. get: function () {
  74964. return this._interFrameTime;
  74965. },
  74966. enumerable: true,
  74967. configurable: true
  74968. });
  74969. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  74970. /**
  74971. * Gets the inter-frames time capture status
  74972. */
  74973. get: function () {
  74974. return this._captureInterFrameTime;
  74975. },
  74976. /**
  74977. * Enable or disable the inter-frames time capture
  74978. */
  74979. set: function (value) {
  74980. this._captureInterFrameTime = value;
  74981. },
  74982. enumerable: true,
  74983. configurable: true
  74984. });
  74985. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  74986. /**
  74987. * Gets the perf counter used for render time capture
  74988. */
  74989. get: function () {
  74990. return this._renderTime;
  74991. },
  74992. enumerable: true,
  74993. configurable: true
  74994. });
  74995. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  74996. /**
  74997. * Gets the render time capture status
  74998. */
  74999. get: function () {
  75000. return this._captureRenderTime;
  75001. },
  75002. /**
  75003. * Enable or disable the render time capture
  75004. */
  75005. set: function (value) {
  75006. var _this = this;
  75007. if (value === this._captureRenderTime) {
  75008. return;
  75009. }
  75010. this._captureRenderTime = value;
  75011. if (value) {
  75012. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  75013. _this._renderTime.beginMonitoring();
  75014. BABYLON.Tools.StartPerformanceCounter("Main render");
  75015. });
  75016. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  75017. _this._renderTime.endMonitoring(false);
  75018. BABYLON.Tools.EndPerformanceCounter("Main render");
  75019. });
  75020. }
  75021. else {
  75022. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  75023. this._onBeforeDrawPhaseObserver = null;
  75024. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  75025. this._onAfterDrawPhaseObserver = null;
  75026. }
  75027. },
  75028. enumerable: true,
  75029. configurable: true
  75030. });
  75031. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  75032. /**
  75033. * Gets the perf counter used for frame time capture
  75034. */
  75035. get: function () {
  75036. return this.scene.getEngine()._drawCalls;
  75037. },
  75038. enumerable: true,
  75039. configurable: true
  75040. });
  75041. SceneInstrumentation.prototype.dispose = function () {
  75042. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75043. this._onAfterRenderObserver = null;
  75044. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  75045. this._onBeforeActiveMeshesEvaluationObserver = null;
  75046. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  75047. this._onAfterActiveMeshesEvaluationObserver = null;
  75048. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  75049. this._onBeforeRenderTargetsRenderObserver = null;
  75050. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  75051. this._onAfterRenderTargetsRenderObserver = null;
  75052. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  75053. this._onBeforeAnimationsObserver = null;
  75054. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  75055. this._onBeforeParticlesRenderingObserver = null;
  75056. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  75057. this._onAfterParticlesRenderingObserver = null;
  75058. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  75059. this._onBeforeSpritesRenderingObserver = null;
  75060. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  75061. this._onAfterSpritesRenderingObserver = null;
  75062. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  75063. this._onBeforeDrawPhaseObserver = null;
  75064. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  75065. this._onAfterDrawPhaseObserver = null;
  75066. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  75067. this._onBeforePhysicsObserver = null;
  75068. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  75069. this._onAfterPhysicsObserver = null;
  75070. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  75071. this._onAfterAnimationsObserver = null;
  75072. this.scene = null;
  75073. };
  75074. return SceneInstrumentation;
  75075. }());
  75076. BABYLON.SceneInstrumentation = SceneInstrumentation;
  75077. })(BABYLON || (BABYLON = {}));
  75078. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  75079. var BABYLON;
  75080. (function (BABYLON) {
  75081. var _TimeToken = /** @class */ (function () {
  75082. function _TimeToken() {
  75083. this._timeElapsedQueryEnded = false;
  75084. }
  75085. return _TimeToken;
  75086. }());
  75087. BABYLON._TimeToken = _TimeToken;
  75088. })(BABYLON || (BABYLON = {}));
  75089. //# sourceMappingURL=babylon.timeToken.js.map
  75090. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  75091. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  75092. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75093. var BABYLON;
  75094. (function (BABYLON) {
  75095. var GridMaterialDefines = /** @class */ (function (_super) {
  75096. __extends(GridMaterialDefines, _super);
  75097. function GridMaterialDefines() {
  75098. var _this = _super.call(this) || this;
  75099. _this.TRANSPARENT = false;
  75100. _this.FOG = false;
  75101. _this.PREMULTIPLYALPHA = false;
  75102. _this.rebuild();
  75103. return _this;
  75104. }
  75105. return GridMaterialDefines;
  75106. }(BABYLON.MaterialDefines));
  75107. /**
  75108. * The grid materials allows you to wrap any shape with a grid.
  75109. * Colors are customizable.
  75110. */
  75111. var GridMaterial = /** @class */ (function (_super) {
  75112. __extends(GridMaterial, _super);
  75113. /**
  75114. * constructor
  75115. * @param name The name given to the material in order to identify it afterwards.
  75116. * @param scene The scene the material is used in.
  75117. */
  75118. function GridMaterial(name, scene) {
  75119. var _this = _super.call(this, name, scene) || this;
  75120. /**
  75121. * Main color of the grid (e.g. between lines)
  75122. */
  75123. _this.mainColor = BABYLON.Color3.Black();
  75124. /**
  75125. * Color of the grid lines.
  75126. */
  75127. _this.lineColor = BABYLON.Color3.Teal();
  75128. /**
  75129. * The scale of the grid compared to unit.
  75130. */
  75131. _this.gridRatio = 1.0;
  75132. /**
  75133. * Allows setting an offset for the grid lines.
  75134. */
  75135. _this.gridOffset = BABYLON.Vector3.Zero();
  75136. /**
  75137. * The frequency of thicker lines.
  75138. */
  75139. _this.majorUnitFrequency = 10;
  75140. /**
  75141. * The visibility of minor units in the grid.
  75142. */
  75143. _this.minorUnitVisibility = 0.33;
  75144. /**
  75145. * The grid opacity outside of the lines.
  75146. */
  75147. _this.opacity = 1.0;
  75148. /**
  75149. * Determine RBG output is premultiplied by alpha value.
  75150. */
  75151. _this.preMultiplyAlpha = false;
  75152. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  75153. return _this;
  75154. }
  75155. /**
  75156. * Returns wehter or not the grid requires alpha blending.
  75157. */
  75158. GridMaterial.prototype.needAlphaBlending = function () {
  75159. return this.opacity < 1.0;
  75160. };
  75161. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75162. if (this.isFrozen) {
  75163. if (this._wasPreviouslyReady && subMesh.effect) {
  75164. return true;
  75165. }
  75166. }
  75167. if (!subMesh._materialDefines) {
  75168. subMesh._materialDefines = new GridMaterialDefines();
  75169. }
  75170. var defines = subMesh._materialDefines;
  75171. var scene = this.getScene();
  75172. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  75173. if (this._renderId === scene.getRenderId()) {
  75174. return true;
  75175. }
  75176. }
  75177. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  75178. defines.TRANSPARENT = !defines.TRANSPARENT;
  75179. defines.markAsUnprocessed();
  75180. }
  75181. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  75182. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  75183. defines.markAsUnprocessed();
  75184. }
  75185. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  75186. // Get correct effect
  75187. if (defines.isDirty) {
  75188. defines.markAsProcessed();
  75189. scene.resetCachedMaterial();
  75190. // Attributes
  75191. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75192. // Defines
  75193. var join = defines.toString();
  75194. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  75195. }
  75196. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75197. return false;
  75198. }
  75199. this._renderId = scene.getRenderId();
  75200. this._wasPreviouslyReady = true;
  75201. return true;
  75202. };
  75203. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75204. var scene = this.getScene();
  75205. var defines = subMesh._materialDefines;
  75206. if (!defines) {
  75207. return;
  75208. }
  75209. var effect = subMesh.effect;
  75210. if (!effect) {
  75211. return;
  75212. }
  75213. this._activeEffect = effect;
  75214. // Matrices
  75215. this.bindOnlyWorldMatrix(world);
  75216. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  75217. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  75218. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  75219. // Uniforms
  75220. if (this._mustRebind(scene, effect)) {
  75221. this._activeEffect.setColor3("mainColor", this.mainColor);
  75222. this._activeEffect.setColor3("lineColor", this.lineColor);
  75223. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  75224. this._gridControl.x = this.gridRatio;
  75225. this._gridControl.y = Math.round(this.majorUnitFrequency);
  75226. this._gridControl.z = this.minorUnitVisibility;
  75227. this._gridControl.w = this.opacity;
  75228. this._activeEffect.setVector4("gridControl", this._gridControl);
  75229. }
  75230. // Fog
  75231. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75232. this._afterBind(mesh, this._activeEffect);
  75233. };
  75234. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  75235. _super.prototype.dispose.call(this, forceDisposeEffect);
  75236. };
  75237. GridMaterial.prototype.clone = function (name) {
  75238. var _this = this;
  75239. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  75240. };
  75241. GridMaterial.prototype.serialize = function () {
  75242. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75243. serializationObject.customType = "BABYLON.GridMaterial";
  75244. return serializationObject;
  75245. };
  75246. GridMaterial.prototype.getClassName = function () {
  75247. return "GridMaterial";
  75248. };
  75249. GridMaterial.Parse = function (source, scene, rootUrl) {
  75250. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  75251. };
  75252. __decorate([
  75253. BABYLON.serializeAsColor3()
  75254. ], GridMaterial.prototype, "mainColor", void 0);
  75255. __decorate([
  75256. BABYLON.serializeAsColor3()
  75257. ], GridMaterial.prototype, "lineColor", void 0);
  75258. __decorate([
  75259. BABYLON.serialize()
  75260. ], GridMaterial.prototype, "gridRatio", void 0);
  75261. __decorate([
  75262. BABYLON.serializeAsColor3()
  75263. ], GridMaterial.prototype, "gridOffset", void 0);
  75264. __decorate([
  75265. BABYLON.serialize()
  75266. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  75267. __decorate([
  75268. BABYLON.serialize()
  75269. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  75270. __decorate([
  75271. BABYLON.serialize()
  75272. ], GridMaterial.prototype, "opacity", void 0);
  75273. __decorate([
  75274. BABYLON.serialize()
  75275. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  75276. return GridMaterial;
  75277. }(BABYLON.PushMaterial));
  75278. BABYLON.GridMaterial = GridMaterial;
  75279. })(BABYLON || (BABYLON = {}));
  75280. //# sourceMappingURL=babylon.gridmaterial.js.map
  75281. 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}";
  75282. 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}";
  75283. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75284. var BABYLON;
  75285. (function (BABYLON) {
  75286. /**
  75287. * Background material defines definition.
  75288. */
  75289. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  75290. __extends(BackgroundMaterialDefines, _super);
  75291. /**
  75292. * Constructor of the defines.
  75293. */
  75294. function BackgroundMaterialDefines() {
  75295. var _this = _super.call(this) || this;
  75296. /**
  75297. * True if the diffuse texture is in use.
  75298. */
  75299. _this.DIFFUSE = false;
  75300. /**
  75301. * The direct UV channel to use.
  75302. */
  75303. _this.DIFFUSEDIRECTUV = 0;
  75304. /**
  75305. * True if the diffuse texture is in gamma space.
  75306. */
  75307. _this.GAMMADIFFUSE = false;
  75308. /**
  75309. * True if the diffuse texture has opacity in the alpha channel.
  75310. */
  75311. _this.DIFFUSEHASALPHA = false;
  75312. /**
  75313. * True if you want the material to fade to transparent at grazing angle.
  75314. */
  75315. _this.OPACITYFRESNEL = false;
  75316. /**
  75317. * True if an extra blur needs to be added in the reflection.
  75318. */
  75319. _this.REFLECTIONBLUR = false;
  75320. /**
  75321. * True if you want the material to fade to reflection at grazing angle.
  75322. */
  75323. _this.REFLECTIONFRESNEL = false;
  75324. /**
  75325. * True if you want the material to falloff as far as you move away from the scene center.
  75326. */
  75327. _this.REFLECTIONFALLOFF = false;
  75328. /**
  75329. * False if the current Webgl implementation does not support the texture lod extension.
  75330. */
  75331. _this.TEXTURELODSUPPORT = false;
  75332. /**
  75333. * True to ensure the data are premultiplied.
  75334. */
  75335. _this.PREMULTIPLYALPHA = false;
  75336. /**
  75337. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  75338. */
  75339. _this.USERGBCOLOR = false;
  75340. // Image Processing Configuration.
  75341. _this.IMAGEPROCESSING = false;
  75342. _this.VIGNETTE = false;
  75343. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  75344. _this.VIGNETTEBLENDMODEOPAQUE = false;
  75345. _this.TONEMAPPING = false;
  75346. _this.CONTRAST = false;
  75347. _this.COLORCURVES = false;
  75348. _this.COLORGRADING = false;
  75349. _this.COLORGRADING3D = false;
  75350. _this.SAMPLER3DGREENDEPTH = false;
  75351. _this.SAMPLER3DBGRMAP = false;
  75352. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  75353. _this.EXPOSURE = false;
  75354. // Reflection.
  75355. _this.REFLECTION = false;
  75356. _this.REFLECTIONMAP_3D = false;
  75357. _this.REFLECTIONMAP_SPHERICAL = false;
  75358. _this.REFLECTIONMAP_PLANAR = false;
  75359. _this.REFLECTIONMAP_CUBIC = false;
  75360. _this.REFLECTIONMAP_PROJECTION = false;
  75361. _this.REFLECTIONMAP_SKYBOX = false;
  75362. _this.REFLECTIONMAP_EXPLICIT = false;
  75363. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75364. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75365. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75366. _this.INVERTCUBICMAP = false;
  75367. _this.REFLECTIONMAP_OPPOSITEZ = false;
  75368. _this.LODINREFLECTIONALPHA = false;
  75369. _this.GAMMAREFLECTION = false;
  75370. // Default BJS.
  75371. _this.MAINUV1 = false;
  75372. _this.MAINUV2 = false;
  75373. _this.UV1 = false;
  75374. _this.UV2 = false;
  75375. _this.CLIPPLANE = false;
  75376. _this.POINTSIZE = false;
  75377. _this.FOG = false;
  75378. _this.NORMAL = false;
  75379. _this.NUM_BONE_INFLUENCERS = 0;
  75380. _this.BonesPerMesh = 0;
  75381. _this.INSTANCES = false;
  75382. _this.SHADOWFLOAT = false;
  75383. _this.rebuild();
  75384. return _this;
  75385. }
  75386. return BackgroundMaterialDefines;
  75387. }(BABYLON.MaterialDefines));
  75388. /**
  75389. * Background material
  75390. */
  75391. var BackgroundMaterial = /** @class */ (function (_super) {
  75392. __extends(BackgroundMaterial, _super);
  75393. /**
  75394. * constructor
  75395. * @param name The name of the material
  75396. * @param scene The scene to add the material to
  75397. */
  75398. function BackgroundMaterial(name, scene) {
  75399. var _this = _super.call(this, name, scene) || this;
  75400. _this.primaryColor = BABYLON.Color3.White();
  75401. _this.primaryLevel = 1;
  75402. _this.secondaryColor = BABYLON.Color3.Gray();
  75403. _this.secondaryLevel = 1;
  75404. _this.tertiaryColor = BABYLON.Color3.Black();
  75405. _this.tertiaryLevel = 1;
  75406. _this.reflectionTexture = null;
  75407. _this.reflectionBlur = 0;
  75408. _this.diffuseTexture = null;
  75409. /**
  75410. * Specify the list of lights casting shadow on the material.
  75411. * All scene shadow lights will be included if null.
  75412. */
  75413. _this._shadowLights = null;
  75414. _this.shadowLights = null;
  75415. _this.shadowBlurScale = 1;
  75416. _this.shadowLevel = 0;
  75417. _this.sceneCenter = BABYLON.Vector3.Zero();
  75418. _this.opacityFresnel = true;
  75419. _this.reflectionFresnel = false;
  75420. _this.reflectionFalloffDistance = 0.0;
  75421. _this.reflectionAmount = 1.0;
  75422. _this.reflectionReflectance0 = 0.05;
  75423. _this.reflectionReflectance90 = 0.5;
  75424. _this.useRGBColor = true;
  75425. /**
  75426. * Number of Simultaneous lights allowed on the material.
  75427. */
  75428. _this._maxSimultaneousLights = 4;
  75429. _this.maxSimultaneousLights = 4;
  75430. /**
  75431. * Keep track of the image processing observer to allow dispose and replace.
  75432. */
  75433. _this._imageProcessingObserver = null;
  75434. // Temp values kept as cache in the material.
  75435. _this._renderTargets = new BABYLON.SmartArray(16);
  75436. _this._reflectionControls = BABYLON.Vector4.Zero();
  75437. // Setup the default processing configuration to the scene.
  75438. _this._attachImageProcessingConfiguration(null);
  75439. _this.getRenderTargetTextures = function () {
  75440. _this._renderTargets.reset();
  75441. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  75442. _this._renderTargets.push(_this._diffuseTexture);
  75443. }
  75444. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  75445. _this._renderTargets.push(_this._reflectionTexture);
  75446. }
  75447. return _this._renderTargets;
  75448. };
  75449. return _this;
  75450. }
  75451. /**
  75452. * Attaches a new image processing configuration to the PBR Material.
  75453. * @param configuration (if null the scene configuration will be use)
  75454. */
  75455. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  75456. var _this = this;
  75457. if (configuration === this._imageProcessingConfiguration) {
  75458. return;
  75459. }
  75460. // Detaches observer.
  75461. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75462. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75463. }
  75464. // Pick the scene configuration if needed.
  75465. if (!configuration) {
  75466. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  75467. }
  75468. else {
  75469. this._imageProcessingConfiguration = configuration;
  75470. }
  75471. // Attaches observer.
  75472. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75473. _this._markAllSubMeshesAsImageProcessingDirty();
  75474. });
  75475. };
  75476. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  75477. /**
  75478. * Gets the image processing configuration used either in this material.
  75479. */
  75480. get: function () {
  75481. return this._imageProcessingConfiguration;
  75482. },
  75483. /**
  75484. * Sets the Default image processing configuration used either in the this material.
  75485. *
  75486. * If sets to null, the scene one is in use.
  75487. */
  75488. set: function (value) {
  75489. this._attachImageProcessingConfiguration(value);
  75490. // Ensure the effect will be rebuilt.
  75491. this._markAllSubMeshesAsTexturesDirty();
  75492. },
  75493. enumerable: true,
  75494. configurable: true
  75495. });
  75496. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  75497. /**
  75498. * Gets wether the color curves effect is enabled.
  75499. */
  75500. get: function () {
  75501. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75502. },
  75503. /**
  75504. * Sets wether the color curves effect is enabled.
  75505. */
  75506. set: function (value) {
  75507. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75508. },
  75509. enumerable: true,
  75510. configurable: true
  75511. });
  75512. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  75513. /**
  75514. * Gets wether the color grading effect is enabled.
  75515. */
  75516. get: function () {
  75517. return this.imageProcessingConfiguration.colorGradingEnabled;
  75518. },
  75519. /**
  75520. * Gets wether the color grading effect is enabled.
  75521. */
  75522. set: function (value) {
  75523. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75524. },
  75525. enumerable: true,
  75526. configurable: true
  75527. });
  75528. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  75529. /**
  75530. * Gets wether tonemapping is enabled or not.
  75531. */
  75532. get: function () {
  75533. return this._imageProcessingConfiguration.toneMappingEnabled;
  75534. },
  75535. /**
  75536. * Sets wether tonemapping is enabled or not
  75537. */
  75538. set: function (value) {
  75539. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75540. },
  75541. enumerable: true,
  75542. configurable: true
  75543. });
  75544. ;
  75545. ;
  75546. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  75547. /**
  75548. * The camera exposure used on this material.
  75549. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75550. * This corresponds to a photographic exposure.
  75551. */
  75552. get: function () {
  75553. return this._imageProcessingConfiguration.exposure;
  75554. },
  75555. /**
  75556. * The camera exposure used on this material.
  75557. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75558. * This corresponds to a photographic exposure.
  75559. */
  75560. set: function (value) {
  75561. this._imageProcessingConfiguration.exposure = value;
  75562. },
  75563. enumerable: true,
  75564. configurable: true
  75565. });
  75566. ;
  75567. ;
  75568. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  75569. /**
  75570. * Gets The camera contrast used on this material.
  75571. */
  75572. get: function () {
  75573. return this._imageProcessingConfiguration.contrast;
  75574. },
  75575. /**
  75576. * Sets The camera contrast used on this material.
  75577. */
  75578. set: function (value) {
  75579. this._imageProcessingConfiguration.contrast = value;
  75580. },
  75581. enumerable: true,
  75582. configurable: true
  75583. });
  75584. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  75585. /**
  75586. * Gets the Color Grading 2D Lookup Texture.
  75587. */
  75588. get: function () {
  75589. return this._imageProcessingConfiguration.colorGradingTexture;
  75590. },
  75591. /**
  75592. * Sets the Color Grading 2D Lookup Texture.
  75593. */
  75594. set: function (value) {
  75595. this.imageProcessingConfiguration.colorGradingTexture = value;
  75596. },
  75597. enumerable: true,
  75598. configurable: true
  75599. });
  75600. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  75601. /**
  75602. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75603. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75604. * 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;
  75605. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75606. */
  75607. get: function () {
  75608. return this.imageProcessingConfiguration.colorCurves;
  75609. },
  75610. /**
  75611. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75612. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75613. * 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;
  75614. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75615. */
  75616. set: function (value) {
  75617. this.imageProcessingConfiguration.colorCurves = value;
  75618. },
  75619. enumerable: true,
  75620. configurable: true
  75621. });
  75622. /**
  75623. * The entire material has been created in order to prevent overdraw.
  75624. * @returns false
  75625. */
  75626. BackgroundMaterial.prototype.needAlphaTesting = function () {
  75627. return false;
  75628. };
  75629. /**
  75630. * The entire material has been created in order to prevent overdraw.
  75631. * @returns true if blending is enable
  75632. */
  75633. BackgroundMaterial.prototype.needAlphaBlending = function () {
  75634. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  75635. };
  75636. /**
  75637. * Checks wether the material is ready to be rendered for a given mesh.
  75638. * @param mesh The mesh to render
  75639. * @param subMesh The submesh to check against
  75640. * @param useInstances Specify wether or not the material is used with instances
  75641. */
  75642. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75643. var _this = this;
  75644. if (useInstances === void 0) { useInstances = false; }
  75645. if (subMesh.effect && this.isFrozen) {
  75646. if (this._wasPreviouslyReady) {
  75647. return true;
  75648. }
  75649. }
  75650. if (!subMesh._materialDefines) {
  75651. subMesh._materialDefines = new BackgroundMaterialDefines();
  75652. }
  75653. var scene = this.getScene();
  75654. var defines = subMesh._materialDefines;
  75655. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  75656. if (defines._renderId === scene.getRenderId()) {
  75657. return true;
  75658. }
  75659. }
  75660. var engine = scene.getEngine();
  75661. // Lights
  75662. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  75663. defines._needNormals = true;
  75664. // Textures
  75665. if (defines._areTexturesDirty) {
  75666. defines._needUVs = false;
  75667. if (scene.texturesEnabled) {
  75668. if (scene.getEngine().getCaps().textureLOD) {
  75669. defines.TEXTURELODSUPPORT = true;
  75670. }
  75671. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75672. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  75673. return false;
  75674. }
  75675. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  75676. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  75677. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  75678. defines.OPACITYFRESNEL = this._opacityFresnel;
  75679. }
  75680. else {
  75681. defines.DIFFUSE = false;
  75682. defines.DIFFUSEHASALPHA = false;
  75683. defines.GAMMADIFFUSE = false;
  75684. defines.OPACITYFRESNEL = false;
  75685. }
  75686. var reflectionTexture = this._reflectionTexture;
  75687. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75688. if (!reflectionTexture.isReadyOrNotBlocking()) {
  75689. return false;
  75690. }
  75691. defines.REFLECTION = true;
  75692. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  75693. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  75694. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  75695. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  75696. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  75697. defines.INVERTCUBICMAP = true;
  75698. }
  75699. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  75700. switch (reflectionTexture.coordinatesMode) {
  75701. case BABYLON.Texture.CUBIC_MODE:
  75702. case BABYLON.Texture.INVCUBIC_MODE:
  75703. defines.REFLECTIONMAP_CUBIC = true;
  75704. break;
  75705. case BABYLON.Texture.EXPLICIT_MODE:
  75706. defines.REFLECTIONMAP_EXPLICIT = true;
  75707. break;
  75708. case BABYLON.Texture.PLANAR_MODE:
  75709. defines.REFLECTIONMAP_PLANAR = true;
  75710. break;
  75711. case BABYLON.Texture.PROJECTION_MODE:
  75712. defines.REFLECTIONMAP_PROJECTION = true;
  75713. break;
  75714. case BABYLON.Texture.SKYBOX_MODE:
  75715. defines.REFLECTIONMAP_SKYBOX = true;
  75716. break;
  75717. case BABYLON.Texture.SPHERICAL_MODE:
  75718. defines.REFLECTIONMAP_SPHERICAL = true;
  75719. break;
  75720. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  75721. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  75722. break;
  75723. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  75724. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  75725. break;
  75726. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  75727. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  75728. break;
  75729. }
  75730. if (this.reflectionFresnel) {
  75731. defines.REFLECTIONFRESNEL = true;
  75732. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  75733. this._reflectionControls.x = this.reflectionAmount;
  75734. this._reflectionControls.y = this.reflectionReflectance0;
  75735. this._reflectionControls.z = this.reflectionReflectance90;
  75736. this._reflectionControls.w = this.reflectionFalloffDistance;
  75737. }
  75738. else {
  75739. defines.REFLECTIONFRESNEL = false;
  75740. defines.REFLECTIONFALLOFF = false;
  75741. }
  75742. }
  75743. else {
  75744. defines.REFLECTION = false;
  75745. defines.REFLECTIONFALLOFF = false;
  75746. defines.REFLECTIONBLUR = false;
  75747. defines.REFLECTIONMAP_3D = false;
  75748. defines.REFLECTIONMAP_SPHERICAL = false;
  75749. defines.REFLECTIONMAP_PLANAR = false;
  75750. defines.REFLECTIONMAP_CUBIC = false;
  75751. defines.REFLECTIONMAP_PROJECTION = false;
  75752. defines.REFLECTIONMAP_SKYBOX = false;
  75753. defines.REFLECTIONMAP_EXPLICIT = false;
  75754. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75755. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75756. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75757. defines.INVERTCUBICMAP = false;
  75758. defines.REFLECTIONMAP_OPPOSITEZ = false;
  75759. defines.LODINREFLECTIONALPHA = false;
  75760. defines.GAMMAREFLECTION = false;
  75761. }
  75762. }
  75763. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  75764. defines.USERGBCOLOR = this._useRGBColor;
  75765. }
  75766. if (defines._areImageProcessingDirty) {
  75767. if (!this._imageProcessingConfiguration.isReady()) {
  75768. return false;
  75769. }
  75770. this._imageProcessingConfiguration.prepareDefines(defines);
  75771. }
  75772. // Misc.
  75773. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  75774. // Values that need to be evaluated on every frame
  75775. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  75776. // Attribs
  75777. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  75778. if (mesh) {
  75779. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75780. mesh.createNormals(true);
  75781. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  75782. }
  75783. }
  75784. }
  75785. // Get correct effect
  75786. if (defines.isDirty) {
  75787. defines.markAsProcessed();
  75788. scene.resetCachedMaterial();
  75789. // Fallbacks
  75790. var fallbacks = new BABYLON.EffectFallbacks();
  75791. if (defines.FOG) {
  75792. fallbacks.addFallback(0, "FOG");
  75793. }
  75794. if (defines.POINTSIZE) {
  75795. fallbacks.addFallback(1, "POINTSIZE");
  75796. }
  75797. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  75798. if (defines.NUM_BONE_INFLUENCERS > 0) {
  75799. fallbacks.addCPUSkinningFallback(0, mesh);
  75800. }
  75801. //Attributes
  75802. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75803. if (defines.NORMAL) {
  75804. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75805. }
  75806. if (defines.UV1) {
  75807. attribs.push(BABYLON.VertexBuffer.UVKind);
  75808. }
  75809. if (defines.UV2) {
  75810. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75811. }
  75812. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  75813. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  75814. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  75815. "vFogInfos", "vFogColor", "pointSize",
  75816. "vClipPlane", "mBones",
  75817. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  75818. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  75819. "shadowLevel", "alpha",
  75820. "vBackgroundCenter", "vReflectionControl",
  75821. "vDiffuseInfos", "diffuseMatrix",
  75822. ];
  75823. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  75824. var uniformBuffers = ["Material", "Scene"];
  75825. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  75826. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  75827. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  75828. uniformsNames: uniforms,
  75829. uniformBuffersNames: uniformBuffers,
  75830. samplers: samplers,
  75831. defines: defines,
  75832. maxSimultaneousLights: this._maxSimultaneousLights
  75833. });
  75834. var onCompiled = function (effect) {
  75835. if (_this.onCompiled) {
  75836. _this.onCompiled(effect);
  75837. }
  75838. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  75839. };
  75840. var join = defines.toString();
  75841. subMesh.setEffect(scene.getEngine().createEffect("background", {
  75842. attributes: attribs,
  75843. uniformsNames: uniforms,
  75844. uniformBuffersNames: uniformBuffers,
  75845. samplers: samplers,
  75846. defines: join,
  75847. fallbacks: fallbacks,
  75848. onCompiled: onCompiled,
  75849. onError: this.onError,
  75850. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  75851. }, engine), defines);
  75852. this.buildUniformLayout();
  75853. }
  75854. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75855. return false;
  75856. }
  75857. defines._renderId = scene.getRenderId();
  75858. this._wasPreviouslyReady = true;
  75859. return true;
  75860. };
  75861. /**
  75862. * Build the uniform buffer used in the material.
  75863. */
  75864. BackgroundMaterial.prototype.buildUniformLayout = function () {
  75865. // Order is important !
  75866. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  75867. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  75868. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  75869. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  75870. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  75871. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  75872. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  75873. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  75874. this._uniformBuffer.addUniform("pointSize", 1);
  75875. this._uniformBuffer.addUniform("shadowLevel", 1);
  75876. this._uniformBuffer.addUniform("alpha", 1);
  75877. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  75878. this._uniformBuffer.addUniform("vReflectionControl", 4);
  75879. this._uniformBuffer.create();
  75880. };
  75881. /**
  75882. * Unbind the material.
  75883. */
  75884. BackgroundMaterial.prototype.unbind = function () {
  75885. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  75886. this._uniformBuffer.setTexture("diffuseSampler", null);
  75887. }
  75888. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  75889. this._uniformBuffer.setTexture("reflectionSampler", null);
  75890. }
  75891. _super.prototype.unbind.call(this);
  75892. };
  75893. /**
  75894. * Bind only the world matrix to the material.
  75895. * @param world The world matrix to bind.
  75896. */
  75897. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  75898. this._activeEffect.setMatrix("world", world);
  75899. };
  75900. /**
  75901. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  75902. * @param world The world matrix to bind.
  75903. * @param subMesh The submesh to bind for.
  75904. */
  75905. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75906. var scene = this.getScene();
  75907. var defines = subMesh._materialDefines;
  75908. if (!defines) {
  75909. return;
  75910. }
  75911. var effect = subMesh.effect;
  75912. if (!effect) {
  75913. return;
  75914. }
  75915. this._activeEffect = effect;
  75916. // Matrices
  75917. this.bindOnlyWorldMatrix(world);
  75918. // Bones
  75919. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  75920. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  75921. if (mustRebind) {
  75922. this._uniformBuffer.bindToEffect(effect, "Material");
  75923. this.bindViewProjection(effect);
  75924. var reflectionTexture = this._reflectionTexture;
  75925. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  75926. // Texture uniforms
  75927. if (scene.texturesEnabled) {
  75928. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75929. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  75930. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  75931. }
  75932. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75933. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  75934. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  75935. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  75936. }
  75937. }
  75938. if (this.shadowLevel > 0) {
  75939. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  75940. }
  75941. this._uniformBuffer.updateFloat("alpha", this.alpha);
  75942. // Point size
  75943. if (this.pointsCloud) {
  75944. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  75945. }
  75946. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  75947. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  75948. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  75949. }
  75950. // Textures
  75951. if (scene.texturesEnabled) {
  75952. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75953. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  75954. }
  75955. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75956. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  75957. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75958. }
  75959. else if (!defines.REFLECTIONBLUR) {
  75960. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75961. }
  75962. else {
  75963. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  75964. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  75965. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  75966. }
  75967. if (defines.REFLECTIONFRESNEL) {
  75968. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  75969. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  75970. }
  75971. }
  75972. }
  75973. // Clip plane
  75974. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  75975. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  75976. }
  75977. if (mustRebind || !this.isFrozen) {
  75978. if (scene.lightsEnabled) {
  75979. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  75980. }
  75981. // View
  75982. this.bindView(effect);
  75983. // Fog
  75984. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75985. // image processing
  75986. this._imageProcessingConfiguration.bind(this._activeEffect);
  75987. }
  75988. this._uniformBuffer.update();
  75989. this._afterBind(mesh);
  75990. };
  75991. /**
  75992. * Dispose the material.
  75993. * @forceDisposeEffect Force disposal of the associated effect.
  75994. * @forceDisposeTextures Force disposal of the associated textures.
  75995. */
  75996. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75997. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  75998. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  75999. if (forceDisposeTextures) {
  76000. if (this.diffuseTexture) {
  76001. this.diffuseTexture.dispose();
  76002. }
  76003. if (this.reflectionTexture) {
  76004. this.reflectionTexture.dispose();
  76005. }
  76006. }
  76007. this._renderTargets.dispose();
  76008. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76009. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76010. }
  76011. _super.prototype.dispose.call(this, forceDisposeEffect);
  76012. };
  76013. /**
  76014. * Clones the material.
  76015. * @name The cloned name.
  76016. * @returns The cloned material.
  76017. */
  76018. BackgroundMaterial.prototype.clone = function (name) {
  76019. var _this = this;
  76020. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  76021. };
  76022. /**
  76023. * Serializes the current material to its JSON representation.
  76024. * @returns The JSON representation.
  76025. */
  76026. BackgroundMaterial.prototype.serialize = function () {
  76027. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76028. serializationObject.customType = "BABYLON.BackgroundMaterial";
  76029. return serializationObject;
  76030. };
  76031. /**
  76032. * Gets the class name of the material
  76033. * @returns "BackgroundMaterial"
  76034. */
  76035. BackgroundMaterial.prototype.getClassName = function () {
  76036. return "BackgroundMaterial";
  76037. };
  76038. /**
  76039. * Parse a JSON input to create back a background material.
  76040. * @param source
  76041. * @param scene
  76042. * @param rootUrl
  76043. * @returns the instantiated BackgroundMaterial.
  76044. */
  76045. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  76046. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  76047. };
  76048. __decorate([
  76049. BABYLON.serializeAsColor3()
  76050. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  76051. __decorate([
  76052. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76053. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  76054. __decorate([
  76055. BABYLON.serialize()
  76056. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  76057. __decorate([
  76058. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76059. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  76060. __decorate([
  76061. BABYLON.serializeAsColor3()
  76062. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  76063. __decorate([
  76064. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76065. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  76066. __decorate([
  76067. BABYLON.serialize()
  76068. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  76069. __decorate([
  76070. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76071. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  76072. __decorate([
  76073. BABYLON.serializeAsColor3()
  76074. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  76075. __decorate([
  76076. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76077. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  76078. __decorate([
  76079. BABYLON.serialize()
  76080. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  76081. __decorate([
  76082. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76083. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  76084. __decorate([
  76085. BABYLON.serializeAsTexture()
  76086. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  76087. __decorate([
  76088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76089. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  76090. __decorate([
  76091. BABYLON.serialize()
  76092. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  76093. __decorate([
  76094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76095. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  76096. __decorate([
  76097. BABYLON.serializeAsTexture()
  76098. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  76099. __decorate([
  76100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76101. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  76102. __decorate([
  76103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76104. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  76105. __decorate([
  76106. BABYLON.serialize()
  76107. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  76108. __decorate([
  76109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76110. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  76111. __decorate([
  76112. BABYLON.serialize()
  76113. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  76114. __decorate([
  76115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76116. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  76117. __decorate([
  76118. BABYLON.serializeAsVector3()
  76119. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  76120. __decorate([
  76121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76122. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  76123. __decorate([
  76124. BABYLON.serialize()
  76125. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  76126. __decorate([
  76127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76128. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  76129. __decorate([
  76130. BABYLON.serialize()
  76131. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  76132. __decorate([
  76133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76134. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  76135. __decorate([
  76136. BABYLON.serialize()
  76137. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  76138. __decorate([
  76139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76140. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  76141. __decorate([
  76142. BABYLON.serialize()
  76143. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  76144. __decorate([
  76145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76146. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  76147. __decorate([
  76148. BABYLON.serialize()
  76149. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  76150. __decorate([
  76151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76152. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  76153. __decorate([
  76154. BABYLON.serialize()
  76155. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  76156. __decorate([
  76157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76158. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  76159. __decorate([
  76160. BABYLON.serialize()
  76161. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  76162. __decorate([
  76163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76164. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  76165. __decorate([
  76166. BABYLON.serialize()
  76167. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  76168. __decorate([
  76169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76170. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  76171. __decorate([
  76172. BABYLON.serializeAsImageProcessingConfiguration()
  76173. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  76174. return BackgroundMaterial;
  76175. }(BABYLON.PushMaterial));
  76176. BABYLON.BackgroundMaterial = BackgroundMaterial;
  76177. })(BABYLON || (BABYLON = {}));
  76178. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  76179. BABYLON.Effect.ShadersStore['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";
  76180. BABYLON.Effect.ShadersStore['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\ngl_FragColor=color;\n}";
  76181. BABYLON.Effect.IncludesShadersStore['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";
  76182. BABYLON.Effect.IncludesShadersStore['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};";
  76183. BABYLON.Effect.IncludesShadersStore['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";
  76184. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  76185. var BABYLON;
  76186. (function (BABYLON) {
  76187. var GLTFLoaderCoordinateSystemMode;
  76188. (function (GLTFLoaderCoordinateSystemMode) {
  76189. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  76190. // 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.
  76191. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  76192. // The glTF right-handed data is not transformed in any form and is loaded directly.
  76193. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  76194. // Sets the useRightHandedSystem flag on the scene.
  76195. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  76196. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  76197. var GLTFFileLoader = /** @class */ (function () {
  76198. function GLTFFileLoader() {
  76199. // V2 options
  76200. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  76201. this.name = "gltf";
  76202. this.extensions = {
  76203. ".gltf": { isBinary: false },
  76204. ".glb": { isBinary: true }
  76205. };
  76206. }
  76207. GLTFFileLoader.prototype.dispose = function () {
  76208. if (this._loader) {
  76209. this._loader.dispose();
  76210. }
  76211. };
  76212. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  76213. try {
  76214. var loaderData = GLTFFileLoader._parse(data);
  76215. if (this.onParsed) {
  76216. this.onParsed(loaderData);
  76217. }
  76218. this._loader = this._getLoader(loaderData);
  76219. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  76220. }
  76221. catch (e) {
  76222. onError(e.message);
  76223. }
  76224. };
  76225. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  76226. try {
  76227. var loaderData = GLTFFileLoader._parse(data);
  76228. if (this.onParsed) {
  76229. this.onParsed(loaderData);
  76230. }
  76231. this._loader = this._getLoader(loaderData);
  76232. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  76233. }
  76234. catch (e) {
  76235. onError(e.message);
  76236. }
  76237. };
  76238. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  76239. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  76240. };
  76241. GLTFFileLoader._parse = function (data) {
  76242. if (data instanceof ArrayBuffer) {
  76243. return GLTFFileLoader._parseBinary(data);
  76244. }
  76245. return {
  76246. json: JSON.parse(data),
  76247. bin: null
  76248. };
  76249. };
  76250. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  76251. var loaderVersion = { major: 2, minor: 0 };
  76252. var asset = loaderData.json.asset || {};
  76253. var version = GLTFFileLoader._parseVersion(asset.version);
  76254. if (!version) {
  76255. throw new Error("Invalid version: " + asset.version);
  76256. }
  76257. if (asset.minVersion !== undefined) {
  76258. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  76259. if (!minVersion) {
  76260. throw new Error("Invalid minimum version: " + asset.minVersion);
  76261. }
  76262. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  76263. throw new Error("Incompatible minimum version: " + asset.minVersion);
  76264. }
  76265. }
  76266. var createLoaders = {
  76267. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  76268. 2: GLTFFileLoader.CreateGLTFLoaderV2
  76269. };
  76270. var createLoader = createLoaders[version.major];
  76271. if (!createLoader) {
  76272. throw new Error("Unsupported version: " + asset.version);
  76273. }
  76274. return createLoader(this);
  76275. };
  76276. GLTFFileLoader._parseBinary = function (data) {
  76277. var Binary = {
  76278. Magic: 0x46546C67
  76279. };
  76280. var binaryReader = new BinaryReader(data);
  76281. var magic = binaryReader.readUint32();
  76282. if (magic !== Binary.Magic) {
  76283. throw new Error("Unexpected magic: " + magic);
  76284. }
  76285. var version = binaryReader.readUint32();
  76286. switch (version) {
  76287. case 1: return GLTFFileLoader._parseV1(binaryReader);
  76288. case 2: return GLTFFileLoader._parseV2(binaryReader);
  76289. }
  76290. throw new Error("Unsupported version: " + version);
  76291. };
  76292. GLTFFileLoader._parseV1 = function (binaryReader) {
  76293. var ContentFormat = {
  76294. JSON: 0
  76295. };
  76296. var length = binaryReader.readUint32();
  76297. if (length != binaryReader.getLength()) {
  76298. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  76299. }
  76300. var contentLength = binaryReader.readUint32();
  76301. var contentFormat = binaryReader.readUint32();
  76302. var content;
  76303. switch (contentFormat) {
  76304. case ContentFormat.JSON: {
  76305. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  76306. break;
  76307. }
  76308. default: {
  76309. throw new Error("Unexpected content format: " + contentFormat);
  76310. }
  76311. }
  76312. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  76313. var body = binaryReader.readUint8Array(bytesRemaining);
  76314. return {
  76315. json: content,
  76316. bin: body
  76317. };
  76318. };
  76319. GLTFFileLoader._parseV2 = function (binaryReader) {
  76320. var ChunkFormat = {
  76321. JSON: 0x4E4F534A,
  76322. BIN: 0x004E4942
  76323. };
  76324. var length = binaryReader.readUint32();
  76325. if (length !== binaryReader.getLength()) {
  76326. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  76327. }
  76328. // JSON chunk
  76329. var chunkLength = binaryReader.readUint32();
  76330. var chunkFormat = binaryReader.readUint32();
  76331. if (chunkFormat !== ChunkFormat.JSON) {
  76332. throw new Error("First chunk format is not JSON");
  76333. }
  76334. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  76335. // Look for BIN chunk
  76336. var bin = null;
  76337. while (binaryReader.getPosition() < binaryReader.getLength()) {
  76338. var chunkLength_1 = binaryReader.readUint32();
  76339. var chunkFormat_1 = binaryReader.readUint32();
  76340. switch (chunkFormat_1) {
  76341. case ChunkFormat.JSON: {
  76342. throw new Error("Unexpected JSON chunk");
  76343. }
  76344. case ChunkFormat.BIN: {
  76345. bin = binaryReader.readUint8Array(chunkLength_1);
  76346. break;
  76347. }
  76348. default: {
  76349. // ignore unrecognized chunkFormat
  76350. binaryReader.skipBytes(chunkLength_1);
  76351. break;
  76352. }
  76353. }
  76354. }
  76355. return {
  76356. json: json,
  76357. bin: bin
  76358. };
  76359. };
  76360. GLTFFileLoader._parseVersion = function (version) {
  76361. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  76362. if (!match) {
  76363. return null;
  76364. }
  76365. return {
  76366. major: parseInt(match[1]),
  76367. minor: parseInt(match[2])
  76368. };
  76369. };
  76370. GLTFFileLoader._compareVersion = function (a, b) {
  76371. if (a.major > b.major)
  76372. return 1;
  76373. if (a.major < b.major)
  76374. return -1;
  76375. if (a.minor > b.minor)
  76376. return 1;
  76377. if (a.minor < b.minor)
  76378. return -1;
  76379. return 0;
  76380. };
  76381. GLTFFileLoader._decodeBufferToText = function (buffer) {
  76382. var result = "";
  76383. var length = buffer.byteLength;
  76384. for (var i = 0; i < length; i++) {
  76385. result += String.fromCharCode(buffer[i]);
  76386. }
  76387. return result;
  76388. };
  76389. // V1 options
  76390. GLTFFileLoader.HomogeneousCoordinates = false;
  76391. GLTFFileLoader.IncrementalLoading = true;
  76392. return GLTFFileLoader;
  76393. }());
  76394. BABYLON.GLTFFileLoader = GLTFFileLoader;
  76395. var BinaryReader = /** @class */ (function () {
  76396. function BinaryReader(arrayBuffer) {
  76397. this._arrayBuffer = arrayBuffer;
  76398. this._dataView = new DataView(arrayBuffer);
  76399. this._byteOffset = 0;
  76400. }
  76401. BinaryReader.prototype.getPosition = function () {
  76402. return this._byteOffset;
  76403. };
  76404. BinaryReader.prototype.getLength = function () {
  76405. return this._arrayBuffer.byteLength;
  76406. };
  76407. BinaryReader.prototype.readUint32 = function () {
  76408. var value = this._dataView.getUint32(this._byteOffset, true);
  76409. this._byteOffset += 4;
  76410. return value;
  76411. };
  76412. BinaryReader.prototype.readUint8Array = function (length) {
  76413. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  76414. this._byteOffset += length;
  76415. return value;
  76416. };
  76417. BinaryReader.prototype.skipBytes = function (length) {
  76418. this._byteOffset += length;
  76419. };
  76420. return BinaryReader;
  76421. }());
  76422. if (BABYLON.SceneLoader) {
  76423. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  76424. }
  76425. })(BABYLON || (BABYLON = {}));
  76426. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  76427. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76428. var BABYLON;
  76429. (function (BABYLON) {
  76430. var GLTF1;
  76431. (function (GLTF1) {
  76432. /**
  76433. * Enums
  76434. */
  76435. var EComponentType;
  76436. (function (EComponentType) {
  76437. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  76438. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76439. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  76440. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76441. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  76442. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  76443. var EShaderType;
  76444. (function (EShaderType) {
  76445. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  76446. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  76447. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  76448. var EParameterType;
  76449. (function (EParameterType) {
  76450. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  76451. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76452. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  76453. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76454. EParameterType[EParameterType["INT"] = 5124] = "INT";
  76455. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  76456. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  76457. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  76458. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  76459. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  76460. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  76461. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  76462. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  76463. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  76464. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  76465. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  76466. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  76467. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  76468. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  76469. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  76470. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  76471. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  76472. var ETextureWrapMode;
  76473. (function (ETextureWrapMode) {
  76474. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  76475. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  76476. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  76477. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  76478. var ETextureFilterType;
  76479. (function (ETextureFilterType) {
  76480. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  76481. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  76482. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  76483. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  76484. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  76485. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  76486. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  76487. var ETextureFormat;
  76488. (function (ETextureFormat) {
  76489. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  76490. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  76491. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  76492. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  76493. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  76494. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  76495. var ECullingType;
  76496. (function (ECullingType) {
  76497. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  76498. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  76499. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  76500. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  76501. var EBlendingFunction;
  76502. (function (EBlendingFunction) {
  76503. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  76504. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  76505. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  76506. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  76507. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  76508. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  76509. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  76510. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  76511. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  76512. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  76513. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  76514. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  76515. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  76516. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  76517. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  76518. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  76519. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  76520. })(BABYLON || (BABYLON = {}));
  76521. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  76522. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76523. var BABYLON;
  76524. (function (BABYLON) {
  76525. var GLTF1;
  76526. (function (GLTF1) {
  76527. /**
  76528. * Tokenizer. Used for shaders compatibility
  76529. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  76530. */
  76531. var ETokenType;
  76532. (function (ETokenType) {
  76533. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  76534. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  76535. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  76536. })(ETokenType || (ETokenType = {}));
  76537. var Tokenizer = /** @class */ (function () {
  76538. function Tokenizer(toParse) {
  76539. this._pos = 0;
  76540. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  76541. this._toParse = toParse;
  76542. this._maxPos = toParse.length;
  76543. }
  76544. Tokenizer.prototype.getNextToken = function () {
  76545. if (this.isEnd())
  76546. return ETokenType.END_OF_INPUT;
  76547. this.currentString = this.read();
  76548. this.currentToken = ETokenType.UNKNOWN;
  76549. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  76550. this.currentToken = ETokenType.IDENTIFIER;
  76551. this.currentIdentifier = this.currentString;
  76552. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  76553. this.currentIdentifier += this.currentString;
  76554. this.forward();
  76555. }
  76556. }
  76557. return this.currentToken;
  76558. };
  76559. Tokenizer.prototype.peek = function () {
  76560. return this._toParse[this._pos];
  76561. };
  76562. Tokenizer.prototype.read = function () {
  76563. return this._toParse[this._pos++];
  76564. };
  76565. Tokenizer.prototype.forward = function () {
  76566. this._pos++;
  76567. };
  76568. Tokenizer.prototype.isEnd = function () {
  76569. return this._pos >= this._maxPos;
  76570. };
  76571. return Tokenizer;
  76572. }());
  76573. /**
  76574. * Values
  76575. */
  76576. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  76577. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  76578. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  76579. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  76580. /**
  76581. * Parse
  76582. */
  76583. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  76584. for (var buf in parsedBuffers) {
  76585. var parsedBuffer = parsedBuffers[buf];
  76586. gltfRuntime.buffers[buf] = parsedBuffer;
  76587. gltfRuntime.buffersCount++;
  76588. }
  76589. };
  76590. var parseShaders = function (parsedShaders, gltfRuntime) {
  76591. for (var sha in parsedShaders) {
  76592. var parsedShader = parsedShaders[sha];
  76593. gltfRuntime.shaders[sha] = parsedShader;
  76594. gltfRuntime.shaderscount++;
  76595. }
  76596. };
  76597. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  76598. for (var object in parsedObjects) {
  76599. var parsedObject = parsedObjects[object];
  76600. gltfRuntime[runtimeProperty][object] = parsedObject;
  76601. }
  76602. };
  76603. /**
  76604. * Utils
  76605. */
  76606. var normalizeUVs = function (buffer) {
  76607. if (!buffer) {
  76608. return;
  76609. }
  76610. for (var i = 0; i < buffer.length / 2; i++) {
  76611. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  76612. }
  76613. };
  76614. var getAttribute = function (attributeParameter) {
  76615. if (attributeParameter.semantic === "NORMAL") {
  76616. return "normal";
  76617. }
  76618. else if (attributeParameter.semantic === "POSITION") {
  76619. return "position";
  76620. }
  76621. else if (attributeParameter.semantic === "JOINT") {
  76622. return "matricesIndices";
  76623. }
  76624. else if (attributeParameter.semantic === "WEIGHT") {
  76625. return "matricesWeights";
  76626. }
  76627. else if (attributeParameter.semantic === "COLOR") {
  76628. return "color";
  76629. }
  76630. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  76631. var channel = Number(attributeParameter.semantic.split("_")[1]);
  76632. return "uv" + (channel === 0 ? "" : channel + 1);
  76633. }
  76634. return null;
  76635. };
  76636. /**
  76637. * Loads and creates animations
  76638. */
  76639. var loadAnimations = function (gltfRuntime) {
  76640. for (var anim in gltfRuntime.animations) {
  76641. var animation = gltfRuntime.animations[anim];
  76642. if (!animation.channels || !animation.samplers) {
  76643. continue;
  76644. }
  76645. var lastAnimation = null;
  76646. for (var i = 0; i < animation.channels.length; i++) {
  76647. // Get parameters and load buffers
  76648. var channel = animation.channels[i];
  76649. var sampler = animation.samplers[channel.sampler];
  76650. if (!sampler) {
  76651. continue;
  76652. }
  76653. var inputData = null;
  76654. var outputData = null;
  76655. if (animation.parameters) {
  76656. inputData = animation.parameters[sampler.input];
  76657. outputData = animation.parameters[sampler.output];
  76658. }
  76659. else {
  76660. inputData = sampler.input;
  76661. outputData = sampler.output;
  76662. }
  76663. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  76664. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  76665. var targetID = channel.target.id;
  76666. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  76667. if (targetNode === null) {
  76668. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  76669. }
  76670. if (targetNode === null) {
  76671. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  76672. continue;
  76673. }
  76674. var isBone = targetNode instanceof BABYLON.Bone;
  76675. // Get target path (position, rotation or scaling)
  76676. var targetPath = channel.target.path;
  76677. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  76678. if (targetPathIndex !== -1) {
  76679. targetPath = babylonAnimationPaths[targetPathIndex];
  76680. }
  76681. // Determine animation type
  76682. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  76683. if (!isBone) {
  76684. if (targetPath === "rotationQuaternion") {
  76685. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  76686. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  76687. }
  76688. else {
  76689. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  76690. }
  76691. }
  76692. // Create animation and key frames
  76693. var babylonAnimation = null;
  76694. var keys = [];
  76695. var arrayOffset = 0;
  76696. var modifyKey = false;
  76697. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  76698. babylonAnimation = lastAnimation;
  76699. modifyKey = true;
  76700. }
  76701. if (!modifyKey) {
  76702. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76703. }
  76704. // For each frame
  76705. for (var j = 0; j < bufferInput.length; j++) {
  76706. var value = null;
  76707. if (targetPath === "rotationQuaternion") {
  76708. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  76709. arrayOffset += 4;
  76710. }
  76711. else {
  76712. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  76713. arrayOffset += 3;
  76714. }
  76715. if (isBone) {
  76716. var bone = targetNode;
  76717. var translation = BABYLON.Vector3.Zero();
  76718. var rotationQuaternion = new BABYLON.Quaternion();
  76719. var scaling = BABYLON.Vector3.Zero();
  76720. // Warning on decompose
  76721. var mat = bone.getBaseMatrix();
  76722. if (modifyKey && lastAnimation) {
  76723. mat = lastAnimation.getKeys()[j].value;
  76724. }
  76725. mat.decompose(scaling, rotationQuaternion, translation);
  76726. if (targetPath === "position") {
  76727. translation = value;
  76728. }
  76729. else if (targetPath === "rotationQuaternion") {
  76730. rotationQuaternion = value;
  76731. }
  76732. else {
  76733. scaling = value;
  76734. }
  76735. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  76736. }
  76737. if (!modifyKey) {
  76738. keys.push({
  76739. frame: bufferInput[j],
  76740. value: value
  76741. });
  76742. }
  76743. else if (lastAnimation) {
  76744. lastAnimation.getKeys()[j].value = value;
  76745. }
  76746. }
  76747. // Finish
  76748. if (!modifyKey && babylonAnimation) {
  76749. babylonAnimation.setKeys(keys);
  76750. targetNode.animations.push(babylonAnimation);
  76751. }
  76752. lastAnimation = babylonAnimation;
  76753. gltfRuntime.scene.stopAnimation(targetNode);
  76754. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  76755. }
  76756. }
  76757. };
  76758. /**
  76759. * Returns the bones transformation matrix
  76760. */
  76761. var configureBoneTransformation = function (node) {
  76762. var mat = null;
  76763. if (node.translation || node.rotation || node.scale) {
  76764. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  76765. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  76766. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  76767. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  76768. }
  76769. else {
  76770. mat = BABYLON.Matrix.FromArray(node.matrix);
  76771. }
  76772. return mat;
  76773. };
  76774. /**
  76775. * Returns the parent bone
  76776. */
  76777. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  76778. // Try to find
  76779. for (var i = 0; i < newSkeleton.bones.length; i++) {
  76780. if (newSkeleton.bones[i].name === jointName) {
  76781. return newSkeleton.bones[i];
  76782. }
  76783. }
  76784. // Not found, search in gltf nodes
  76785. var nodes = gltfRuntime.nodes;
  76786. for (var nde in nodes) {
  76787. var node = nodes[nde];
  76788. if (!node.jointName) {
  76789. continue;
  76790. }
  76791. var children = node.children;
  76792. for (var i = 0; i < children.length; i++) {
  76793. var child = gltfRuntime.nodes[children[i]];
  76794. if (!child.jointName) {
  76795. continue;
  76796. }
  76797. if (child.jointName === jointName) {
  76798. var mat = configureBoneTransformation(node);
  76799. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  76800. bone.id = nde;
  76801. return bone;
  76802. }
  76803. }
  76804. }
  76805. return null;
  76806. };
  76807. /**
  76808. * Returns the appropriate root node
  76809. */
  76810. var getNodeToRoot = function (nodesToRoot, id) {
  76811. for (var i = 0; i < nodesToRoot.length; i++) {
  76812. var nodeToRoot = nodesToRoot[i];
  76813. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  76814. var child = nodeToRoot.node.children[j];
  76815. if (child === id) {
  76816. return nodeToRoot.bone;
  76817. }
  76818. }
  76819. }
  76820. return null;
  76821. };
  76822. /**
  76823. * Returns the node with the joint name
  76824. */
  76825. var getJointNode = function (gltfRuntime, jointName) {
  76826. var nodes = gltfRuntime.nodes;
  76827. var node = nodes[jointName];
  76828. if (node) {
  76829. return {
  76830. node: node,
  76831. id: jointName
  76832. };
  76833. }
  76834. for (var nde in nodes) {
  76835. node = nodes[nde];
  76836. if (node.jointName === jointName) {
  76837. return {
  76838. node: node,
  76839. id: nde
  76840. };
  76841. }
  76842. }
  76843. return null;
  76844. };
  76845. /**
  76846. * Checks if a nodes is in joints
  76847. */
  76848. var nodeIsInJoints = function (skins, id) {
  76849. for (var i = 0; i < skins.jointNames.length; i++) {
  76850. if (skins.jointNames[i] === id) {
  76851. return true;
  76852. }
  76853. }
  76854. return false;
  76855. };
  76856. /**
  76857. * Fills the nodes to root for bones and builds hierarchy
  76858. */
  76859. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  76860. // Creates nodes for root
  76861. for (var nde in gltfRuntime.nodes) {
  76862. var node = gltfRuntime.nodes[nde];
  76863. var id = nde;
  76864. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  76865. continue;
  76866. }
  76867. // Create node to root bone
  76868. var mat = configureBoneTransformation(node);
  76869. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  76870. bone.id = id;
  76871. nodesToRoot.push({ bone: bone, node: node, id: id });
  76872. }
  76873. // Parenting
  76874. for (var i = 0; i < nodesToRoot.length; i++) {
  76875. var nodeToRoot = nodesToRoot[i];
  76876. var children = nodeToRoot.node.children;
  76877. for (var j = 0; j < children.length; j++) {
  76878. var child = null;
  76879. for (var k = 0; k < nodesToRoot.length; k++) {
  76880. if (nodesToRoot[k].id === children[j]) {
  76881. child = nodesToRoot[k];
  76882. break;
  76883. }
  76884. }
  76885. if (child) {
  76886. child.bone._parent = nodeToRoot.bone;
  76887. nodeToRoot.bone.children.push(child.bone);
  76888. }
  76889. }
  76890. }
  76891. };
  76892. /**
  76893. * Imports a skeleton
  76894. */
  76895. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  76896. if (!newSkeleton) {
  76897. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  76898. }
  76899. if (!skins.babylonSkeleton) {
  76900. return newSkeleton;
  76901. }
  76902. // Find the root bones
  76903. var nodesToRoot = [];
  76904. var nodesToRootToAdd = [];
  76905. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  76906. newSkeleton.bones = [];
  76907. // Joints
  76908. for (var i = 0; i < skins.jointNames.length; i++) {
  76909. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76910. if (!jointNode) {
  76911. continue;
  76912. }
  76913. var node = jointNode.node;
  76914. if (!node) {
  76915. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  76916. continue;
  76917. }
  76918. var id = jointNode.id;
  76919. // Optimize, if the bone already exists...
  76920. var existingBone = gltfRuntime.scene.getBoneByID(id);
  76921. if (existingBone) {
  76922. newSkeleton.bones.push(existingBone);
  76923. continue;
  76924. }
  76925. // Search for parent bone
  76926. var foundBone = false;
  76927. var parentBone = null;
  76928. for (var j = 0; j < i; j++) {
  76929. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  76930. if (!jointNode_1) {
  76931. continue;
  76932. }
  76933. var joint = jointNode_1.node;
  76934. if (!joint) {
  76935. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  76936. continue;
  76937. }
  76938. var children = joint.children;
  76939. if (!children) {
  76940. continue;
  76941. }
  76942. foundBone = false;
  76943. for (var k = 0; k < children.length; k++) {
  76944. if (children[k] === id) {
  76945. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  76946. foundBone = true;
  76947. break;
  76948. }
  76949. }
  76950. if (foundBone) {
  76951. break;
  76952. }
  76953. }
  76954. // Create bone
  76955. var mat = configureBoneTransformation(node);
  76956. if (!parentBone && nodesToRoot.length > 0) {
  76957. parentBone = getNodeToRoot(nodesToRoot, id);
  76958. if (parentBone) {
  76959. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  76960. nodesToRootToAdd.push(parentBone);
  76961. }
  76962. }
  76963. }
  76964. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  76965. bone.id = id;
  76966. }
  76967. // Polish
  76968. var bones = newSkeleton.bones;
  76969. newSkeleton.bones = [];
  76970. for (var i = 0; i < skins.jointNames.length; i++) {
  76971. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76972. if (!jointNode) {
  76973. continue;
  76974. }
  76975. for (var j = 0; j < bones.length; j++) {
  76976. if (bones[j].id === jointNode.id) {
  76977. newSkeleton.bones.push(bones[j]);
  76978. break;
  76979. }
  76980. }
  76981. }
  76982. newSkeleton.prepare();
  76983. // Finish
  76984. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  76985. newSkeleton.bones.push(nodesToRootToAdd[i]);
  76986. }
  76987. return newSkeleton;
  76988. };
  76989. /**
  76990. * Imports a mesh and its geometries
  76991. */
  76992. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  76993. if (!newMesh) {
  76994. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76995. newMesh.id = id;
  76996. }
  76997. if (!node.babylonNode) {
  76998. return newMesh;
  76999. }
  77000. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  77001. if (!newMesh.material) {
  77002. newMesh.material = multiMat;
  77003. }
  77004. var vertexData = new BABYLON.VertexData();
  77005. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  77006. var verticesStarts = new Array();
  77007. var verticesCounts = new Array();
  77008. var indexStarts = new Array();
  77009. var indexCounts = new Array();
  77010. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  77011. var meshID = meshes[meshIndex];
  77012. var mesh = gltfRuntime.meshes[meshID];
  77013. if (!mesh) {
  77014. continue;
  77015. }
  77016. // Positions, normals and UVs
  77017. for (var i = 0; i < mesh.primitives.length; i++) {
  77018. // Temporary vertex data
  77019. var tempVertexData = new BABYLON.VertexData();
  77020. var primitive = mesh.primitives[i];
  77021. if (primitive.mode !== 4) {
  77022. // continue;
  77023. }
  77024. var attributes = primitive.attributes;
  77025. var accessor = null;
  77026. var buffer = null;
  77027. // Set positions, normal and uvs
  77028. for (var semantic in attributes) {
  77029. // Link accessor and buffer view
  77030. accessor = gltfRuntime.accessors[attributes[semantic]];
  77031. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  77032. if (semantic === "NORMAL") {
  77033. tempVertexData.normals = new Float32Array(buffer.length);
  77034. tempVertexData.normals.set(buffer);
  77035. }
  77036. else if (semantic === "POSITION") {
  77037. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  77038. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  77039. for (var j = 0; j < buffer.length; j += 4) {
  77040. tempVertexData.positions[j] = buffer[j];
  77041. tempVertexData.positions[j + 1] = buffer[j + 1];
  77042. tempVertexData.positions[j + 2] = buffer[j + 2];
  77043. }
  77044. }
  77045. else {
  77046. tempVertexData.positions = new Float32Array(buffer.length);
  77047. tempVertexData.positions.set(buffer);
  77048. }
  77049. verticesCounts.push(tempVertexData.positions.length);
  77050. }
  77051. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  77052. var channel = Number(semantic.split("_")[1]);
  77053. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  77054. var uvs = new Float32Array(buffer.length);
  77055. uvs.set(buffer);
  77056. normalizeUVs(uvs);
  77057. tempVertexData.set(uvs, uvKind);
  77058. }
  77059. else if (semantic === "JOINT") {
  77060. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  77061. tempVertexData.matricesIndices.set(buffer);
  77062. }
  77063. else if (semantic === "WEIGHT") {
  77064. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  77065. tempVertexData.matricesWeights.set(buffer);
  77066. }
  77067. else if (semantic === "COLOR") {
  77068. tempVertexData.colors = new Float32Array(buffer.length);
  77069. tempVertexData.colors.set(buffer);
  77070. }
  77071. }
  77072. // Indices
  77073. accessor = gltfRuntime.accessors[primitive.indices];
  77074. if (accessor) {
  77075. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  77076. tempVertexData.indices = new Int32Array(buffer.length);
  77077. tempVertexData.indices.set(buffer);
  77078. indexCounts.push(tempVertexData.indices.length);
  77079. }
  77080. else {
  77081. // Set indices on the fly
  77082. var indices = [];
  77083. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  77084. indices.push(j);
  77085. }
  77086. tempVertexData.indices = new Int32Array(indices);
  77087. indexCounts.push(tempVertexData.indices.length);
  77088. }
  77089. vertexData.merge(tempVertexData);
  77090. // Sub material
  77091. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  77092. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  77093. // Update vertices start and index start
  77094. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  77095. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  77096. }
  77097. }
  77098. // Apply geometry
  77099. geometry.setAllVerticesData(vertexData, false);
  77100. newMesh.computeWorldMatrix(true);
  77101. // Apply submeshes
  77102. newMesh.subMeshes = [];
  77103. var index = 0;
  77104. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  77105. var meshID = meshes[meshIndex];
  77106. var mesh = gltfRuntime.meshes[meshID];
  77107. if (!mesh) {
  77108. continue;
  77109. }
  77110. for (var i = 0; i < mesh.primitives.length; i++) {
  77111. if (mesh.primitives[i].mode !== 4) {
  77112. //continue;
  77113. }
  77114. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  77115. index++;
  77116. }
  77117. }
  77118. // Finish
  77119. return newMesh;
  77120. };
  77121. /**
  77122. * Configure node transformation from position, rotation and scaling
  77123. */
  77124. var configureNode = function (newNode, position, rotation, scaling) {
  77125. if (newNode.position) {
  77126. newNode.position = position;
  77127. }
  77128. if (newNode.rotationQuaternion || newNode.rotation) {
  77129. newNode.rotationQuaternion = rotation;
  77130. }
  77131. if (newNode.scaling) {
  77132. newNode.scaling = scaling;
  77133. }
  77134. };
  77135. /**
  77136. * Configures node from transformation matrix
  77137. */
  77138. var configureNodeFromMatrix = function (newNode, node, parent) {
  77139. if (node.matrix) {
  77140. var position = new BABYLON.Vector3(0, 0, 0);
  77141. var rotation = new BABYLON.Quaternion();
  77142. var scaling = new BABYLON.Vector3(0, 0, 0);
  77143. var mat = BABYLON.Matrix.FromArray(node.matrix);
  77144. mat.decompose(scaling, rotation, position);
  77145. configureNode(newNode, position, rotation, scaling);
  77146. }
  77147. else if (node.translation && node.rotation && node.scale) {
  77148. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  77149. }
  77150. newNode.computeWorldMatrix(true);
  77151. };
  77152. /**
  77153. * Imports a node
  77154. */
  77155. var importNode = function (gltfRuntime, node, id, parent) {
  77156. var lastNode = null;
  77157. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  77158. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  77159. return null;
  77160. }
  77161. }
  77162. // Meshes
  77163. if (node.skin) {
  77164. if (node.meshes) {
  77165. var skin = gltfRuntime.skins[node.skin];
  77166. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  77167. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  77168. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  77169. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  77170. if (!skin.babylonSkeleton) {
  77171. skin.babylonSkeleton = newMesh.skeleton;
  77172. }
  77173. }
  77174. lastNode = newMesh;
  77175. }
  77176. }
  77177. else if (node.meshes) {
  77178. /**
  77179. * Improve meshes property
  77180. */
  77181. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  77182. lastNode = newMesh;
  77183. }
  77184. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  77185. var light = gltfRuntime.lights[node.light];
  77186. if (light) {
  77187. if (light.type === "ambient") {
  77188. var ambienLight = light[light.type];
  77189. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77190. hemiLight.name = node.name || "";
  77191. if (ambienLight.color) {
  77192. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  77193. }
  77194. lastNode = hemiLight;
  77195. }
  77196. else if (light.type === "directional") {
  77197. var directionalLight = light[light.type];
  77198. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77199. dirLight.name = node.name || "";
  77200. if (directionalLight.color) {
  77201. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  77202. }
  77203. lastNode = dirLight;
  77204. }
  77205. else if (light.type === "point") {
  77206. var pointLight = light[light.type];
  77207. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77208. ptLight.name = node.name || "";
  77209. if (pointLight.color) {
  77210. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  77211. }
  77212. lastNode = ptLight;
  77213. }
  77214. else if (light.type === "spot") {
  77215. var spotLight = light[light.type];
  77216. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  77217. spLight.name = node.name || "";
  77218. if (spotLight.color) {
  77219. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  77220. }
  77221. if (spotLight.fallOfAngle) {
  77222. spLight.angle = spotLight.fallOfAngle;
  77223. }
  77224. if (spotLight.fallOffExponent) {
  77225. spLight.exponent = spotLight.fallOffExponent;
  77226. }
  77227. lastNode = spLight;
  77228. }
  77229. }
  77230. }
  77231. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  77232. var camera = gltfRuntime.cameras[node.camera];
  77233. if (camera) {
  77234. if (camera.type === "orthographic") {
  77235. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77236. orthoCamera.name = node.name || "";
  77237. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  77238. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  77239. lastNode = orthoCamera;
  77240. }
  77241. else if (camera.type === "perspective") {
  77242. var perspectiveCamera = camera[camera.type];
  77243. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77244. persCamera.name = node.name || "";
  77245. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  77246. if (!perspectiveCamera.aspectRatio) {
  77247. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  77248. }
  77249. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  77250. persCamera.maxZ = perspectiveCamera.zfar;
  77251. persCamera.minZ = perspectiveCamera.znear;
  77252. }
  77253. lastNode = persCamera;
  77254. }
  77255. }
  77256. }
  77257. // Empty node
  77258. if (!node.jointName) {
  77259. if (node.babylonNode) {
  77260. return node.babylonNode;
  77261. }
  77262. else if (lastNode === null) {
  77263. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  77264. node.babylonNode = dummy;
  77265. lastNode = dummy;
  77266. }
  77267. }
  77268. if (lastNode !== null) {
  77269. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  77270. configureNodeFromMatrix(lastNode, node, parent);
  77271. }
  77272. else {
  77273. var translation = node.translation || [0, 0, 0];
  77274. var rotation = node.rotation || [0, 0, 0, 1];
  77275. var scale = node.scale || [1, 1, 1];
  77276. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  77277. }
  77278. lastNode.updateCache(true);
  77279. node.babylonNode = lastNode;
  77280. }
  77281. return lastNode;
  77282. };
  77283. /**
  77284. * Traverses nodes and creates them
  77285. */
  77286. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  77287. if (meshIncluded === void 0) { meshIncluded = false; }
  77288. var node = gltfRuntime.nodes[id];
  77289. var newNode = null;
  77290. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  77291. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  77292. meshIncluded = true;
  77293. }
  77294. else {
  77295. meshIncluded = false;
  77296. }
  77297. }
  77298. else {
  77299. meshIncluded = true;
  77300. }
  77301. if (!node.jointName && meshIncluded) {
  77302. newNode = importNode(gltfRuntime, node, id, parent);
  77303. if (newNode !== null) {
  77304. newNode.id = id;
  77305. newNode.parent = parent;
  77306. }
  77307. }
  77308. if (node.children) {
  77309. for (var i = 0; i < node.children.length; i++) {
  77310. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  77311. }
  77312. }
  77313. };
  77314. /**
  77315. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  77316. */
  77317. var postLoad = function (gltfRuntime) {
  77318. // Nodes
  77319. var currentScene = gltfRuntime.currentScene;
  77320. if (currentScene) {
  77321. for (var i = 0; i < currentScene.nodes.length; i++) {
  77322. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77323. }
  77324. }
  77325. else {
  77326. for (var thing in gltfRuntime.scenes) {
  77327. currentScene = gltfRuntime.scenes[thing];
  77328. for (var i = 0; i < currentScene.nodes.length; i++) {
  77329. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77330. }
  77331. }
  77332. }
  77333. // Set animations
  77334. loadAnimations(gltfRuntime);
  77335. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  77336. var skeleton = gltfRuntime.scene.skeletons[i];
  77337. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  77338. }
  77339. };
  77340. /**
  77341. * onBind shaderrs callback to set uniforms and matrices
  77342. */
  77343. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  77344. var materialValues = material.values || technique.parameters;
  77345. for (var unif in unTreatedUniforms) {
  77346. var uniform = unTreatedUniforms[unif];
  77347. var type = uniform.type;
  77348. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  77349. if (uniform.semantic && !uniform.source && !uniform.node) {
  77350. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  77351. }
  77352. else if (uniform.semantic && (uniform.source || uniform.node)) {
  77353. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  77354. if (source === null) {
  77355. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  77356. }
  77357. if (source === null) {
  77358. continue;
  77359. }
  77360. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  77361. }
  77362. }
  77363. else {
  77364. var value = materialValues[technique.uniforms[unif]];
  77365. if (!value) {
  77366. continue;
  77367. }
  77368. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77369. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  77370. if (texture === null || texture === undefined) {
  77371. continue;
  77372. }
  77373. shaderMaterial.getEffect().setTexture(unif, texture);
  77374. }
  77375. else {
  77376. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  77377. }
  77378. }
  77379. }
  77380. onSuccess(shaderMaterial);
  77381. };
  77382. /**
  77383. * Prepare uniforms to send the only one time
  77384. * Loads the appropriate textures
  77385. */
  77386. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  77387. var materialValues = material.values || technique.parameters;
  77388. var techniqueUniforms = technique.uniforms;
  77389. /**
  77390. * Prepare values here (not matrices)
  77391. */
  77392. for (var unif in unTreatedUniforms) {
  77393. var uniform = unTreatedUniforms[unif];
  77394. var type = uniform.type;
  77395. var value = materialValues[techniqueUniforms[unif]];
  77396. if (value === undefined) {
  77397. // In case the value is the same for all materials
  77398. value = uniform.value;
  77399. }
  77400. if (!value) {
  77401. continue;
  77402. }
  77403. var onLoadTexture = function (uniformName) {
  77404. return function (texture) {
  77405. if (uniform.value && uniformName) {
  77406. // Static uniform
  77407. shaderMaterial.setTexture(uniformName, texture);
  77408. delete unTreatedUniforms[uniformName];
  77409. }
  77410. };
  77411. };
  77412. // Texture (sampler2D)
  77413. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77414. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  77415. }
  77416. else {
  77417. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  77418. // Static uniform
  77419. delete unTreatedUniforms[unif];
  77420. }
  77421. }
  77422. }
  77423. };
  77424. /**
  77425. * Shader compilation failed
  77426. */
  77427. var onShaderCompileError = function (program, shaderMaterial, onError) {
  77428. return function (effect, error) {
  77429. shaderMaterial.dispose(true);
  77430. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  77431. };
  77432. };
  77433. /**
  77434. * Shader compilation success
  77435. */
  77436. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  77437. return function (_) {
  77438. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  77439. shaderMaterial.onBind = function (mesh) {
  77440. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  77441. };
  77442. };
  77443. };
  77444. /**
  77445. * Returns the appropriate uniform if already handled by babylon
  77446. */
  77447. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  77448. for (var unif in technique.uniforms) {
  77449. var uniform = technique.uniforms[unif];
  77450. var uniformParameter = technique.parameters[uniform];
  77451. if (tokenizer.currentIdentifier === unif) {
  77452. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  77453. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77454. if (transformIndex !== -1) {
  77455. delete unTreatedUniforms[unif];
  77456. return babylonTransforms[transformIndex];
  77457. }
  77458. }
  77459. }
  77460. }
  77461. return tokenizer.currentIdentifier;
  77462. };
  77463. /**
  77464. * All shaders loaded. Create materials one by one
  77465. */
  77466. var importMaterials = function (gltfRuntime) {
  77467. // Create materials
  77468. for (var mat in gltfRuntime.materials) {
  77469. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  77470. }
  77471. };
  77472. /**
  77473. * Implementation of the base glTF spec
  77474. */
  77475. var GLTFLoaderBase = /** @class */ (function () {
  77476. function GLTFLoaderBase() {
  77477. }
  77478. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  77479. var gltfRuntime = {
  77480. extensions: {},
  77481. accessors: {},
  77482. buffers: {},
  77483. bufferViews: {},
  77484. meshes: {},
  77485. lights: {},
  77486. cameras: {},
  77487. nodes: {},
  77488. images: {},
  77489. textures: {},
  77490. shaders: {},
  77491. programs: {},
  77492. samplers: {},
  77493. techniques: {},
  77494. materials: {},
  77495. animations: {},
  77496. skins: {},
  77497. extensionsUsed: [],
  77498. scenes: {},
  77499. buffersCount: 0,
  77500. shaderscount: 0,
  77501. scene: scene,
  77502. rootUrl: rootUrl,
  77503. loadedBufferCount: 0,
  77504. loadedBufferViews: {},
  77505. loadedShaderCount: 0,
  77506. importOnlyMeshes: false,
  77507. dummyNodes: []
  77508. };
  77509. // Parse
  77510. if (parsedData.extensions) {
  77511. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  77512. }
  77513. if (parsedData.extensionsUsed) {
  77514. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  77515. }
  77516. if (parsedData.buffers) {
  77517. parseBuffers(parsedData.buffers, gltfRuntime);
  77518. }
  77519. if (parsedData.bufferViews) {
  77520. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  77521. }
  77522. if (parsedData.accessors) {
  77523. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  77524. }
  77525. if (parsedData.meshes) {
  77526. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  77527. }
  77528. if (parsedData.lights) {
  77529. parseObject(parsedData.lights, "lights", gltfRuntime);
  77530. }
  77531. if (parsedData.cameras) {
  77532. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  77533. }
  77534. if (parsedData.nodes) {
  77535. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  77536. }
  77537. if (parsedData.images) {
  77538. parseObject(parsedData.images, "images", gltfRuntime);
  77539. }
  77540. if (parsedData.textures) {
  77541. parseObject(parsedData.textures, "textures", gltfRuntime);
  77542. }
  77543. if (parsedData.shaders) {
  77544. parseShaders(parsedData.shaders, gltfRuntime);
  77545. }
  77546. if (parsedData.programs) {
  77547. parseObject(parsedData.programs, "programs", gltfRuntime);
  77548. }
  77549. if (parsedData.samplers) {
  77550. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  77551. }
  77552. if (parsedData.techniques) {
  77553. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  77554. }
  77555. if (parsedData.materials) {
  77556. parseObject(parsedData.materials, "materials", gltfRuntime);
  77557. }
  77558. if (parsedData.animations) {
  77559. parseObject(parsedData.animations, "animations", gltfRuntime);
  77560. }
  77561. if (parsedData.skins) {
  77562. parseObject(parsedData.skins, "skins", gltfRuntime);
  77563. }
  77564. if (parsedData.scenes) {
  77565. gltfRuntime.scenes = parsedData.scenes;
  77566. }
  77567. if (parsedData.scene && parsedData.scenes) {
  77568. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  77569. }
  77570. return gltfRuntime;
  77571. };
  77572. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77573. var buffer = gltfRuntime.buffers[id];
  77574. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  77575. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  77576. }
  77577. else {
  77578. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  77579. if (request) {
  77580. onError(request.status + " " + request.statusText);
  77581. }
  77582. });
  77583. }
  77584. };
  77585. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77586. var texture = gltfRuntime.textures[id];
  77587. if (!texture || !texture.source) {
  77588. onError("");
  77589. return;
  77590. }
  77591. if (texture.babylonTexture) {
  77592. onSuccess(null);
  77593. return;
  77594. }
  77595. var source = gltfRuntime.images[texture.source];
  77596. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  77597. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  77598. }
  77599. else {
  77600. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  77601. if (request) {
  77602. onError(request.status + " " + request.statusText);
  77603. }
  77604. });
  77605. }
  77606. };
  77607. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77608. var texture = gltfRuntime.textures[id];
  77609. if (texture.babylonTexture) {
  77610. onSuccess(texture.babylonTexture);
  77611. return;
  77612. }
  77613. var sampler = gltfRuntime.samplers[texture.sampler];
  77614. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  77615. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  77616. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  77617. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  77618. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77619. var blob = new Blob([buffer]);
  77620. var blobURL = URL.createObjectURL(blob);
  77621. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  77622. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  77623. if (sampler.wrapS !== undefined) {
  77624. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  77625. }
  77626. if (sampler.wrapT !== undefined) {
  77627. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  77628. }
  77629. newTexture.name = id;
  77630. texture.babylonTexture = newTexture;
  77631. onSuccess(newTexture);
  77632. };
  77633. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77634. var shader = gltfRuntime.shaders[id];
  77635. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  77636. var shaderString = atob(shader.uri.split(",")[1]);
  77637. onSuccess(shaderString);
  77638. }
  77639. else {
  77640. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  77641. if (request) {
  77642. onError(request.status + " " + request.statusText);
  77643. }
  77644. });
  77645. }
  77646. };
  77647. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77648. var material = gltfRuntime.materials[id];
  77649. if (!material.technique) {
  77650. if (onError) {
  77651. onError("No technique found.");
  77652. }
  77653. return;
  77654. }
  77655. var technique = gltfRuntime.techniques[material.technique];
  77656. if (!technique) {
  77657. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  77658. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  77659. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77660. onSuccess(defaultMaterial);
  77661. return;
  77662. }
  77663. var program = gltfRuntime.programs[technique.program];
  77664. var states = technique.states;
  77665. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  77666. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  77667. var newVertexShader = "";
  77668. var newPixelShader = "";
  77669. var vertexTokenizer = new Tokenizer(vertexShader);
  77670. var pixelTokenizer = new Tokenizer(pixelShader);
  77671. var unTreatedUniforms = {};
  77672. var uniforms = [];
  77673. var attributes = [];
  77674. var samplers = [];
  77675. // Fill uniform, sampler2D and attributes
  77676. for (var unif in technique.uniforms) {
  77677. var uniform = technique.uniforms[unif];
  77678. var uniformParameter = technique.parameters[uniform];
  77679. unTreatedUniforms[unif] = uniformParameter;
  77680. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  77681. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77682. if (transformIndex !== -1) {
  77683. uniforms.push(babylonTransforms[transformIndex]);
  77684. delete unTreatedUniforms[unif];
  77685. }
  77686. else {
  77687. uniforms.push(unif);
  77688. }
  77689. }
  77690. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  77691. samplers.push(unif);
  77692. }
  77693. else {
  77694. uniforms.push(unif);
  77695. }
  77696. }
  77697. for (var attr in technique.attributes) {
  77698. var attribute = technique.attributes[attr];
  77699. var attributeParameter = technique.parameters[attribute];
  77700. if (attributeParameter.semantic) {
  77701. attributes.push(getAttribute(attributeParameter));
  77702. }
  77703. }
  77704. // Configure vertex shader
  77705. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  77706. var tokenType = vertexTokenizer.currentToken;
  77707. if (tokenType !== ETokenType.IDENTIFIER) {
  77708. newVertexShader += vertexTokenizer.currentString;
  77709. continue;
  77710. }
  77711. var foundAttribute = false;
  77712. for (var attr in technique.attributes) {
  77713. var attribute = technique.attributes[attr];
  77714. var attributeParameter = technique.parameters[attribute];
  77715. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  77716. newVertexShader += getAttribute(attributeParameter);
  77717. foundAttribute = true;
  77718. break;
  77719. }
  77720. }
  77721. if (foundAttribute) {
  77722. continue;
  77723. }
  77724. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  77725. }
  77726. // Configure pixel shader
  77727. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  77728. var tokenType = pixelTokenizer.currentToken;
  77729. if (tokenType !== ETokenType.IDENTIFIER) {
  77730. newPixelShader += pixelTokenizer.currentString;
  77731. continue;
  77732. }
  77733. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  77734. }
  77735. // Create shader material
  77736. var shaderPath = {
  77737. vertex: program.vertexShader + id,
  77738. fragment: program.fragmentShader + id
  77739. };
  77740. var options = {
  77741. attributes: attributes,
  77742. uniforms: uniforms,
  77743. samplers: samplers,
  77744. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  77745. };
  77746. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  77747. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  77748. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  77749. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  77750. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  77751. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77752. if (states && states.functions) {
  77753. var functions = states.functions;
  77754. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  77755. shaderMaterial.backFaceCulling = false;
  77756. }
  77757. var blendFunc = functions.blendFuncSeparate;
  77758. if (blendFunc) {
  77759. 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) {
  77760. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  77761. }
  77762. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77763. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77764. }
  77765. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77766. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  77767. }
  77768. 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) {
  77769. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  77770. }
  77771. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77772. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  77773. }
  77774. 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) {
  77775. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  77776. }
  77777. }
  77778. }
  77779. };
  77780. return GLTFLoaderBase;
  77781. }());
  77782. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  77783. /**
  77784. * glTF V1 Loader
  77785. */
  77786. var GLTFLoader = /** @class */ (function () {
  77787. function GLTFLoader() {
  77788. }
  77789. GLTFLoader.RegisterExtension = function (extension) {
  77790. if (GLTFLoader.Extensions[extension.name]) {
  77791. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  77792. return;
  77793. }
  77794. GLTFLoader.Extensions[extension.name] = extension;
  77795. };
  77796. GLTFLoader.prototype.dispose = function () {
  77797. // do nothing
  77798. };
  77799. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77800. var _this = this;
  77801. scene.useRightHandedSystem = true;
  77802. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77803. gltfRuntime.importOnlyMeshes = true;
  77804. if (meshesNames === "") {
  77805. gltfRuntime.importMeshesNames = [];
  77806. }
  77807. else if (typeof meshesNames === "string") {
  77808. gltfRuntime.importMeshesNames = [meshesNames];
  77809. }
  77810. else if (meshesNames && !(meshesNames instanceof Array)) {
  77811. gltfRuntime.importMeshesNames = [meshesNames];
  77812. }
  77813. else {
  77814. gltfRuntime.importMeshesNames = [];
  77815. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  77816. }
  77817. // Create nodes
  77818. _this._createNodes(gltfRuntime);
  77819. var meshes = new Array();
  77820. var skeletons = new Array();
  77821. // Fill arrays of meshes and skeletons
  77822. for (var nde in gltfRuntime.nodes) {
  77823. var node = gltfRuntime.nodes[nde];
  77824. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  77825. meshes.push(node.babylonNode);
  77826. }
  77827. }
  77828. for (var skl in gltfRuntime.skins) {
  77829. var skin = gltfRuntime.skins[skl];
  77830. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  77831. skeletons.push(skin.babylonSkeleton);
  77832. }
  77833. }
  77834. // Load buffers, shaders, materials, etc.
  77835. _this._loadBuffersAsync(gltfRuntime, function () {
  77836. _this._loadShadersAsync(gltfRuntime, function () {
  77837. importMaterials(gltfRuntime);
  77838. postLoad(gltfRuntime);
  77839. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77840. onSuccess(meshes, [], skeletons);
  77841. }
  77842. });
  77843. }, onProgress);
  77844. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77845. onSuccess(meshes, [], skeletons);
  77846. }
  77847. }, onError);
  77848. return true;
  77849. };
  77850. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77851. var _this = this;
  77852. scene.useRightHandedSystem = true;
  77853. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77854. // Load runtime extensios
  77855. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  77856. // Create nodes
  77857. _this._createNodes(gltfRuntime);
  77858. // Load buffers, shaders, materials, etc.
  77859. _this._loadBuffersAsync(gltfRuntime, function () {
  77860. _this._loadShadersAsync(gltfRuntime, function () {
  77861. importMaterials(gltfRuntime);
  77862. postLoad(gltfRuntime);
  77863. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  77864. onSuccess();
  77865. }
  77866. });
  77867. });
  77868. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  77869. onSuccess();
  77870. }
  77871. }, onError);
  77872. }, onError);
  77873. };
  77874. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  77875. var hasShaders = false;
  77876. var processShader = function (sha, shader) {
  77877. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  77878. gltfRuntime.loadedShaderCount++;
  77879. if (shaderString) {
  77880. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  77881. }
  77882. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  77883. onload();
  77884. }
  77885. }, function () {
  77886. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  77887. });
  77888. };
  77889. for (var sha in gltfRuntime.shaders) {
  77890. hasShaders = true;
  77891. var shader = gltfRuntime.shaders[sha];
  77892. if (shader) {
  77893. processShader.bind(this, sha, shader)();
  77894. }
  77895. else {
  77896. BABYLON.Tools.Error("No shader named: " + sha);
  77897. }
  77898. }
  77899. if (!hasShaders) {
  77900. onload();
  77901. }
  77902. };
  77903. ;
  77904. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  77905. var hasBuffers = false;
  77906. var processBuffer = function (buf, buffer) {
  77907. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  77908. gltfRuntime.loadedBufferCount++;
  77909. if (bufferView) {
  77910. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  77911. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  77912. }
  77913. gltfRuntime.loadedBufferViews[buf] = bufferView;
  77914. }
  77915. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  77916. onLoad();
  77917. }
  77918. }, function () {
  77919. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  77920. });
  77921. };
  77922. for (var buf in gltfRuntime.buffers) {
  77923. hasBuffers = true;
  77924. var buffer = gltfRuntime.buffers[buf];
  77925. if (buffer) {
  77926. processBuffer.bind(this, buf, buffer)();
  77927. }
  77928. else {
  77929. BABYLON.Tools.Error("No buffer named: " + buf);
  77930. }
  77931. }
  77932. if (!hasBuffers) {
  77933. onLoad();
  77934. }
  77935. };
  77936. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  77937. var currentScene = gltfRuntime.currentScene;
  77938. if (currentScene) {
  77939. // Only one scene even if multiple scenes are defined
  77940. for (var i = 0; i < currentScene.nodes.length; i++) {
  77941. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77942. }
  77943. }
  77944. else {
  77945. // Load all scenes
  77946. for (var thing in gltfRuntime.scenes) {
  77947. currentScene = gltfRuntime.scenes[thing];
  77948. for (var i = 0; i < currentScene.nodes.length; i++) {
  77949. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77950. }
  77951. }
  77952. }
  77953. };
  77954. GLTFLoader.Extensions = {};
  77955. return GLTFLoader;
  77956. }());
  77957. GLTF1.GLTFLoader = GLTFLoader;
  77958. ;
  77959. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  77960. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77961. })(BABYLON || (BABYLON = {}));
  77962. //# sourceMappingURL=babylon.glTFLoader.js.map
  77963. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77964. var BABYLON;
  77965. (function (BABYLON) {
  77966. var GLTF1;
  77967. (function (GLTF1) {
  77968. /**
  77969. * Utils functions for GLTF
  77970. */
  77971. var GLTFUtils = /** @class */ (function () {
  77972. function GLTFUtils() {
  77973. }
  77974. /**
  77975. * Sets the given "parameter" matrix
  77976. * @param scene: the {BABYLON.Scene} object
  77977. * @param source: the source node where to pick the matrix
  77978. * @param parameter: the GLTF technique parameter
  77979. * @param uniformName: the name of the shader's uniform
  77980. * @param shaderMaterial: the shader material
  77981. */
  77982. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  77983. var mat = null;
  77984. if (parameter.semantic === "MODEL") {
  77985. mat = source.getWorldMatrix();
  77986. }
  77987. else if (parameter.semantic === "PROJECTION") {
  77988. mat = scene.getProjectionMatrix();
  77989. }
  77990. else if (parameter.semantic === "VIEW") {
  77991. mat = scene.getViewMatrix();
  77992. }
  77993. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  77994. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  77995. }
  77996. else if (parameter.semantic === "MODELVIEW") {
  77997. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  77998. }
  77999. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  78000. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  78001. }
  78002. else if (parameter.semantic === "MODELINVERSE") {
  78003. mat = source.getWorldMatrix().invert();
  78004. }
  78005. else if (parameter.semantic === "VIEWINVERSE") {
  78006. mat = scene.getViewMatrix().invert();
  78007. }
  78008. else if (parameter.semantic === "PROJECTIONINVERSE") {
  78009. mat = scene.getProjectionMatrix().invert();
  78010. }
  78011. else if (parameter.semantic === "MODELVIEWINVERSE") {
  78012. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  78013. }
  78014. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  78015. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  78016. }
  78017. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  78018. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  78019. }
  78020. else {
  78021. debugger;
  78022. }
  78023. if (mat) {
  78024. switch (parameter.type) {
  78025. case GLTF1.EParameterType.FLOAT_MAT2:
  78026. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  78027. break;
  78028. case GLTF1.EParameterType.FLOAT_MAT3:
  78029. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  78030. break;
  78031. case GLTF1.EParameterType.FLOAT_MAT4:
  78032. shaderMaterial.setMatrix(uniformName, mat);
  78033. break;
  78034. default: break;
  78035. }
  78036. }
  78037. };
  78038. /**
  78039. * Sets the given "parameter" matrix
  78040. * @param shaderMaterial: the shader material
  78041. * @param uniform: the name of the shader's uniform
  78042. * @param value: the value of the uniform
  78043. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  78044. */
  78045. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  78046. switch (type) {
  78047. case GLTF1.EParameterType.FLOAT:
  78048. shaderMaterial.setFloat(uniform, value);
  78049. return true;
  78050. case GLTF1.EParameterType.FLOAT_VEC2:
  78051. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  78052. return true;
  78053. case GLTF1.EParameterType.FLOAT_VEC3:
  78054. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  78055. return true;
  78056. case GLTF1.EParameterType.FLOAT_VEC4:
  78057. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  78058. return true;
  78059. default: return false;
  78060. }
  78061. };
  78062. /**
  78063. * If the uri is a base64 string
  78064. * @param uri: the uri to test
  78065. */
  78066. GLTFUtils.IsBase64 = function (uri) {
  78067. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  78068. };
  78069. /**
  78070. * Decode the base64 uri
  78071. * @param uri: the uri to decode
  78072. */
  78073. GLTFUtils.DecodeBase64 = function (uri) {
  78074. var decodedString = atob(uri.split(",")[1]);
  78075. var bufferLength = decodedString.length;
  78076. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  78077. for (var i = 0; i < bufferLength; i++) {
  78078. bufferView[i] = decodedString.charCodeAt(i);
  78079. }
  78080. return bufferView.buffer;
  78081. };
  78082. /**
  78083. * Returns the wrap mode of the texture
  78084. * @param mode: the mode value
  78085. */
  78086. GLTFUtils.GetWrapMode = function (mode) {
  78087. switch (mode) {
  78088. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  78089. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  78090. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  78091. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  78092. }
  78093. };
  78094. /**
  78095. * Returns the byte stride giving an accessor
  78096. * @param accessor: the GLTF accessor objet
  78097. */
  78098. GLTFUtils.GetByteStrideFromType = function (accessor) {
  78099. // Needs this function since "byteStride" isn't requiered in glTF format
  78100. var type = accessor.type;
  78101. switch (type) {
  78102. case "VEC2": return 2;
  78103. case "VEC3": return 3;
  78104. case "VEC4": return 4;
  78105. case "MAT2": return 4;
  78106. case "MAT3": return 9;
  78107. case "MAT4": return 16;
  78108. default: return 1;
  78109. }
  78110. };
  78111. /**
  78112. * Returns the texture filter mode giving a mode value
  78113. * @param mode: the filter mode value
  78114. */
  78115. GLTFUtils.GetTextureFilterMode = function (mode) {
  78116. switch (mode) {
  78117. case GLTF1.ETextureFilterType.LINEAR:
  78118. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  78119. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  78120. case GLTF1.ETextureFilterType.NEAREST:
  78121. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  78122. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  78123. }
  78124. };
  78125. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  78126. var byteOffset = bufferView.byteOffset + byteOffset;
  78127. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  78128. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  78129. throw new Error("Buffer access is out of range");
  78130. }
  78131. var buffer = loadedBufferView.buffer;
  78132. byteOffset += loadedBufferView.byteOffset;
  78133. switch (componentType) {
  78134. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  78135. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  78136. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  78137. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  78138. default: return new Float32Array(buffer, byteOffset, byteLength);
  78139. }
  78140. };
  78141. /**
  78142. * Returns a buffer from its accessor
  78143. * @param gltfRuntime: the GLTF runtime
  78144. * @param accessor: the GLTF accessor
  78145. */
  78146. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  78147. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  78148. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  78149. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  78150. };
  78151. /**
  78152. * Decodes a buffer view into a string
  78153. * @param view: the buffer view
  78154. */
  78155. GLTFUtils.DecodeBufferToText = function (view) {
  78156. var result = "";
  78157. var length = view.byteLength;
  78158. for (var i = 0; i < length; ++i) {
  78159. result += String.fromCharCode(view[i]);
  78160. }
  78161. return result;
  78162. };
  78163. /**
  78164. * Returns the default material of gltf. Related to
  78165. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  78166. * @param scene: the Babylon.js scene
  78167. */
  78168. GLTFUtils.GetDefaultMaterial = function (scene) {
  78169. if (!GLTFUtils._DefaultMaterial) {
  78170. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  78171. "precision highp float;",
  78172. "",
  78173. "uniform mat4 worldView;",
  78174. "uniform mat4 projection;",
  78175. "",
  78176. "attribute vec3 position;",
  78177. "",
  78178. "void main(void)",
  78179. "{",
  78180. " gl_Position = projection * worldView * vec4(position, 1.0);",
  78181. "}"
  78182. ].join("\n");
  78183. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  78184. "precision highp float;",
  78185. "",
  78186. "uniform vec4 u_emission;",
  78187. "",
  78188. "void main(void)",
  78189. "{",
  78190. " gl_FragColor = u_emission;",
  78191. "}"
  78192. ].join("\n");
  78193. var shaderPath = {
  78194. vertex: "GLTFDefaultMaterial",
  78195. fragment: "GLTFDefaultMaterial"
  78196. };
  78197. var options = {
  78198. attributes: ["position"],
  78199. uniforms: ["worldView", "projection", "u_emission"],
  78200. samplers: new Array(),
  78201. needAlphaBlending: false
  78202. };
  78203. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  78204. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  78205. }
  78206. return GLTFUtils._DefaultMaterial;
  78207. };
  78208. // The GLTF default material
  78209. GLTFUtils._DefaultMaterial = null;
  78210. return GLTFUtils;
  78211. }());
  78212. GLTF1.GLTFUtils = GLTFUtils;
  78213. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78214. })(BABYLON || (BABYLON = {}));
  78215. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  78216. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78217. var BABYLON;
  78218. (function (BABYLON) {
  78219. var GLTF1;
  78220. (function (GLTF1) {
  78221. var GLTFLoaderExtension = /** @class */ (function () {
  78222. function GLTFLoaderExtension(name) {
  78223. this._name = name;
  78224. }
  78225. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  78226. get: function () {
  78227. return this._name;
  78228. },
  78229. enumerable: true,
  78230. configurable: true
  78231. });
  78232. /**
  78233. * Defines an override for loading the runtime
  78234. * Return true to stop further extensions from loading the runtime
  78235. */
  78236. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78237. return false;
  78238. };
  78239. /**
  78240. * Defines an onverride for creating gltf runtime
  78241. * Return true to stop further extensions from creating the runtime
  78242. */
  78243. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78244. return false;
  78245. };
  78246. /**
  78247. * Defines an override for loading buffers
  78248. * Return true to stop further extensions from loading this buffer
  78249. */
  78250. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  78251. return false;
  78252. };
  78253. /**
  78254. * Defines an override for loading texture buffers
  78255. * Return true to stop further extensions from loading this texture data
  78256. */
  78257. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78258. return false;
  78259. };
  78260. /**
  78261. * Defines an override for creating textures
  78262. * Return true to stop further extensions from loading this texture
  78263. */
  78264. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78265. return false;
  78266. };
  78267. /**
  78268. * Defines an override for loading shader strings
  78269. * Return true to stop further extensions from loading this shader data
  78270. */
  78271. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78272. return false;
  78273. };
  78274. /**
  78275. * Defines an override for loading materials
  78276. * Return true to stop further extensions from loading this material
  78277. */
  78278. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78279. return false;
  78280. };
  78281. // ---------
  78282. // Utilities
  78283. // ---------
  78284. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78285. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78286. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  78287. }, function () {
  78288. setTimeout(function () {
  78289. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  78290. });
  78291. });
  78292. };
  78293. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78294. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78295. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  78296. }, function () {
  78297. setTimeout(function () {
  78298. onSuccess();
  78299. });
  78300. });
  78301. };
  78302. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  78303. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78304. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  78305. }, function () {
  78306. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  78307. });
  78308. };
  78309. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  78310. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  78311. };
  78312. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78313. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78314. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  78315. }, function () {
  78316. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  78317. });
  78318. };
  78319. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78320. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78321. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  78322. }, function () {
  78323. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  78324. });
  78325. };
  78326. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78327. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78328. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  78329. }, function () {
  78330. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  78331. });
  78332. };
  78333. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78334. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78335. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  78336. }, function () {
  78337. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  78338. });
  78339. };
  78340. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  78341. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  78342. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  78343. if (func(loaderExtension)) {
  78344. return;
  78345. }
  78346. }
  78347. defaultFunc();
  78348. };
  78349. return GLTFLoaderExtension;
  78350. }());
  78351. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  78352. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78353. })(BABYLON || (BABYLON = {}));
  78354. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  78355. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78356. var BABYLON;
  78357. (function (BABYLON) {
  78358. var GLTF1;
  78359. (function (GLTF1) {
  78360. var BinaryExtensionBufferName = "binary_glTF";
  78361. ;
  78362. ;
  78363. var GLTFBinaryExtension = /** @class */ (function (_super) {
  78364. __extends(GLTFBinaryExtension, _super);
  78365. function GLTFBinaryExtension() {
  78366. return _super.call(this, "KHR_binary_glTF") || this;
  78367. }
  78368. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78369. var extensionsUsed = data.json.extensionsUsed;
  78370. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  78371. return false;
  78372. }
  78373. this._bin = data.bin;
  78374. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  78375. return true;
  78376. };
  78377. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78378. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  78379. return false;
  78380. }
  78381. if (id !== BinaryExtensionBufferName) {
  78382. return false;
  78383. }
  78384. onSuccess(this._bin);
  78385. return true;
  78386. };
  78387. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78388. var texture = gltfRuntime.textures[id];
  78389. var source = gltfRuntime.images[texture.source];
  78390. if (!source.extensions || !(this.name in source.extensions)) {
  78391. return false;
  78392. }
  78393. var sourceExt = source.extensions[this.name];
  78394. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  78395. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78396. onSuccess(buffer);
  78397. return true;
  78398. };
  78399. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78400. var shader = gltfRuntime.shaders[id];
  78401. if (!shader.extensions || !(this.name in shader.extensions)) {
  78402. return false;
  78403. }
  78404. var binaryExtensionShader = shader.extensions[this.name];
  78405. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  78406. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78407. setTimeout(function () {
  78408. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  78409. onSuccess(shaderString);
  78410. });
  78411. return true;
  78412. };
  78413. return GLTFBinaryExtension;
  78414. }(GLTF1.GLTFLoaderExtension));
  78415. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  78416. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  78417. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78418. })(BABYLON || (BABYLON = {}));
  78419. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  78420. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78421. var BABYLON;
  78422. (function (BABYLON) {
  78423. var GLTF1;
  78424. (function (GLTF1) {
  78425. ;
  78426. ;
  78427. ;
  78428. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  78429. __extends(GLTFMaterialsCommonExtension, _super);
  78430. function GLTFMaterialsCommonExtension() {
  78431. return _super.call(this, "KHR_materials_common") || this;
  78432. }
  78433. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78434. if (!gltfRuntime.extensions)
  78435. return false;
  78436. var extension = gltfRuntime.extensions[this.name];
  78437. if (!extension)
  78438. return false;
  78439. // Create lights
  78440. var lights = extension.lights;
  78441. if (lights) {
  78442. for (var thing in lights) {
  78443. var light = lights[thing];
  78444. switch (light.type) {
  78445. case "ambient":
  78446. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  78447. var ambient = light.ambient;
  78448. if (ambient) {
  78449. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  78450. }
  78451. break;
  78452. case "point":
  78453. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  78454. var point = light.point;
  78455. if (point) {
  78456. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  78457. }
  78458. break;
  78459. case "directional":
  78460. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  78461. var directional = light.directional;
  78462. if (directional) {
  78463. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  78464. }
  78465. break;
  78466. case "spot":
  78467. var spot = light.spot;
  78468. if (spot) {
  78469. 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);
  78470. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  78471. }
  78472. break;
  78473. default:
  78474. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  78475. break;
  78476. }
  78477. }
  78478. }
  78479. return false;
  78480. };
  78481. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78482. var material = gltfRuntime.materials[id];
  78483. if (!material || !material.extensions)
  78484. return false;
  78485. var extension = material.extensions[this.name];
  78486. if (!extension)
  78487. return false;
  78488. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  78489. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78490. if (extension.technique === "CONSTANT") {
  78491. standardMaterial.disableLighting = true;
  78492. }
  78493. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  78494. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  78495. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  78496. // Ambient
  78497. if (typeof extension.values.ambient === "string") {
  78498. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  78499. }
  78500. else {
  78501. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  78502. }
  78503. // Diffuse
  78504. if (typeof extension.values.diffuse === "string") {
  78505. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  78506. }
  78507. else {
  78508. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  78509. }
  78510. // Emission
  78511. if (typeof extension.values.emission === "string") {
  78512. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  78513. }
  78514. else {
  78515. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  78516. }
  78517. // Specular
  78518. if (typeof extension.values.specular === "string") {
  78519. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  78520. }
  78521. else {
  78522. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  78523. }
  78524. return true;
  78525. };
  78526. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  78527. // Create buffer from texture url
  78528. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  78529. // Create texture from buffer
  78530. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  78531. }, onError);
  78532. };
  78533. return GLTFMaterialsCommonExtension;
  78534. }(GLTF1.GLTFLoaderExtension));
  78535. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  78536. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  78537. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78538. })(BABYLON || (BABYLON = {}));
  78539. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  78540. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78541. var BABYLON;
  78542. (function (BABYLON) {
  78543. var GLTF2;
  78544. (function (GLTF2) {
  78545. /**
  78546. * Enums
  78547. */
  78548. var EComponentType;
  78549. (function (EComponentType) {
  78550. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  78551. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78552. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  78553. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78554. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  78555. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  78556. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  78557. var EMeshPrimitiveMode;
  78558. (function (EMeshPrimitiveMode) {
  78559. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  78560. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  78561. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  78562. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  78563. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  78564. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  78565. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  78566. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  78567. var ETextureMagFilter;
  78568. (function (ETextureMagFilter) {
  78569. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  78570. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  78571. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  78572. var ETextureMinFilter;
  78573. (function (ETextureMinFilter) {
  78574. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  78575. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  78576. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  78577. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  78578. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  78579. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  78580. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  78581. var ETextureWrapMode;
  78582. (function (ETextureWrapMode) {
  78583. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  78584. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  78585. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  78586. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  78587. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  78588. })(BABYLON || (BABYLON = {}));
  78589. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  78590. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78591. var BABYLON;
  78592. (function (BABYLON) {
  78593. var GLTF2;
  78594. (function (GLTF2) {
  78595. var GLTFLoaderTracker = /** @class */ (function () {
  78596. function GLTFLoaderTracker(onComplete) {
  78597. this._pendingCount = 0;
  78598. this._callback = onComplete;
  78599. }
  78600. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  78601. this._pendingCount++;
  78602. };
  78603. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  78604. if (--this._pendingCount === 0) {
  78605. this._callback();
  78606. }
  78607. };
  78608. return GLTFLoaderTracker;
  78609. }());
  78610. var GLTFLoader = /** @class */ (function () {
  78611. function GLTFLoader(parent) {
  78612. this._disposed = false;
  78613. this._renderReady = false;
  78614. this._requests = new Array();
  78615. this._renderReadyObservable = new BABYLON.Observable();
  78616. // Count of pending work that needs to complete before the asset is rendered.
  78617. this._renderPendingCount = 0;
  78618. // Count of pending work that needs to complete before the loader is disposed.
  78619. this._loaderPendingCount = 0;
  78620. this._loaderTrackers = new Array();
  78621. this._parent = parent;
  78622. }
  78623. GLTFLoader.RegisterExtension = function (extension) {
  78624. if (GLTFLoader.Extensions[extension.name]) {
  78625. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  78626. return;
  78627. }
  78628. GLTFLoader.Extensions[extension.name] = extension;
  78629. // Keep the order of registration so that extensions registered first are called first.
  78630. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  78631. };
  78632. GLTFLoader.prototype.dispose = function () {
  78633. if (this._disposed) {
  78634. return;
  78635. }
  78636. this._disposed = true;
  78637. // Abort requests that are not complete
  78638. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  78639. var request = _a[_i];
  78640. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  78641. request.abort();
  78642. }
  78643. }
  78644. // Revoke object urls created during load
  78645. if (this._gltf.textures) {
  78646. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  78647. var texture = _c[_b];
  78648. if (texture.url) {
  78649. URL.revokeObjectURL(texture.url);
  78650. }
  78651. }
  78652. }
  78653. };
  78654. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78655. var _this = this;
  78656. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  78657. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  78658. }, onProgress, onError);
  78659. };
  78660. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  78661. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  78662. };
  78663. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78664. var _this = this;
  78665. this._tryCatchOnError(function () {
  78666. _this._loadData(data);
  78667. _this._babylonScene = scene;
  78668. _this._rootUrl = rootUrl;
  78669. _this._successCallback = onSuccess;
  78670. _this._progressCallback = onProgress;
  78671. _this._errorCallback = onError;
  78672. _this._addPendingData(_this);
  78673. _this._loadDefaultScene(nodeNames);
  78674. _this._loadAnimations();
  78675. _this._removePendingData(_this);
  78676. });
  78677. };
  78678. GLTFLoader.prototype._onProgress = function (event) {
  78679. if (this._progressCallback) {
  78680. this._progressCallback(event);
  78681. }
  78682. };
  78683. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  78684. if (this._renderReady) {
  78685. func();
  78686. }
  78687. else {
  78688. this._renderReadyObservable.add(func);
  78689. }
  78690. };
  78691. GLTFLoader.prototype._onRenderReady = function () {
  78692. this._rootNode.babylonMesh.setEnabled(true);
  78693. this._startAnimations();
  78694. this._successCallback();
  78695. this._renderReadyObservable.notifyObservers(this);
  78696. };
  78697. GLTFLoader.prototype._onComplete = function () {
  78698. if (this._parent.onComplete) {
  78699. this._parent.onComplete();
  78700. }
  78701. this.dispose();
  78702. };
  78703. GLTFLoader.prototype._loadData = function (data) {
  78704. this._gltf = data.json;
  78705. // Assign the index of each object for convinience.
  78706. GLTFLoader._AssignIndices(this._gltf.accessors);
  78707. GLTFLoader._AssignIndices(this._gltf.animations);
  78708. GLTFLoader._AssignIndices(this._gltf.buffers);
  78709. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  78710. GLTFLoader._AssignIndices(this._gltf.images);
  78711. GLTFLoader._AssignIndices(this._gltf.materials);
  78712. GLTFLoader._AssignIndices(this._gltf.meshes);
  78713. GLTFLoader._AssignIndices(this._gltf.nodes);
  78714. GLTFLoader._AssignIndices(this._gltf.scenes);
  78715. GLTFLoader._AssignIndices(this._gltf.skins);
  78716. GLTFLoader._AssignIndices(this._gltf.textures);
  78717. if (data.bin) {
  78718. var buffers = this._gltf.buffers;
  78719. if (buffers && buffers[0] && !buffers[0].uri) {
  78720. var binaryBuffer = buffers[0];
  78721. if (binaryBuffer.byteLength != data.bin.byteLength) {
  78722. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  78723. }
  78724. binaryBuffer.loadedData = data.bin;
  78725. }
  78726. else {
  78727. BABYLON.Tools.Warn("Unexpected BIN chunk");
  78728. }
  78729. }
  78730. };
  78731. GLTFLoader.prototype._getMeshes = function () {
  78732. var meshes = new Array();
  78733. // Root mesh is always first.
  78734. meshes.push(this._rootNode.babylonMesh);
  78735. var nodes = this._gltf.nodes;
  78736. if (nodes) {
  78737. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  78738. var node = nodes_1[_i];
  78739. if (node.babylonMesh) {
  78740. meshes.push(node.babylonMesh);
  78741. }
  78742. }
  78743. }
  78744. return meshes;
  78745. };
  78746. GLTFLoader.prototype._getSkeletons = function () {
  78747. var skeletons = new Array();
  78748. var skins = this._gltf.skins;
  78749. if (skins) {
  78750. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  78751. var skin = skins_1[_i];
  78752. if (skin.babylonSkeleton) {
  78753. skeletons.push(skin.babylonSkeleton);
  78754. }
  78755. }
  78756. }
  78757. return skeletons;
  78758. };
  78759. GLTFLoader.prototype._getAnimationTargets = function () {
  78760. var targets = new Array();
  78761. var animations = this._gltf.animations;
  78762. if (animations) {
  78763. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  78764. var animation = animations_1[_i];
  78765. targets.push.apply(targets, animation.targets);
  78766. }
  78767. }
  78768. return targets;
  78769. };
  78770. GLTFLoader.prototype._startAnimations = function () {
  78771. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  78772. var target = _a[_i];
  78773. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  78774. }
  78775. };
  78776. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  78777. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  78778. if (!scene) {
  78779. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  78780. }
  78781. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  78782. };
  78783. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  78784. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  78785. switch (this._parent.coordinateSystemMode) {
  78786. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  78787. if (!this._babylonScene.useRightHandedSystem) {
  78788. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  78789. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  78790. }
  78791. break;
  78792. }
  78793. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  78794. // do nothing
  78795. break;
  78796. }
  78797. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  78798. this._babylonScene.useRightHandedSystem = true;
  78799. break;
  78800. }
  78801. default: {
  78802. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  78803. return;
  78804. }
  78805. }
  78806. var nodeIndices = scene.nodes;
  78807. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  78808. node.parent = parentNode;
  78809. return true;
  78810. }, this._rootNode);
  78811. if (nodeNames) {
  78812. if (!(nodeNames instanceof Array)) {
  78813. nodeNames = [nodeNames];
  78814. }
  78815. var filteredNodeIndices_1 = new Array();
  78816. this._traverseNodes(context, nodeIndices, function (node) {
  78817. if (nodeNames.indexOf(node.name) !== -1) {
  78818. filteredNodeIndices_1.push(node.index);
  78819. return false;
  78820. }
  78821. return true;
  78822. }, this._rootNode);
  78823. nodeIndices = filteredNodeIndices_1;
  78824. }
  78825. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  78826. var index = nodeIndices_1[_i];
  78827. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78828. if (!node) {
  78829. throw new Error(context + ": Failed to find node " + index);
  78830. }
  78831. this._loadNode("#/nodes/" + index, node);
  78832. }
  78833. // Disable the root mesh until the asset is ready to render.
  78834. this._rootNode.babylonMesh.setEnabled(false);
  78835. };
  78836. GLTFLoader.prototype._loadNode = function (context, node) {
  78837. node.babylonBones = {};
  78838. node.babylonAnimationTargets = [];
  78839. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  78840. return;
  78841. }
  78842. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  78843. node.babylonMesh.hasVertexAlpha = true;
  78844. this._loadTransform(node);
  78845. if (node.mesh != null) {
  78846. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  78847. if (!mesh) {
  78848. throw new Error(context + ": Failed to find mesh " + node.mesh);
  78849. }
  78850. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  78851. }
  78852. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  78853. node.babylonAnimationTargets.push(node.babylonMesh);
  78854. if (node.skin != null) {
  78855. var skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  78856. if (!skin) {
  78857. throw new Error(context + ": Failed to find skin " + node.skin);
  78858. }
  78859. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  78860. }
  78861. if (node.camera != null) {
  78862. // TODO: handle cameras
  78863. }
  78864. if (node.children) {
  78865. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  78866. var index = _a[_i];
  78867. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78868. if (!childNode) {
  78869. throw new Error(context + ": Failed to find child node " + index);
  78870. }
  78871. this._loadNode("#/nodes/" + index, childNode);
  78872. }
  78873. }
  78874. };
  78875. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  78876. var _this = this;
  78877. var primitives = mesh.primitives;
  78878. if (!primitives || primitives.length === 0) {
  78879. throw new Error(context + ": Primitives are missing");
  78880. }
  78881. this._createMorphTargets(context, node, mesh);
  78882. this._loadAllVertexDataAsync(context, mesh, function () {
  78883. _this._loadMorphTargets(context, node, mesh);
  78884. var vertexData = new BABYLON.VertexData();
  78885. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  78886. var primitive = primitives_1[_i];
  78887. vertexData.merge(primitive.vertexData);
  78888. }
  78889. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  78890. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  78891. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  78892. node.babylonMesh.subMeshes = [];
  78893. var verticesStart = 0;
  78894. var indicesStart = 0;
  78895. for (var index = 0; index < primitives.length; index++) {
  78896. var vertexData_1 = primitives[index].vertexData;
  78897. var verticesCount = vertexData_1.positions.length;
  78898. var indicesCount = vertexData_1.indices.length;
  78899. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  78900. verticesStart += verticesCount;
  78901. indicesStart += indicesCount;
  78902. }
  78903. ;
  78904. });
  78905. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  78906. node.babylonMesh.material = multiMaterial;
  78907. var subMaterials = multiMaterial.subMaterials;
  78908. var _loop_1 = function (index) {
  78909. var primitive = primitives[index];
  78910. if (primitive.material == null) {
  78911. subMaterials[index] = this_1._getDefaultMaterial();
  78912. }
  78913. else {
  78914. var material_1 = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  78915. if (!material_1) {
  78916. throw new Error(context + ": Failed to find material " + primitive.material);
  78917. }
  78918. this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) {
  78919. if (isNew && _this._parent.onMaterialLoaded) {
  78920. _this._parent.onMaterialLoaded(babylonMaterial);
  78921. }
  78922. if (_this._parent.onBeforeMaterialReadyAsync) {
  78923. _this._addLoaderPendingData(material_1);
  78924. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  78925. _this._tryCatchOnError(function () {
  78926. subMaterials[index] = babylonMaterial;
  78927. _this._removeLoaderPendingData(material_1);
  78928. });
  78929. });
  78930. }
  78931. else {
  78932. subMaterials[index] = babylonMaterial;
  78933. }
  78934. });
  78935. }
  78936. };
  78937. var this_1 = this;
  78938. for (var index = 0; index < primitives.length; index++) {
  78939. _loop_1(index);
  78940. }
  78941. ;
  78942. };
  78943. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  78944. var primitives = mesh.primitives;
  78945. var numRemainingPrimitives = primitives.length;
  78946. var _loop_2 = function (index) {
  78947. var primitive = primitives[index];
  78948. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  78949. primitive.vertexData = vertexData;
  78950. if (--numRemainingPrimitives === 0) {
  78951. onSuccess();
  78952. }
  78953. });
  78954. };
  78955. var this_2 = this;
  78956. for (var index = 0; index < primitives.length; index++) {
  78957. _loop_2(index);
  78958. }
  78959. };
  78960. /**
  78961. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  78962. * @param {ArrayBufferView} data
  78963. * @param {IGLTFAccessor} accessor
  78964. */
  78965. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  78966. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  78967. return data;
  78968. }
  78969. var buffer = data;
  78970. var factor = 1;
  78971. switch (accessor.componentType) {
  78972. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78973. factor = 1 / 255;
  78974. break;
  78975. }
  78976. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78977. factor = 1 / 65535;
  78978. break;
  78979. }
  78980. default: {
  78981. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78982. }
  78983. }
  78984. var result = new Float32Array(accessor.count * 2);
  78985. for (var i = 0; i < result.length; ++i) {
  78986. result[i] = buffer[i] * factor;
  78987. }
  78988. return result;
  78989. };
  78990. /**
  78991. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  78992. * @param {ArrayBufferView} data
  78993. * @param {IGLTFAccessor} accessor
  78994. */
  78995. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  78996. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  78997. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  78998. return data;
  78999. }
  79000. var buffer = data;
  79001. var factor = 1;
  79002. switch (accessor.componentType) {
  79003. case GLTF2.EComponentType.FLOAT: {
  79004. factor = 1;
  79005. break;
  79006. }
  79007. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  79008. factor = 1 / 255;
  79009. break;
  79010. }
  79011. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  79012. factor = 1 / 65535;
  79013. break;
  79014. }
  79015. default: {
  79016. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  79017. }
  79018. }
  79019. var result = new Float32Array(accessor.count * 4);
  79020. if (colorComponentCount === 4) {
  79021. for (var i = 0; i < result.length; ++i) {
  79022. result[i] = buffer[i] * factor;
  79023. }
  79024. }
  79025. else {
  79026. var offset = 0;
  79027. for (var i = 0; i < result.length; ++i) {
  79028. if ((i + 1) % 4 === 0) {
  79029. result[i] = 1;
  79030. }
  79031. else {
  79032. result[i] = buffer[offset++] * factor;
  79033. }
  79034. }
  79035. }
  79036. return result;
  79037. };
  79038. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  79039. var _this = this;
  79040. var attributes = primitive.attributes;
  79041. if (!attributes) {
  79042. throw new Error(context + ": Attributes are missing");
  79043. }
  79044. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  79045. // TODO: handle other primitive modes
  79046. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  79047. }
  79048. var vertexData = new BABYLON.VertexData();
  79049. var numRemainingAttributes = Object.keys(attributes).length;
  79050. var _loop_3 = function (attribute) {
  79051. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  79052. if (!accessor) {
  79053. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  79054. }
  79055. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  79056. switch (attribute) {
  79057. case "POSITION": {
  79058. vertexData.positions = data;
  79059. break;
  79060. }
  79061. case "NORMAL": {
  79062. vertexData.normals = data;
  79063. break;
  79064. }
  79065. case "TANGENT": {
  79066. vertexData.tangents = data;
  79067. break;
  79068. }
  79069. case "TEXCOORD_0": {
  79070. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  79071. break;
  79072. }
  79073. case "TEXCOORD_1": {
  79074. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  79075. break;
  79076. }
  79077. case "JOINTS_0": {
  79078. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  79079. break;
  79080. }
  79081. case "WEIGHTS_0": {
  79082. //TODO: need to add support for normalized weights.
  79083. vertexData.matricesWeights = data;
  79084. break;
  79085. }
  79086. case "COLOR_0": {
  79087. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  79088. break;
  79089. }
  79090. default: {
  79091. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  79092. break;
  79093. }
  79094. }
  79095. if (--numRemainingAttributes === 0) {
  79096. if (primitive.indices == null) {
  79097. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  79098. for (var i = 0; i < vertexData.indices.length; i++) {
  79099. vertexData.indices[i] = i;
  79100. }
  79101. onSuccess(vertexData);
  79102. }
  79103. else {
  79104. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  79105. if (!indicesAccessor) {
  79106. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  79107. }
  79108. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  79109. vertexData.indices = data;
  79110. onSuccess(vertexData);
  79111. });
  79112. }
  79113. }
  79114. });
  79115. };
  79116. var this_3 = this;
  79117. for (var attribute in attributes) {
  79118. _loop_3(attribute);
  79119. }
  79120. };
  79121. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  79122. var primitives = mesh.primitives;
  79123. var targets = primitives[0].targets;
  79124. if (!targets) {
  79125. return;
  79126. }
  79127. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  79128. var primitive = primitives_2[_i];
  79129. if (!primitive.targets || primitive.targets.length != targets.length) {
  79130. throw new Error(context + ": All primitives are required to list the same number of targets");
  79131. }
  79132. }
  79133. var morphTargetManager = new BABYLON.MorphTargetManager();
  79134. node.babylonMesh.morphTargetManager = morphTargetManager;
  79135. for (var index = 0; index < targets.length; index++) {
  79136. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  79137. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  79138. }
  79139. };
  79140. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  79141. var morphTargetManager = node.babylonMesh.morphTargetManager;
  79142. if (!morphTargetManager) {
  79143. return;
  79144. }
  79145. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  79146. var numTargets = morphTargetManager.numTargets;
  79147. for (var index = 0; index < numTargets; index++) {
  79148. var vertexData = new BABYLON.VertexData();
  79149. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  79150. var primitive = _a[_i];
  79151. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  79152. }
  79153. if (!vertexData.positions) {
  79154. throw new Error(context + ": Positions are missing");
  79155. }
  79156. var target = morphTargetManager.getTarget(index);
  79157. target.setPositions(vertexData.positions);
  79158. target.setNormals(vertexData.normals);
  79159. target.setTangents(vertexData.tangents);
  79160. }
  79161. });
  79162. };
  79163. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  79164. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  79165. var _loop_4 = function (primitive) {
  79166. var targets = primitive.targets;
  79167. primitive.targetsVertexData = new Array(targets.length);
  79168. var _loop_5 = function (index) {
  79169. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  79170. primitive.targetsVertexData[index] = vertexData;
  79171. if (--numRemainingTargets === 0) {
  79172. onSuccess();
  79173. }
  79174. });
  79175. };
  79176. for (var index = 0; index < targets.length; index++) {
  79177. _loop_5(index);
  79178. }
  79179. };
  79180. var this_4 = this;
  79181. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  79182. var primitive = _a[_i];
  79183. _loop_4(primitive);
  79184. }
  79185. };
  79186. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  79187. var targetVertexData = new BABYLON.VertexData();
  79188. var numRemainingAttributes = Object.keys(attributes).length;
  79189. var _loop_6 = function (attribute) {
  79190. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  79191. if (!accessor) {
  79192. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  79193. }
  79194. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  79195. // glTF stores morph target information as deltas while babylon.js expects the final data.
  79196. // As a result we have to add the original data to the delta to calculate the final data.
  79197. var values = data;
  79198. switch (attribute) {
  79199. case "POSITION": {
  79200. for (var i = 0; i < values.length; i++) {
  79201. values[i] += vertexData.positions[i];
  79202. }
  79203. targetVertexData.positions = values;
  79204. break;
  79205. }
  79206. case "NORMAL": {
  79207. for (var i = 0; i < values.length; i++) {
  79208. values[i] += vertexData.normals[i];
  79209. }
  79210. targetVertexData.normals = values;
  79211. break;
  79212. }
  79213. case "TANGENT": {
  79214. // Tangent data for morph targets is stored as xyz delta.
  79215. // The vertexData.tangent is stored as xyzw.
  79216. // So we need to skip every fourth vertexData.tangent.
  79217. for (var i = 0, j = 0; i < values.length; i++, j++) {
  79218. values[i] += vertexData.tangents[j];
  79219. if ((i + 1) % 3 == 0) {
  79220. j++;
  79221. }
  79222. }
  79223. targetVertexData.tangents = values;
  79224. break;
  79225. }
  79226. default: {
  79227. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  79228. break;
  79229. }
  79230. }
  79231. if (--numRemainingAttributes === 0) {
  79232. onSuccess(targetVertexData);
  79233. }
  79234. });
  79235. };
  79236. var this_5 = this;
  79237. for (var attribute in attributes) {
  79238. _loop_6(attribute);
  79239. }
  79240. };
  79241. GLTFLoader.prototype._loadTransform = function (node) {
  79242. var position = BABYLON.Vector3.Zero();
  79243. var rotation = BABYLON.Quaternion.Identity();
  79244. var scaling = BABYLON.Vector3.One();
  79245. if (node.matrix) {
  79246. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  79247. matrix.decompose(scaling, rotation, position);
  79248. }
  79249. else {
  79250. if (node.translation)
  79251. position = BABYLON.Vector3.FromArray(node.translation);
  79252. if (node.rotation)
  79253. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  79254. if (node.scale)
  79255. scaling = BABYLON.Vector3.FromArray(node.scale);
  79256. }
  79257. node.babylonMesh.position = position;
  79258. node.babylonMesh.rotationQuaternion = rotation;
  79259. node.babylonMesh.scaling = scaling;
  79260. };
  79261. GLTFLoader.prototype._loadSkin = function (context, skin) {
  79262. var _this = this;
  79263. var skeletonId = "skeleton" + skin.index;
  79264. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  79265. if (skin.inverseBindMatrices == null) {
  79266. this._loadBones(context, skin, null);
  79267. }
  79268. else {
  79269. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  79270. if (!accessor) {
  79271. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  79272. }
  79273. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  79274. _this._loadBones(context, skin, data);
  79275. });
  79276. }
  79277. return skin.babylonSkeleton;
  79278. };
  79279. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  79280. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  79281. node.babylonBones[skin.index] = babylonBone;
  79282. node.babylonAnimationTargets.push(babylonBone);
  79283. return babylonBone;
  79284. };
  79285. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  79286. var babylonBones = {};
  79287. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  79288. var index = _a[_i];
  79289. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79290. if (!node) {
  79291. throw new Error(context + ": Failed to find joint " + index);
  79292. }
  79293. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  79294. }
  79295. };
  79296. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  79297. var babylonBone = babylonBones[node.index];
  79298. if (babylonBone) {
  79299. return babylonBone;
  79300. }
  79301. var boneIndex = skin.joints.indexOf(node.index);
  79302. var baseMatrix = BABYLON.Matrix.Identity();
  79303. if (inverseBindMatrixData && boneIndex !== -1) {
  79304. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  79305. baseMatrix.invertToRef(baseMatrix);
  79306. }
  79307. var babylonParentBone = null;
  79308. if (node.index !== skin.skeleton && node.parent && node.parent !== this._rootNode) {
  79309. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  79310. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  79311. }
  79312. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  79313. babylonBones[node.index] = babylonBone;
  79314. return babylonBone;
  79315. };
  79316. GLTFLoader.prototype._getNodeMatrix = function (node) {
  79317. return node.matrix ?
  79318. BABYLON.Matrix.FromArray(node.matrix) :
  79319. 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());
  79320. };
  79321. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  79322. if (parentNode === void 0) { parentNode = null; }
  79323. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  79324. var index = indices_1[_i];
  79325. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79326. if (!node) {
  79327. throw new Error(context + ": Failed to find node " + index);
  79328. }
  79329. this._traverseNode(context, node, action, parentNode);
  79330. }
  79331. };
  79332. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  79333. if (parentNode === void 0) { parentNode = null; }
  79334. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  79335. return;
  79336. }
  79337. if (!action(node, parentNode)) {
  79338. return;
  79339. }
  79340. if (node.children) {
  79341. this._traverseNodes(context, node.children, action, node);
  79342. }
  79343. };
  79344. GLTFLoader.prototype._loadAnimations = function () {
  79345. var animations = this._gltf.animations;
  79346. if (!animations) {
  79347. return;
  79348. }
  79349. for (var index = 0; index < animations.length; index++) {
  79350. var animation = animations[index];
  79351. this._loadAnimation("#/animations/" + index, animation);
  79352. }
  79353. };
  79354. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  79355. animation.targets = [];
  79356. for (var index = 0; index < animation.channels.length; index++) {
  79357. var channel = GLTFLoader._GetProperty(animation.channels, index);
  79358. if (!channel) {
  79359. throw new Error(context + ": Failed to find channel " + index);
  79360. }
  79361. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  79362. if (!sampler) {
  79363. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  79364. }
  79365. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  79366. }
  79367. };
  79368. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  79369. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  79370. if (!targetNode) {
  79371. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  79372. }
  79373. var targetPath;
  79374. var animationType;
  79375. switch (channel.target.path) {
  79376. case "translation": {
  79377. targetPath = "position";
  79378. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79379. break;
  79380. }
  79381. case "rotation": {
  79382. targetPath = "rotationQuaternion";
  79383. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  79384. break;
  79385. }
  79386. case "scale": {
  79387. targetPath = "scaling";
  79388. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79389. break;
  79390. }
  79391. case "weights": {
  79392. targetPath = "influence";
  79393. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  79394. break;
  79395. }
  79396. default: {
  79397. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  79398. }
  79399. }
  79400. var inputData;
  79401. var outputData;
  79402. var checkSuccess = function () {
  79403. if (!inputData || !outputData) {
  79404. return;
  79405. }
  79406. var outputBufferOffset = 0;
  79407. var getNextOutputValue;
  79408. switch (targetPath) {
  79409. case "position": {
  79410. getNextOutputValue = function () {
  79411. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79412. outputBufferOffset += 3;
  79413. return value;
  79414. };
  79415. break;
  79416. }
  79417. case "rotationQuaternion": {
  79418. getNextOutputValue = function () {
  79419. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  79420. outputBufferOffset += 4;
  79421. return value;
  79422. };
  79423. break;
  79424. }
  79425. case "scaling": {
  79426. getNextOutputValue = function () {
  79427. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79428. outputBufferOffset += 3;
  79429. return value;
  79430. };
  79431. break;
  79432. }
  79433. case "influence": {
  79434. getNextOutputValue = function () {
  79435. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  79436. var value = new Array(numTargets);
  79437. for (var i = 0; i < numTargets; i++) {
  79438. value[i] = outputData[outputBufferOffset++];
  79439. }
  79440. return value;
  79441. };
  79442. break;
  79443. }
  79444. }
  79445. var getNextKey;
  79446. switch (sampler.interpolation) {
  79447. case "LINEAR": {
  79448. getNextKey = function (frameIndex) { return ({
  79449. frame: inputData[frameIndex],
  79450. value: getNextOutputValue()
  79451. }); };
  79452. break;
  79453. }
  79454. case "CUBICSPLINE": {
  79455. getNextKey = function (frameIndex) { return ({
  79456. frame: inputData[frameIndex],
  79457. inTangent: getNextOutputValue(),
  79458. value: getNextOutputValue(),
  79459. outTangent: getNextOutputValue()
  79460. }); };
  79461. break;
  79462. }
  79463. default: {
  79464. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  79465. }
  79466. }
  79467. ;
  79468. var keys = new Array(inputData.length);
  79469. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  79470. keys[frameIndex] = getNextKey(frameIndex);
  79471. }
  79472. if (targetPath === "influence") {
  79473. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  79474. var _loop_7 = function (targetIndex) {
  79475. var morphTarget = morphTargetManager.getTarget(targetIndex);
  79476. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  79477. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79478. babylonAnimation.setKeys(keys.map(function (key) { return ({
  79479. frame: key.frame,
  79480. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  79481. value: key.value[targetIndex],
  79482. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  79483. }); }));
  79484. morphTarget.animations.push(babylonAnimation);
  79485. animation.targets.push(morphTarget);
  79486. };
  79487. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  79488. _loop_7(targetIndex);
  79489. }
  79490. }
  79491. else {
  79492. var animationName = animation.name || "anim" + animation.index;
  79493. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79494. babylonAnimation.setKeys(keys);
  79495. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  79496. var target = _a[_i];
  79497. target.animations.push(babylonAnimation.clone());
  79498. animation.targets.push(target);
  79499. }
  79500. }
  79501. };
  79502. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  79503. if (!inputAccessor) {
  79504. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  79505. }
  79506. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  79507. inputData = data;
  79508. checkSuccess();
  79509. });
  79510. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  79511. if (!outputAccessor) {
  79512. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  79513. }
  79514. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  79515. outputData = data;
  79516. checkSuccess();
  79517. });
  79518. };
  79519. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  79520. var _this = this;
  79521. this._addPendingData(buffer);
  79522. if (buffer.loadedData) {
  79523. onSuccess(buffer.loadedData);
  79524. this._removePendingData(buffer);
  79525. }
  79526. else if (buffer.loadedObservable) {
  79527. buffer.loadedObservable.add(function (buffer) {
  79528. onSuccess(buffer.loadedData);
  79529. _this._removePendingData(buffer);
  79530. });
  79531. }
  79532. else {
  79533. if (!buffer.uri) {
  79534. throw new Error(context + ": Uri is missing");
  79535. }
  79536. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  79537. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  79538. buffer.loadedData = new Uint8Array(data);
  79539. onSuccess(buffer.loadedData);
  79540. this._removePendingData(buffer);
  79541. }
  79542. else {
  79543. buffer.loadedObservable = new BABYLON.Observable();
  79544. buffer.loadedObservable.add(function (buffer) {
  79545. onSuccess(buffer.loadedData);
  79546. _this._removePendingData(buffer);
  79547. });
  79548. this._loadUri(context, buffer.uri, function (data) {
  79549. buffer.loadedData = data;
  79550. buffer.loadedObservable.notifyObservers(buffer);
  79551. buffer.loadedObservable = undefined;
  79552. });
  79553. }
  79554. }
  79555. };
  79556. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  79557. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  79558. if (!buffer) {
  79559. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  79560. }
  79561. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  79562. var data;
  79563. try {
  79564. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  79565. }
  79566. catch (e) {
  79567. throw new Error(context + ": " + e.message);
  79568. }
  79569. onSuccess(data);
  79570. });
  79571. };
  79572. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  79573. var _this = this;
  79574. if (accessor.sparse) {
  79575. throw new Error(context + ": Sparse accessors are not currently supported");
  79576. }
  79577. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  79578. if (!bufferView) {
  79579. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  79580. }
  79581. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  79582. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  79583. if (numComponents === 0) {
  79584. throw new Error(context + ": Invalid type " + accessor.type);
  79585. }
  79586. var data;
  79587. var byteOffset = accessor.byteOffset || 0;
  79588. var byteStride = bufferView.byteStride;
  79589. try {
  79590. switch (accessor.componentType) {
  79591. case GLTF2.EComponentType.BYTE: {
  79592. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79593. break;
  79594. }
  79595. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  79596. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79597. break;
  79598. }
  79599. case GLTF2.EComponentType.SHORT: {
  79600. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79601. break;
  79602. }
  79603. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  79604. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79605. break;
  79606. }
  79607. case GLTF2.EComponentType.UNSIGNED_INT: {
  79608. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79609. break;
  79610. }
  79611. case GLTF2.EComponentType.FLOAT: {
  79612. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79613. break;
  79614. }
  79615. default: {
  79616. throw new Error(context + ": Invalid component type " + accessor.componentType);
  79617. }
  79618. }
  79619. }
  79620. catch (e) {
  79621. throw new Error(context + ": " + e);
  79622. }
  79623. onSuccess(data);
  79624. });
  79625. };
  79626. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  79627. byteOffset += data.byteOffset;
  79628. var targetLength = count * numComponents;
  79629. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  79630. return new typedArray(data.buffer, byteOffset, targetLength);
  79631. }
  79632. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  79633. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  79634. var targetBuffer = new typedArray(targetLength);
  79635. var sourceIndex = 0;
  79636. var targetIndex = 0;
  79637. while (targetIndex < targetLength) {
  79638. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  79639. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  79640. targetIndex++;
  79641. }
  79642. sourceIndex += elementStride;
  79643. }
  79644. return targetBuffer;
  79645. };
  79646. GLTFLoader.prototype._addPendingData = function (data) {
  79647. if (!this._renderReady) {
  79648. this._renderPendingCount++;
  79649. }
  79650. this._addLoaderPendingData(data);
  79651. };
  79652. GLTFLoader.prototype._removePendingData = function (data) {
  79653. if (!this._renderReady) {
  79654. if (--this._renderPendingCount === 0) {
  79655. this._renderReady = true;
  79656. this._onRenderReady();
  79657. }
  79658. }
  79659. this._removeLoaderPendingData(data);
  79660. };
  79661. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  79662. this._loaderPendingCount++;
  79663. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  79664. var tracker = _a[_i];
  79665. tracker._addPendingData(data);
  79666. }
  79667. };
  79668. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  79669. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  79670. var tracker = _a[_i];
  79671. tracker._removePendingData(data);
  79672. }
  79673. if (--this._loaderPendingCount === 0) {
  79674. this._onComplete();
  79675. }
  79676. };
  79677. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  79678. var _this = this;
  79679. var tracker = new GLTFLoaderTracker(function () {
  79680. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  79681. onComplete();
  79682. });
  79683. this._loaderTrackers.push(tracker);
  79684. this._addLoaderPendingData(tracker);
  79685. action();
  79686. this._removeLoaderPendingData(tracker);
  79687. };
  79688. GLTFLoader.prototype._getDefaultMaterial = function () {
  79689. if (!this._defaultMaterial) {
  79690. var id = "__gltf_default";
  79691. var material = this._babylonScene.getMaterialByName(id);
  79692. if (!material) {
  79693. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  79694. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79695. material.metallic = 1;
  79696. material.roughness = 1;
  79697. }
  79698. this._defaultMaterial = material;
  79699. }
  79700. return this._defaultMaterial;
  79701. };
  79702. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  79703. var babylonMaterial = material.babylonMaterial;
  79704. // Ensure metallic workflow
  79705. babylonMaterial.metallic = 1;
  79706. babylonMaterial.roughness = 1;
  79707. var properties = material.pbrMetallicRoughness;
  79708. if (!properties) {
  79709. return;
  79710. }
  79711. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  79712. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  79713. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  79714. if (properties.baseColorTexture) {
  79715. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  79716. if (!texture) {
  79717. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  79718. }
  79719. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  79720. }
  79721. if (properties.metallicRoughnessTexture) {
  79722. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  79723. if (!texture) {
  79724. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  79725. }
  79726. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  79727. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  79728. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  79729. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  79730. }
  79731. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  79732. };
  79733. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  79734. if (material.babylonMaterial) {
  79735. assign(material.babylonMaterial, false);
  79736. return;
  79737. }
  79738. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  79739. return;
  79740. }
  79741. this._createPbrMaterial(material);
  79742. this._loadMaterialBaseProperties(context, material);
  79743. this._loadMaterialMetallicRoughnessProperties(context, material);
  79744. assign(material.babylonMaterial, true);
  79745. };
  79746. GLTFLoader.prototype._createPbrMaterial = function (material) {
  79747. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  79748. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79749. material.babylonMaterial = babylonMaterial;
  79750. };
  79751. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  79752. var babylonMaterial = material.babylonMaterial;
  79753. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  79754. if (material.doubleSided) {
  79755. babylonMaterial.backFaceCulling = false;
  79756. babylonMaterial.twoSidedLighting = true;
  79757. }
  79758. if (material.normalTexture) {
  79759. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  79760. if (!texture) {
  79761. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  79762. }
  79763. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  79764. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  79765. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  79766. if (material.normalTexture.scale != null) {
  79767. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  79768. }
  79769. }
  79770. if (material.occlusionTexture) {
  79771. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  79772. if (!texture) {
  79773. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  79774. }
  79775. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  79776. babylonMaterial.useAmbientInGrayScale = true;
  79777. if (material.occlusionTexture.strength != null) {
  79778. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  79779. }
  79780. }
  79781. if (material.emissiveTexture) {
  79782. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  79783. if (!texture) {
  79784. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  79785. }
  79786. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  79787. }
  79788. };
  79789. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  79790. var babylonMaterial = material.babylonMaterial;
  79791. var alphaMode = material.alphaMode || "OPAQUE";
  79792. switch (alphaMode) {
  79793. case "OPAQUE": {
  79794. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  79795. break;
  79796. }
  79797. case "MASK": {
  79798. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  79799. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  79800. if (colorFactor) {
  79801. if (colorFactor[3] == 0) {
  79802. babylonMaterial.alphaCutOff = 1;
  79803. }
  79804. else {
  79805. babylonMaterial.alphaCutOff /= colorFactor[3];
  79806. }
  79807. }
  79808. if (babylonMaterial.albedoTexture) {
  79809. babylonMaterial.albedoTexture.hasAlpha = true;
  79810. }
  79811. break;
  79812. }
  79813. case "BLEND": {
  79814. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  79815. if (colorFactor) {
  79816. babylonMaterial.alpha = colorFactor[3];
  79817. }
  79818. if (babylonMaterial.albedoTexture) {
  79819. babylonMaterial.albedoTexture.hasAlpha = true;
  79820. babylonMaterial.useAlphaFromAlbedoTexture = true;
  79821. }
  79822. break;
  79823. }
  79824. default: {
  79825. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  79826. }
  79827. }
  79828. };
  79829. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  79830. var _this = this;
  79831. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  79832. if (!sampler) {
  79833. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  79834. }
  79835. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  79836. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  79837. this._addPendingData(texture);
  79838. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  79839. _this._tryCatchOnError(function () {
  79840. _this._removePendingData(texture);
  79841. });
  79842. }, function (message) {
  79843. _this._tryCatchOnError(function () {
  79844. throw new Error(context + ": " + message);
  79845. });
  79846. });
  79847. if (texture.url) {
  79848. babylonTexture.updateURL(texture.url);
  79849. }
  79850. else if (texture.dataReadyObservable) {
  79851. texture.dataReadyObservable.add(function (texture) {
  79852. babylonTexture.updateURL(texture.url);
  79853. });
  79854. }
  79855. else {
  79856. texture.dataReadyObservable = new BABYLON.Observable();
  79857. texture.dataReadyObservable.add(function (texture) {
  79858. babylonTexture.updateURL(texture.url);
  79859. });
  79860. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  79861. if (!image_1) {
  79862. throw new Error(context + ": Failed to find source " + texture.source);
  79863. }
  79864. this._loadImage("#/images/" + image_1.index, image_1, function (data) {
  79865. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  79866. texture.dataReadyObservable.notifyObservers(texture);
  79867. texture.dataReadyObservable = undefined;
  79868. });
  79869. }
  79870. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  79871. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  79872. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  79873. babylonTexture.name = texture.name || "texture" + texture.index;
  79874. if (this._parent.onTextureLoaded) {
  79875. this._parent.onTextureLoaded(babylonTexture);
  79876. }
  79877. return babylonTexture;
  79878. };
  79879. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  79880. if (image.uri) {
  79881. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  79882. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  79883. }
  79884. else {
  79885. this._loadUri(context, image.uri, onSuccess);
  79886. }
  79887. }
  79888. else {
  79889. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  79890. if (!bufferView) {
  79891. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  79892. }
  79893. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  79894. }
  79895. };
  79896. GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) {
  79897. var _this = this;
  79898. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  79899. throw new Error(context + ": Uri '" + uri + "' is invalid");
  79900. }
  79901. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  79902. _this._tryCatchOnError(function () {
  79903. onSuccess(new Uint8Array(data));
  79904. });
  79905. }, function (event) {
  79906. _this._tryCatchOnError(function () {
  79907. _this._onProgress(event);
  79908. });
  79909. }, this._babylonScene.database, true, function (request) {
  79910. _this._tryCatchOnError(function () {
  79911. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  79912. });
  79913. });
  79914. if (request) {
  79915. this._requests.push(request);
  79916. }
  79917. };
  79918. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  79919. if (this._disposed) {
  79920. return;
  79921. }
  79922. try {
  79923. handler();
  79924. }
  79925. catch (e) {
  79926. BABYLON.Tools.Error("glTF Loader: " + e.message);
  79927. if (this._errorCallback) {
  79928. this._errorCallback(e.message);
  79929. }
  79930. this.dispose();
  79931. }
  79932. };
  79933. GLTFLoader._AssignIndices = function (array) {
  79934. if (array) {
  79935. for (var index = 0; index < array.length; index++) {
  79936. array[index].index = index;
  79937. }
  79938. }
  79939. };
  79940. GLTFLoader._GetProperty = function (array, index) {
  79941. if (!array || index == undefined || !array[index]) {
  79942. return null;
  79943. }
  79944. return array[index];
  79945. };
  79946. GLTFLoader._GetTextureWrapMode = function (mode) {
  79947. // Set defaults if undefined
  79948. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  79949. switch (mode) {
  79950. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  79951. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  79952. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  79953. default:
  79954. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  79955. return BABYLON.Texture.WRAP_ADDRESSMODE;
  79956. }
  79957. };
  79958. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  79959. // Set defaults if undefined
  79960. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  79961. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  79962. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  79963. switch (minFilter) {
  79964. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  79965. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  79966. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  79967. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  79968. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  79969. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79970. default:
  79971. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79972. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79973. }
  79974. }
  79975. else {
  79976. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  79977. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  79978. }
  79979. switch (minFilter) {
  79980. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  79981. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  79982. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79983. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  79984. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  79985. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  79986. default:
  79987. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79988. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79989. }
  79990. }
  79991. };
  79992. GLTFLoader._GetNumComponents = function (type) {
  79993. switch (type) {
  79994. case "SCALAR": return 1;
  79995. case "VEC2": return 2;
  79996. case "VEC3": return 3;
  79997. case "VEC4": return 4;
  79998. case "MAT2": return 4;
  79999. case "MAT3": return 9;
  80000. case "MAT4": return 16;
  80001. }
  80002. return 0;
  80003. };
  80004. GLTFLoader.Extensions = {};
  80005. return GLTFLoader;
  80006. }());
  80007. GLTF2.GLTFLoader = GLTFLoader;
  80008. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  80009. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80010. })(BABYLON || (BABYLON = {}));
  80011. //# sourceMappingURL=babylon.glTFLoader.js.map
  80012. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80013. var BABYLON;
  80014. (function (BABYLON) {
  80015. var GLTF2;
  80016. (function (GLTF2) {
  80017. /**
  80018. * Utils functions for GLTF
  80019. */
  80020. var GLTFUtils = /** @class */ (function () {
  80021. function GLTFUtils() {
  80022. }
  80023. /**
  80024. * If the uri is a base64 string
  80025. * @param uri: the uri to test
  80026. */
  80027. GLTFUtils.IsBase64 = function (uri) {
  80028. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  80029. };
  80030. /**
  80031. * Decode the base64 uri
  80032. * @param uri: the uri to decode
  80033. */
  80034. GLTFUtils.DecodeBase64 = function (uri) {
  80035. var decodedString = atob(uri.split(",")[1]);
  80036. var bufferLength = decodedString.length;
  80037. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  80038. for (var i = 0; i < bufferLength; i++) {
  80039. bufferView[i] = decodedString.charCodeAt(i);
  80040. }
  80041. return bufferView.buffer;
  80042. };
  80043. GLTFUtils.ValidateUri = function (uri) {
  80044. return (uri.indexOf("..") === -1);
  80045. };
  80046. return GLTFUtils;
  80047. }());
  80048. GLTF2.GLTFUtils = GLTFUtils;
  80049. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80050. })(BABYLON || (BABYLON = {}));
  80051. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  80052. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80053. var BABYLON;
  80054. (function (BABYLON) {
  80055. var GLTF2;
  80056. (function (GLTF2) {
  80057. var GLTFLoaderExtension = /** @class */ (function () {
  80058. function GLTFLoaderExtension() {
  80059. this.enabled = true;
  80060. }
  80061. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  80062. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  80063. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  80064. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  80065. var _this = this;
  80066. if (!property.extensions) {
  80067. return false;
  80068. }
  80069. var extension = property.extensions[this.name];
  80070. if (!extension) {
  80071. return false;
  80072. }
  80073. // Clear out the extension before executing the action to avoid recursing into the same property.
  80074. property.extensions[this.name] = undefined;
  80075. action(context + "extensions/" + this.name, extension, function () {
  80076. // Restore the extension after completing the action.
  80077. property.extensions[_this.name] = extension;
  80078. });
  80079. return true;
  80080. };
  80081. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  80082. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  80083. };
  80084. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  80085. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  80086. };
  80087. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  80088. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  80089. };
  80090. GLTFLoaderExtension._ApplyExtensions = function (action) {
  80091. var extensions = GLTFLoaderExtension._Extensions;
  80092. if (!extensions) {
  80093. return false;
  80094. }
  80095. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  80096. var extension = extensions_1[_i];
  80097. if (extension.enabled && action(extension)) {
  80098. return true;
  80099. }
  80100. }
  80101. return false;
  80102. };
  80103. //
  80104. // Utilities
  80105. //
  80106. GLTFLoaderExtension._Extensions = [];
  80107. return GLTFLoaderExtension;
  80108. }());
  80109. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  80110. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80111. })(BABYLON || (BABYLON = {}));
  80112. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  80113. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  80114. var BABYLON;
  80115. (function (BABYLON) {
  80116. var GLTF2;
  80117. (function (GLTF2) {
  80118. var Extensions;
  80119. (function (Extensions) {
  80120. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  80121. var MSFTLOD = /** @class */ (function (_super) {
  80122. __extends(MSFTLOD, _super);
  80123. function MSFTLOD() {
  80124. return _super !== null && _super.apply(this, arguments) || this;
  80125. }
  80126. Object.defineProperty(MSFTLOD.prototype, "name", {
  80127. get: function () {
  80128. return "MSFT_lod";
  80129. },
  80130. enumerable: true,
  80131. configurable: true
  80132. });
  80133. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  80134. return this._loadExtension(context, node, function (context, extension, onComplete) {
  80135. for (var i = extension.ids.length - 1; i >= 0; i--) {
  80136. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  80137. if (!lodNode) {
  80138. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  80139. }
  80140. loader._traverseNode(context, lodNode, action, parentNode);
  80141. }
  80142. loader._traverseNode(context, node, action, parentNode);
  80143. onComplete();
  80144. });
  80145. };
  80146. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  80147. var _this = this;
  80148. return this._loadExtension(context, node, function (context, extension, onComplete) {
  80149. var nodes = [node];
  80150. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  80151. var index = _a[_i];
  80152. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  80153. if (!lodNode) {
  80154. throw new Error(context + ": Failed to find node " + index);
  80155. }
  80156. nodes.push(lodNode);
  80157. }
  80158. loader._addLoaderPendingData(node);
  80159. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  80160. loader._removeLoaderPendingData(node);
  80161. onComplete();
  80162. });
  80163. });
  80164. };
  80165. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  80166. var _this = this;
  80167. loader._whenAction(function () {
  80168. loader._loadNode(context, nodes[index]);
  80169. }, function () {
  80170. if (index !== nodes.length - 1) {
  80171. var previousNode = nodes[index + 1];
  80172. previousNode.babylonMesh.setEnabled(false);
  80173. }
  80174. if (index === 0) {
  80175. onComplete();
  80176. return;
  80177. }
  80178. setTimeout(function () {
  80179. loader._tryCatchOnError(function () {
  80180. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  80181. });
  80182. }, MSFTLOD.MinimalLODDelay);
  80183. });
  80184. };
  80185. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  80186. var _this = this;
  80187. return this._loadExtension(context, material, function (context, extension, onComplete) {
  80188. var materials = [material];
  80189. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  80190. var index = _a[_i];
  80191. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  80192. if (!lodMaterial) {
  80193. throw new Error(context + ": Failed to find material " + index);
  80194. }
  80195. materials.push(lodMaterial);
  80196. }
  80197. loader._addLoaderPendingData(material);
  80198. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  80199. loader._removeLoaderPendingData(material);
  80200. onComplete();
  80201. });
  80202. });
  80203. };
  80204. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  80205. var _this = this;
  80206. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  80207. assign(babylonMaterial, isNew);
  80208. if (index === 0) {
  80209. onComplete();
  80210. return;
  80211. }
  80212. // Load the next LOD when the loader is ready to render and
  80213. // all active material textures of the current LOD are loaded.
  80214. loader._executeWhenRenderReady(function () {
  80215. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  80216. setTimeout(function () {
  80217. loader._tryCatchOnError(function () {
  80218. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  80219. });
  80220. }, MSFTLOD.MinimalLODDelay);
  80221. });
  80222. });
  80223. });
  80224. };
  80225. /**
  80226. * Specify the minimal delay between LODs in ms (default = 250)
  80227. */
  80228. MSFTLOD.MinimalLODDelay = 250;
  80229. return MSFTLOD;
  80230. }(GLTF2.GLTFLoaderExtension));
  80231. Extensions.MSFTLOD = MSFTLOD;
  80232. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  80233. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  80234. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80235. })(BABYLON || (BABYLON = {}));
  80236. //# sourceMappingURL=MSFT_lod.js.map
  80237. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  80238. var BABYLON;
  80239. (function (BABYLON) {
  80240. var GLTF2;
  80241. (function (GLTF2) {
  80242. var Extensions;
  80243. (function (Extensions) {
  80244. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  80245. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  80246. function KHRMaterialsPbrSpecularGlossiness() {
  80247. return _super !== null && _super.apply(this, arguments) || this;
  80248. }
  80249. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  80250. get: function () {
  80251. return "KHR_materials_pbrSpecularGlossiness";
  80252. },
  80253. enumerable: true,
  80254. configurable: true
  80255. });
  80256. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  80257. var _this = this;
  80258. return this._loadExtension(context, material, function (context, extension, onComplete) {
  80259. loader._createPbrMaterial(material);
  80260. loader._loadMaterialBaseProperties(context, material);
  80261. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  80262. assign(material.babylonMaterial, true);
  80263. });
  80264. };
  80265. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  80266. var babylonMaterial = material.babylonMaterial;
  80267. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  80268. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  80269. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  80270. if (properties.diffuseTexture) {
  80271. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  80272. if (!texture) {
  80273. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  80274. }
  80275. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  80276. }
  80277. if (properties.specularGlossinessTexture) {
  80278. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  80279. if (!texture) {
  80280. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  80281. }
  80282. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  80283. babylonMaterial.reflectivityTexture.hasAlpha = true;
  80284. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  80285. }
  80286. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  80287. };
  80288. return KHRMaterialsPbrSpecularGlossiness;
  80289. }(GLTF2.GLTFLoaderExtension));
  80290. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  80291. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  80292. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  80293. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80294. })(BABYLON || (BABYLON = {}));
  80295. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  80296. (function universalModuleDefinition(root, factory) {
  80297. if (root && root["BABYLON"]) {
  80298. return;
  80299. }
  80300. var f = factory();
  80301. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  80302. globalObject["BABYLON"] = f;
  80303. if(typeof exports === 'object' && typeof module === 'object')
  80304. module.exports = f;
  80305. else if(typeof define === 'function' && define.amd)
  80306. define([], factory);
  80307. else if(typeof exports === 'object')
  80308. exports["BABYLON"] = f;
  80309. else {
  80310. root["BABYLON"] = f;
  80311. }
  80312. })(this, function() {
  80313. return BABYLON;
  80314. });