babylon.max.js 4.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. this._loadVertexShader(vertexSource, function (vertexCode) {
  157. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  158. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  159. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  160. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  161. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  162. if (baseName) {
  163. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  164. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  165. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  166. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  167. }
  168. else {
  169. _this._vertexSourceCode = migratedVertexCode;
  170. _this._fragmentSourceCode = migratedFragmentCode;
  171. }
  172. _this._prepareEffect();
  173. });
  174. });
  175. });
  176. });
  177. });
  178. });
  179. }
  180. Object.defineProperty(Effect.prototype, "key", {
  181. get: function () {
  182. return this._key;
  183. },
  184. enumerable: true,
  185. configurable: true
  186. });
  187. // Properties
  188. Effect.prototype.isReady = function () {
  189. return this._isReady;
  190. };
  191. Effect.prototype.getEngine = function () {
  192. return this._engine;
  193. };
  194. Effect.prototype.getProgram = function () {
  195. return this._program;
  196. };
  197. Effect.prototype.getAttributesNames = function () {
  198. return this._attributesNames;
  199. };
  200. Effect.prototype.getAttributeLocation = function (index) {
  201. return this._attributes[index];
  202. };
  203. Effect.prototype.getAttributeLocationByName = function (name) {
  204. var index = this._attributesNames.indexOf(name);
  205. return this._attributes[index];
  206. };
  207. Effect.prototype.getAttributesCount = function () {
  208. return this._attributes.length;
  209. };
  210. Effect.prototype.getUniformIndex = function (uniformName) {
  211. return this._uniformsNames.indexOf(uniformName);
  212. };
  213. Effect.prototype.getUniform = function (uniformName) {
  214. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  215. };
  216. Effect.prototype.getSamplers = function () {
  217. return this._samplers;
  218. };
  219. Effect.prototype.getCompilationError = function () {
  220. return this._compilationError;
  221. };
  222. // Methods
  223. Effect.prototype.executeWhenCompiled = function (func) {
  224. if (this.isReady()) {
  225. func(this);
  226. return;
  227. }
  228. this.onCompileObservable.add(function (effect) {
  229. func(effect);
  230. });
  231. };
  232. Effect.prototype._loadVertexShader = function (vertex, callback) {
  233. if (BABYLON.Tools.IsWindowObjectExist()) {
  234. // DOM element ?
  235. if (vertex instanceof HTMLElement) {
  236. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  237. callback(vertexCode);
  238. return;
  239. }
  240. }
  241. // Base64 encoded ?
  242. if (vertex.substr(0, 7) === "base64:") {
  243. var vertexBinary = window.atob(vertex.substr(7));
  244. callback(vertexBinary);
  245. return;
  246. }
  247. // Is in local store ?
  248. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  249. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  250. return;
  251. }
  252. var vertexShaderUrl;
  253. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  254. vertexShaderUrl = vertex;
  255. }
  256. else {
  257. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  258. }
  259. // Vertex shader
  260. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  261. };
  262. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  263. if (BABYLON.Tools.IsWindowObjectExist()) {
  264. // DOM element ?
  265. if (fragment instanceof HTMLElement) {
  266. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  267. callback(fragmentCode);
  268. return;
  269. }
  270. }
  271. // Base64 encoded ?
  272. if (fragment.substr(0, 7) === "base64:") {
  273. var fragmentBinary = window.atob(fragment.substr(7));
  274. callback(fragmentBinary);
  275. return;
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  280. return;
  281. }
  282. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  283. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  284. return;
  285. }
  286. var fragmentShaderUrl;
  287. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  288. fragmentShaderUrl = fragment;
  289. }
  290. else {
  291. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  292. }
  293. // Fragment shader
  294. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  295. };
  296. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  297. // Rebuild shaders source code
  298. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  299. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  300. vertexCode = prefix + vertexCode;
  301. fragmentCode = prefix + fragmentCode;
  302. // Number lines of shaders source code
  303. var i = 2;
  304. var regex = /\n/gm;
  305. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. i = 2;
  307. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  308. // Dump shaders name and formatted source code
  309. if (this.name.vertexElement) {
  310. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  311. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  312. }
  313. else if (this.name.vertex) {
  314. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  315. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  316. }
  317. else {
  318. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  319. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  320. }
  321. };
  322. ;
  323. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  324. var preparedSourceCode = this._processPrecision(sourceCode);
  325. if (this._engine.webGLVersion == 1) {
  326. callback(preparedSourceCode);
  327. return;
  328. }
  329. // Already converted
  330. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  331. callback(preparedSourceCode.replace("#version 300 es", ""));
  332. return;
  333. }
  334. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  335. // Remove extensions
  336. // #extension GL_OES_standard_derivatives : enable
  337. // #extension GL_EXT_shader_texture_lod : enable
  338. // #extension GL_EXT_frag_depth : enable
  339. // #extension GL_EXT_draw_buffers : require
  340. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  341. var result = preparedSourceCode.replace(regex, "");
  342. // Migrate to GLSL v300
  343. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  344. result = result.replace(/attribute[ \t]/g, "in ");
  345. result = result.replace(/[ \t]attribute/g, " in");
  346. if (isFragment) {
  347. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  348. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  349. result = result.replace(/texture2D\s*\(/g, "texture(");
  350. result = result.replace(/textureCube\s*\(/g, "texture(");
  351. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  352. result = result.replace(/gl_FragColor/g, "glFragColor");
  353. result = result.replace(/gl_FragData/g, "glFragData");
  354. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  355. }
  356. callback(result);
  357. };
  358. Effect.prototype._processIncludes = function (sourceCode, callback) {
  359. var _this = this;
  360. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  361. var match = regex.exec(sourceCode);
  362. var returnValue = new String(sourceCode);
  363. while (match != null) {
  364. var includeFile = match[1];
  365. // Uniform declaration
  366. if (includeFile.indexOf("__decl__") !== -1) {
  367. includeFile = includeFile.replace(/__decl__/, "");
  368. if (this._engine.supportsUniformBuffers) {
  369. includeFile = includeFile.replace(/Vertex/, "Ubo");
  370. includeFile = includeFile.replace(/Fragment/, "Ubo");
  371. }
  372. includeFile = includeFile + "Declaration";
  373. }
  374. if (Effect.IncludesShadersStore[includeFile]) {
  375. // Substitution
  376. var includeContent = Effect.IncludesShadersStore[includeFile];
  377. if (match[2]) {
  378. var splits = match[3].split(",");
  379. for (var index = 0; index < splits.length; index += 2) {
  380. var source = new RegExp(splits[index], "g");
  381. var dest = splits[index + 1];
  382. includeContent = includeContent.replace(source, dest);
  383. }
  384. }
  385. if (match[4]) {
  386. var indexString = match[5];
  387. if (indexString.indexOf("..") !== -1) {
  388. var indexSplits = indexString.split("..");
  389. var minIndex = parseInt(indexSplits[0]);
  390. var maxIndex = parseInt(indexSplits[1]);
  391. var sourceIncludeContent = includeContent.slice(0);
  392. includeContent = "";
  393. if (isNaN(maxIndex)) {
  394. maxIndex = this._indexParameters[indexSplits[1]];
  395. }
  396. for (var i = minIndex; i < maxIndex; i++) {
  397. if (!this._engine.supportsUniformBuffers) {
  398. // Ubo replacement
  399. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  400. return p1 + "{X}";
  401. });
  402. }
  403. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  404. }
  405. }
  406. else {
  407. if (!this._engine.supportsUniformBuffers) {
  408. // Ubo replacement
  409. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  410. return p1 + "{X}";
  411. });
  412. }
  413. includeContent = includeContent.replace(/\{X\}/g, indexString);
  414. }
  415. }
  416. // Replace
  417. returnValue = returnValue.replace(match[0], includeContent);
  418. }
  419. else {
  420. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  421. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  422. Effect.IncludesShadersStore[includeFile] = fileContent;
  423. _this._processIncludes(returnValue, callback);
  424. });
  425. return;
  426. }
  427. match = regex.exec(sourceCode);
  428. }
  429. callback(returnValue);
  430. };
  431. Effect.prototype._processPrecision = function (source) {
  432. if (source.indexOf("precision highp float") === -1) {
  433. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  434. source = "precision mediump float;\n" + source;
  435. }
  436. else {
  437. source = "precision highp float;\n" + source;
  438. }
  439. }
  440. else {
  441. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  442. source = source.replace("precision highp float", "precision mediump float");
  443. }
  444. }
  445. return source;
  446. };
  447. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  448. var _this = this;
  449. this._isReady = false;
  450. this._vertexSourceCodeOverride = vertexSourceCode;
  451. this._fragmentSourceCodeOverride = fragmentSourceCode;
  452. this.onError = function (effect, error) {
  453. if (onError) {
  454. onError(error);
  455. }
  456. };
  457. this.onCompiled = function () {
  458. var scenes = _this.getEngine().scenes;
  459. for (var i = 0; i < scenes.length; i++) {
  460. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  461. }
  462. if (onCompiled) {
  463. onCompiled(_this._program);
  464. }
  465. };
  466. this._fallbacks = null;
  467. this._prepareEffect();
  468. };
  469. Effect.prototype.getSpecificUniformLocations = function (names) {
  470. var engine = this._engine;
  471. return engine.getUniforms(this._program, names);
  472. };
  473. Effect.prototype._prepareEffect = function () {
  474. var attributesNames = this._attributesNames;
  475. var defines = this.defines;
  476. var fallbacks = this._fallbacks;
  477. this._valueCache = {};
  478. var previousProgram = this._program;
  479. try {
  480. var engine = this._engine;
  481. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  482. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  483. }
  484. else {
  485. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  486. }
  487. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  488. if (engine.supportsUniformBuffers) {
  489. for (var name in this._uniformBuffersNames) {
  490. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  491. }
  492. }
  493. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  494. this._attributes = engine.getAttributes(this._program, attributesNames);
  495. var index;
  496. for (index = 0; index < this._samplers.length; index++) {
  497. var sampler = this.getUniform(this._samplers[index]);
  498. if (sampler == null) {
  499. this._samplers.splice(index, 1);
  500. index--;
  501. }
  502. }
  503. engine.bindSamplers(this);
  504. this._compilationError = "";
  505. this._isReady = true;
  506. if (this.onCompiled) {
  507. this.onCompiled(this);
  508. }
  509. this.onCompileObservable.notifyObservers(this);
  510. this.onCompileObservable.clear();
  511. // Unbind mesh reference in fallbacks
  512. if (this._fallbacks) {
  513. this._fallbacks.unBindMesh();
  514. }
  515. if (previousProgram) {
  516. this.getEngine()._deleteProgram(previousProgram);
  517. }
  518. }
  519. catch (e) {
  520. this._compilationError = e.message;
  521. // Let's go through fallbacks then
  522. BABYLON.Tools.Error("Unable to compile effect:");
  523. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  524. return " " + uniform;
  525. }));
  526. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  527. return " " + attribute;
  528. }));
  529. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  530. BABYLON.Tools.Error("Error: " + this._compilationError);
  531. if (previousProgram) {
  532. this._program = previousProgram;
  533. this._isReady = true;
  534. if (this.onError) {
  535. this.onError(this, this._compilationError);
  536. }
  537. this.onErrorObservable.notifyObservers(this);
  538. }
  539. if (fallbacks && fallbacks.isMoreFallbacks) {
  540. BABYLON.Tools.Error("Trying next fallback.");
  541. this.defines = fallbacks.reduce(this.defines);
  542. this._prepareEffect();
  543. }
  544. else {
  545. if (this.onError) {
  546. this.onError(this, this._compilationError);
  547. }
  548. this.onErrorObservable.notifyObservers(this);
  549. this.onErrorObservable.clear();
  550. // Unbind mesh reference in fallbacks
  551. if (this._fallbacks) {
  552. this._fallbacks.unBindMesh();
  553. }
  554. }
  555. }
  556. };
  557. Object.defineProperty(Effect.prototype, "isSupported", {
  558. get: function () {
  559. return this._compilationError === "";
  560. },
  561. enumerable: true,
  562. configurable: true
  563. });
  564. Effect.prototype._bindTexture = function (channel, texture) {
  565. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  566. };
  567. Effect.prototype.setTexture = function (channel, texture) {
  568. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  569. };
  570. Effect.prototype.setTextureArray = function (channel, textures) {
  571. if (this._samplers.indexOf(channel + "Ex") === -1) {
  572. var initialPos = this._samplers.indexOf(channel);
  573. for (var index = 1; index < textures.length; index++) {
  574. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  575. }
  576. }
  577. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  578. };
  579. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  580. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  581. };
  582. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  583. var cache = this._valueCache[uniformName];
  584. var flag = matrix.updateFlag;
  585. if (cache !== undefined && cache === flag) {
  586. return false;
  587. }
  588. this._valueCache[uniformName] = flag;
  589. return true;
  590. };
  591. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  592. var cache = this._valueCache[uniformName];
  593. if (!cache) {
  594. cache = [x, y];
  595. this._valueCache[uniformName] = cache;
  596. return true;
  597. }
  598. var changed = false;
  599. if (cache[0] !== x) {
  600. cache[0] = x;
  601. changed = true;
  602. }
  603. if (cache[1] !== y) {
  604. cache[1] = y;
  605. changed = true;
  606. }
  607. return changed;
  608. };
  609. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  610. var cache = this._valueCache[uniformName];
  611. if (!cache) {
  612. cache = [x, y, z];
  613. this._valueCache[uniformName] = cache;
  614. return true;
  615. }
  616. var changed = false;
  617. if (cache[0] !== x) {
  618. cache[0] = x;
  619. changed = true;
  620. }
  621. if (cache[1] !== y) {
  622. cache[1] = y;
  623. changed = true;
  624. }
  625. if (cache[2] !== z) {
  626. cache[2] = z;
  627. changed = true;
  628. }
  629. return changed;
  630. };
  631. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  632. var cache = this._valueCache[uniformName];
  633. if (!cache) {
  634. cache = [x, y, z, w];
  635. this._valueCache[uniformName] = cache;
  636. return true;
  637. }
  638. var changed = false;
  639. if (cache[0] !== x) {
  640. cache[0] = x;
  641. changed = true;
  642. }
  643. if (cache[1] !== y) {
  644. cache[1] = y;
  645. changed = true;
  646. }
  647. if (cache[2] !== z) {
  648. cache[2] = z;
  649. changed = true;
  650. }
  651. if (cache[3] !== w) {
  652. cache[3] = w;
  653. changed = true;
  654. }
  655. return changed;
  656. };
  657. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  658. var bufferName = this._uniformBuffersNames[name];
  659. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  660. return;
  661. }
  662. Effect._baseCache[bufferName] = buffer;
  663. this._engine.bindUniformBufferBase(buffer, bufferName);
  664. };
  665. Effect.prototype.bindUniformBlock = function (blockName, index) {
  666. this._engine.bindUniformBlock(this._program, blockName, index);
  667. };
  668. Effect.prototype.setInt = function (uniformName, value) {
  669. var cache = this._valueCache[uniformName];
  670. if (cache !== undefined && cache === value)
  671. return this;
  672. this._valueCache[uniformName] = value;
  673. this._engine.setInt(this.getUniform(uniformName), value);
  674. return this;
  675. };
  676. Effect.prototype.setIntArray = function (uniformName, array) {
  677. this._valueCache[uniformName] = null;
  678. this._engine.setIntArray(this.getUniform(uniformName), array);
  679. return this;
  680. };
  681. Effect.prototype.setIntArray2 = function (uniformName, array) {
  682. this._valueCache[uniformName] = null;
  683. this._engine.setIntArray2(this.getUniform(uniformName), array);
  684. return this;
  685. };
  686. Effect.prototype.setIntArray3 = function (uniformName, array) {
  687. this._valueCache[uniformName] = null;
  688. this._engine.setIntArray3(this.getUniform(uniformName), array);
  689. return this;
  690. };
  691. Effect.prototype.setIntArray4 = function (uniformName, array) {
  692. this._valueCache[uniformName] = null;
  693. this._engine.setIntArray4(this.getUniform(uniformName), array);
  694. return this;
  695. };
  696. Effect.prototype.setFloatArray = function (uniformName, array) {
  697. this._valueCache[uniformName] = null;
  698. this._engine.setFloatArray(this.getUniform(uniformName), array);
  699. return this;
  700. };
  701. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  702. this._valueCache[uniformName] = null;
  703. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  704. return this;
  705. };
  706. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  707. this._valueCache[uniformName] = null;
  708. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  709. return this;
  710. };
  711. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  712. this._valueCache[uniformName] = null;
  713. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  714. return this;
  715. };
  716. Effect.prototype.setArray = function (uniformName, array) {
  717. this._valueCache[uniformName] = null;
  718. this._engine.setArray(this.getUniform(uniformName), array);
  719. return this;
  720. };
  721. Effect.prototype.setArray2 = function (uniformName, array) {
  722. this._valueCache[uniformName] = null;
  723. this._engine.setArray2(this.getUniform(uniformName), array);
  724. return this;
  725. };
  726. Effect.prototype.setArray3 = function (uniformName, array) {
  727. this._valueCache[uniformName] = null;
  728. this._engine.setArray3(this.getUniform(uniformName), array);
  729. return this;
  730. };
  731. Effect.prototype.setArray4 = function (uniformName, array) {
  732. this._valueCache[uniformName] = null;
  733. this._engine.setArray4(this.getUniform(uniformName), array);
  734. return this;
  735. };
  736. Effect.prototype.setMatrices = function (uniformName, matrices) {
  737. if (!matrices) {
  738. return this;
  739. }
  740. this._valueCache[uniformName] = null;
  741. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  742. return this;
  743. };
  744. Effect.prototype.setMatrix = function (uniformName, matrix) {
  745. if (this._cacheMatrix(uniformName, matrix)) {
  746. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  747. }
  748. return this;
  749. };
  750. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  751. this._valueCache[uniformName] = null;
  752. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  753. return this;
  754. };
  755. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  756. this._valueCache[uniformName] = null;
  757. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  758. return this;
  759. };
  760. Effect.prototype.setFloat = function (uniformName, value) {
  761. var cache = this._valueCache[uniformName];
  762. if (cache !== undefined && cache === value)
  763. return this;
  764. this._valueCache[uniformName] = value;
  765. this._engine.setFloat(this.getUniform(uniformName), value);
  766. return this;
  767. };
  768. Effect.prototype.setBool = function (uniformName, bool) {
  769. var cache = this._valueCache[uniformName];
  770. if (cache !== undefined && cache === bool)
  771. return this;
  772. this._valueCache[uniformName] = bool;
  773. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  774. return this;
  775. };
  776. Effect.prototype.setVector2 = function (uniformName, vector2) {
  777. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  778. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  783. if (this._cacheFloat2(uniformName, x, y)) {
  784. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector3 = function (uniformName, vector3) {
  789. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  790. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  795. if (this._cacheFloat3(uniformName, x, y, z)) {
  796. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setVector4 = function (uniformName, vector4) {
  801. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  802. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  807. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  808. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  809. }
  810. return this;
  811. };
  812. Effect.prototype.setColor3 = function (uniformName, color3) {
  813. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  814. this._engine.setColor3(this.getUniform(uniformName), color3);
  815. }
  816. return this;
  817. };
  818. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  819. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  820. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  821. }
  822. return this;
  823. };
  824. Effect.ResetCache = function () {
  825. Effect._baseCache = {};
  826. };
  827. Effect._uniqueIdSeed = 0;
  828. Effect._baseCache = {};
  829. // Statics
  830. Effect.ShadersStore = {};
  831. Effect.IncludesShadersStore = {};
  832. return Effect;
  833. }());
  834. BABYLON.Effect = Effect;
  835. })(BABYLON || (BABYLON = {}));
  836. //# sourceMappingURL=babylon.effect.js.map
  837. //# sourceMappingURL=babylon.types.js.map
  838. var BABYLON;
  839. (function (BABYLON) {
  840. var KeyboardEventTypes = /** @class */ (function () {
  841. function KeyboardEventTypes() {
  842. }
  843. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  844. get: function () {
  845. return KeyboardEventTypes._KEYDOWN;
  846. },
  847. enumerable: true,
  848. configurable: true
  849. });
  850. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  851. get: function () {
  852. return KeyboardEventTypes._KEYUP;
  853. },
  854. enumerable: true,
  855. configurable: true
  856. });
  857. KeyboardEventTypes._KEYDOWN = 0x01;
  858. KeyboardEventTypes._KEYUP = 0x02;
  859. return KeyboardEventTypes;
  860. }());
  861. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  862. var KeyboardInfo = /** @class */ (function () {
  863. function KeyboardInfo(type, event) {
  864. this.type = type;
  865. this.event = event;
  866. }
  867. return KeyboardInfo;
  868. }());
  869. BABYLON.KeyboardInfo = KeyboardInfo;
  870. /**
  871. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  872. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  873. */
  874. var KeyboardInfoPre = /** @class */ (function (_super) {
  875. __extends(KeyboardInfoPre, _super);
  876. function KeyboardInfoPre(type, event) {
  877. var _this = _super.call(this, type, event) || this;
  878. _this.skipOnPointerObservable = false;
  879. return _this;
  880. }
  881. return KeyboardInfoPre;
  882. }(KeyboardInfo));
  883. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  884. })(BABYLON || (BABYLON = {}));
  885. //# sourceMappingURL=babylon.keyboardEvents.js.map
  886. var BABYLON;
  887. (function (BABYLON) {
  888. var PointerEventTypes = /** @class */ (function () {
  889. function PointerEventTypes() {
  890. }
  891. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  892. get: function () {
  893. return PointerEventTypes._POINTERDOWN;
  894. },
  895. enumerable: true,
  896. configurable: true
  897. });
  898. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  899. get: function () {
  900. return PointerEventTypes._POINTERUP;
  901. },
  902. enumerable: true,
  903. configurable: true
  904. });
  905. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  906. get: function () {
  907. return PointerEventTypes._POINTERMOVE;
  908. },
  909. enumerable: true,
  910. configurable: true
  911. });
  912. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  913. get: function () {
  914. return PointerEventTypes._POINTERWHEEL;
  915. },
  916. enumerable: true,
  917. configurable: true
  918. });
  919. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  920. get: function () {
  921. return PointerEventTypes._POINTERPICK;
  922. },
  923. enumerable: true,
  924. configurable: true
  925. });
  926. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  927. get: function () {
  928. return PointerEventTypes._POINTERTAP;
  929. },
  930. enumerable: true,
  931. configurable: true
  932. });
  933. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  934. get: function () {
  935. return PointerEventTypes._POINTERDOUBLETAP;
  936. },
  937. enumerable: true,
  938. configurable: true
  939. });
  940. PointerEventTypes._POINTERDOWN = 0x01;
  941. PointerEventTypes._POINTERUP = 0x02;
  942. PointerEventTypes._POINTERMOVE = 0x04;
  943. PointerEventTypes._POINTERWHEEL = 0x08;
  944. PointerEventTypes._POINTERPICK = 0x10;
  945. PointerEventTypes._POINTERTAP = 0x20;
  946. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  947. return PointerEventTypes;
  948. }());
  949. BABYLON.PointerEventTypes = PointerEventTypes;
  950. var PointerInfoBase = /** @class */ (function () {
  951. function PointerInfoBase(type, event) {
  952. this.type = type;
  953. this.event = event;
  954. }
  955. return PointerInfoBase;
  956. }());
  957. BABYLON.PointerInfoBase = PointerInfoBase;
  958. /**
  959. * This class is used to store pointer related info for the onPrePointerObservable event.
  960. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  961. */
  962. var PointerInfoPre = /** @class */ (function (_super) {
  963. __extends(PointerInfoPre, _super);
  964. function PointerInfoPre(type, event, localX, localY) {
  965. var _this = _super.call(this, type, event) || this;
  966. _this.skipOnPointerObservable = false;
  967. _this.localPosition = new BABYLON.Vector2(localX, localY);
  968. return _this;
  969. }
  970. return PointerInfoPre;
  971. }(PointerInfoBase));
  972. BABYLON.PointerInfoPre = PointerInfoPre;
  973. /**
  974. * This type contains all the data related to a pointer event in Babylon.js.
  975. * 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.
  976. */
  977. var PointerInfo = /** @class */ (function (_super) {
  978. __extends(PointerInfo, _super);
  979. function PointerInfo(type, event, pickInfo) {
  980. var _this = _super.call(this, type, event) || this;
  981. _this.pickInfo = pickInfo;
  982. return _this;
  983. }
  984. return PointerInfo;
  985. }(PointerInfoBase));
  986. BABYLON.PointerInfo = PointerInfo;
  987. })(BABYLON || (BABYLON = {}));
  988. //# sourceMappingURL=babylon.pointerEvents.js.map
  989. var BABYLON;
  990. (function (BABYLON) {
  991. BABYLON.ToGammaSpace = 1 / 2.2;
  992. BABYLON.ToLinearSpace = 2.2;
  993. BABYLON.Epsilon = 0.001;
  994. var Color3 = /** @class */ (function () {
  995. /**
  996. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  997. */
  998. function Color3(r, g, b) {
  999. if (r === void 0) { r = 0; }
  1000. if (g === void 0) { g = 0; }
  1001. if (b === void 0) { b = 0; }
  1002. this.r = r;
  1003. this.g = g;
  1004. this.b = b;
  1005. }
  1006. /**
  1007. * Returns a string with the Color3 current values.
  1008. */
  1009. Color3.prototype.toString = function () {
  1010. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1011. };
  1012. /**
  1013. * Returns the string "Color3".
  1014. */
  1015. Color3.prototype.getClassName = function () {
  1016. return "Color3";
  1017. };
  1018. /**
  1019. * Returns the Color3 hash code.
  1020. */
  1021. Color3.prototype.getHashCode = function () {
  1022. var hash = this.r || 0;
  1023. hash = (hash * 397) ^ (this.g || 0);
  1024. hash = (hash * 397) ^ (this.b || 0);
  1025. return hash;
  1026. };
  1027. // Operators
  1028. /**
  1029. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1030. * Returns the Color3.
  1031. */
  1032. Color3.prototype.toArray = function (array, index) {
  1033. if (index === undefined) {
  1034. index = 0;
  1035. }
  1036. array[index] = this.r;
  1037. array[index + 1] = this.g;
  1038. array[index + 2] = this.b;
  1039. return this;
  1040. };
  1041. /**
  1042. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1043. */
  1044. Color3.prototype.toColor4 = function (alpha) {
  1045. if (alpha === void 0) { alpha = 1; }
  1046. return new Color4(this.r, this.g, this.b, alpha);
  1047. };
  1048. /**
  1049. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1050. */
  1051. Color3.prototype.asArray = function () {
  1052. var result = new Array();
  1053. this.toArray(result, 0);
  1054. return result;
  1055. };
  1056. /**
  1057. * Returns the luminance value (float).
  1058. */
  1059. Color3.prototype.toLuminance = function () {
  1060. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1061. };
  1062. /**
  1063. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1064. * Returns this new object.
  1065. */
  1066. Color3.prototype.multiply = function (otherColor) {
  1067. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1068. };
  1069. /**
  1070. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1071. * Returns the current Color3.
  1072. */
  1073. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1074. result.r = this.r * otherColor.r;
  1075. result.g = this.g * otherColor.g;
  1076. result.b = this.b * otherColor.b;
  1077. return this;
  1078. };
  1079. /**
  1080. * Boolean : True if the rgb values are equal to the passed ones.
  1081. */
  1082. Color3.prototype.equals = function (otherColor) {
  1083. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1084. };
  1085. /**
  1086. * Boolean : True if the rgb values are equal to the passed ones.
  1087. */
  1088. Color3.prototype.equalsFloats = function (r, g, b) {
  1089. return this.r === r && this.g === g && this.b === b;
  1090. };
  1091. /**
  1092. * Multiplies in place each rgb value by scale.
  1093. * Returns the updated Color3.
  1094. */
  1095. Color3.prototype.scale = function (scale) {
  1096. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1097. };
  1098. /**
  1099. * Multiplies the rgb values by scale and stores the result into "result".
  1100. * Returns the unmodified current Color3.
  1101. */
  1102. Color3.prototype.scaleToRef = function (scale, result) {
  1103. result.r = this.r * scale;
  1104. result.g = this.g * scale;
  1105. result.b = this.b * scale;
  1106. return this;
  1107. };
  1108. /**
  1109. * Clamps the rgb values by the min and max values and stores the result into "result".
  1110. * Returns the unmodified current Color3.
  1111. * @param min - minimum clamping value. Defaults to 0
  1112. * @param max - maximum clamping value. Defaults to 1
  1113. * @param result - color to store the result into.
  1114. * @returns - the original Color3
  1115. */
  1116. Color3.prototype.clampToRef = function (min, max, result) {
  1117. if (min === void 0) { min = 0; }
  1118. if (max === void 0) { max = 1; }
  1119. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1120. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1121. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1122. return this;
  1123. };
  1124. /**
  1125. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1126. */
  1127. Color3.prototype.add = function (otherColor) {
  1128. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1129. };
  1130. /**
  1131. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1132. * Returns the unmodified current Color3.
  1133. */
  1134. Color3.prototype.addToRef = function (otherColor, result) {
  1135. result.r = this.r + otherColor.r;
  1136. result.g = this.g + otherColor.g;
  1137. result.b = this.b + otherColor.b;
  1138. return this;
  1139. };
  1140. /**
  1141. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1142. */
  1143. Color3.prototype.subtract = function (otherColor) {
  1144. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1145. };
  1146. /**
  1147. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1148. * Returns the unmodified current Color3.
  1149. */
  1150. Color3.prototype.subtractToRef = function (otherColor, result) {
  1151. result.r = this.r - otherColor.r;
  1152. result.g = this.g - otherColor.g;
  1153. result.b = this.b - otherColor.b;
  1154. return this;
  1155. };
  1156. /**
  1157. * Returns a new Color3 copied the current one.
  1158. */
  1159. Color3.prototype.clone = function () {
  1160. return new Color3(this.r, this.g, this.b);
  1161. };
  1162. /**
  1163. * Copies the rgb values from the source in the current Color3.
  1164. * Returns the updated Color3.
  1165. */
  1166. Color3.prototype.copyFrom = function (source) {
  1167. this.r = source.r;
  1168. this.g = source.g;
  1169. this.b = source.b;
  1170. return this;
  1171. };
  1172. /**
  1173. * Updates the Color3 rgb values from the passed floats.
  1174. * Returns the Color3.
  1175. */
  1176. Color3.prototype.copyFromFloats = function (r, g, b) {
  1177. this.r = r;
  1178. this.g = g;
  1179. this.b = b;
  1180. return this;
  1181. };
  1182. /**
  1183. * Updates the Color3 rgb values from the passed floats.
  1184. * Returns the Color3.
  1185. */
  1186. Color3.prototype.set = function (r, g, b) {
  1187. return this.copyFromFloats(r, g, b);
  1188. };
  1189. /**
  1190. * Returns the Color3 hexadecimal code as a string.
  1191. */
  1192. Color3.prototype.toHexString = function () {
  1193. var intR = (this.r * 255) | 0;
  1194. var intG = (this.g * 255) | 0;
  1195. var intB = (this.b * 255) | 0;
  1196. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1197. };
  1198. /**
  1199. * Returns a new Color3 converted to linear space.
  1200. */
  1201. Color3.prototype.toLinearSpace = function () {
  1202. var convertedColor = new Color3();
  1203. this.toLinearSpaceToRef(convertedColor);
  1204. return convertedColor;
  1205. };
  1206. /**
  1207. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1208. * Returns the unmodified Color3.
  1209. */
  1210. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1211. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1212. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1213. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Color3 converted to gamma space.
  1218. */
  1219. Color3.prototype.toGammaSpace = function () {
  1220. var convertedColor = new Color3();
  1221. this.toGammaSpaceToRef(convertedColor);
  1222. return convertedColor;
  1223. };
  1224. /**
  1225. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1226. * Returns the unmodified Color3.
  1227. */
  1228. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1229. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1230. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1231. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1232. return this;
  1233. };
  1234. // Statics
  1235. /**
  1236. * Creates a new Color3 from the string containing valid hexadecimal values.
  1237. */
  1238. Color3.FromHexString = function (hex) {
  1239. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1240. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1241. return new Color3(0, 0, 0);
  1242. }
  1243. var r = parseInt(hex.substring(1, 3), 16);
  1244. var g = parseInt(hex.substring(3, 5), 16);
  1245. var b = parseInt(hex.substring(5, 7), 16);
  1246. return Color3.FromInts(r, g, b);
  1247. };
  1248. /**
  1249. * Creates a new Vector3 from the startind index of the passed array.
  1250. */
  1251. Color3.FromArray = function (array, offset) {
  1252. if (offset === void 0) { offset = 0; }
  1253. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1254. };
  1255. /**
  1256. * Creates a new Color3 from integer values ( < 256).
  1257. */
  1258. Color3.FromInts = function (r, g, b) {
  1259. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1260. };
  1261. /**
  1262. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1263. */
  1264. Color3.Lerp = function (start, end, amount) {
  1265. var r = start.r + ((end.r - start.r) * amount);
  1266. var g = start.g + ((end.g - start.g) * amount);
  1267. var b = start.b + ((end.b - start.b) * amount);
  1268. return new Color3(r, g, b);
  1269. };
  1270. Color3.Red = function () { return new Color3(1, 0, 0); };
  1271. Color3.Green = function () { return new Color3(0, 1, 0); };
  1272. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1273. Color3.Black = function () { return new Color3(0, 0, 0); };
  1274. Color3.White = function () { return new Color3(1, 1, 1); };
  1275. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1276. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1277. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1278. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1279. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1280. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1281. return Color3;
  1282. }());
  1283. BABYLON.Color3 = Color3;
  1284. var Color4 = /** @class */ (function () {
  1285. /**
  1286. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1287. */
  1288. function Color4(r, g, b, a) {
  1289. if (r === void 0) { r = 0; }
  1290. if (g === void 0) { g = 0; }
  1291. if (b === void 0) { b = 0; }
  1292. if (a === void 0) { a = 1; }
  1293. this.r = r;
  1294. this.g = g;
  1295. this.b = b;
  1296. this.a = a;
  1297. }
  1298. // Operators
  1299. /**
  1300. * Adds in place the passed Color4 values to the current Color4.
  1301. * Returns the updated Color4.
  1302. */
  1303. Color4.prototype.addInPlace = function (right) {
  1304. this.r += right.r;
  1305. this.g += right.g;
  1306. this.b += right.b;
  1307. this.a += right.a;
  1308. return this;
  1309. };
  1310. /**
  1311. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1312. */
  1313. Color4.prototype.asArray = function () {
  1314. var result = new Array();
  1315. this.toArray(result, 0);
  1316. return result;
  1317. };
  1318. /**
  1319. * Stores from the starting index in the passed array the Color4 successive values.
  1320. * Returns the Color4.
  1321. */
  1322. Color4.prototype.toArray = function (array, index) {
  1323. if (index === undefined) {
  1324. index = 0;
  1325. }
  1326. array[index] = this.r;
  1327. array[index + 1] = this.g;
  1328. array[index + 2] = this.b;
  1329. array[index + 3] = this.a;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1334. */
  1335. Color4.prototype.add = function (right) {
  1336. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1337. };
  1338. /**
  1339. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1340. */
  1341. Color4.prototype.subtract = function (right) {
  1342. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1343. };
  1344. /**
  1345. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1346. * Returns the Color4.
  1347. */
  1348. Color4.prototype.subtractToRef = function (right, result) {
  1349. result.r = this.r - right.r;
  1350. result.g = this.g - right.g;
  1351. result.b = this.b - right.b;
  1352. result.a = this.a - right.a;
  1353. return this;
  1354. };
  1355. /**
  1356. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1357. */
  1358. Color4.prototype.scale = function (scale) {
  1359. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1360. };
  1361. /**
  1362. * Multiplies the current Color4 values by scale and stores the result in "result".
  1363. * Returns the Color4.
  1364. */
  1365. Color4.prototype.scaleToRef = function (scale, result) {
  1366. result.r = this.r * scale;
  1367. result.g = this.g * scale;
  1368. result.b = this.b * scale;
  1369. result.a = this.a * scale;
  1370. return this;
  1371. };
  1372. /**
  1373. * Clamps the rgb values by the min and max values and stores the result into "result".
  1374. * Returns the unmodified current Color4.
  1375. * @param min - minimum clamping value. Defaults to 0
  1376. * @param max - maximum clamping value. Defaults to 1
  1377. * @param result - color to store the result into.
  1378. * @returns - the original Color4
  1379. */
  1380. Color4.prototype.clampToRef = function (min, max, result) {
  1381. if (min === void 0) { min = 0; }
  1382. if (max === void 0) { max = 1; }
  1383. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1384. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1385. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1386. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1387. return this;
  1388. };
  1389. /**
  1390. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1391. * @param color The Color4 (RGBA) value to multiply by
  1392. * @returns A new Color4.
  1393. */
  1394. Color4.prototype.multiply = function (color) {
  1395. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1396. };
  1397. /**
  1398. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1399. * @param color The Color4 (RGBA) value to multiply by
  1400. * @param result The Color4 (RGBA) to fill the result in
  1401. * @returns the result Color4.
  1402. */
  1403. Color4.prototype.multiplyToRef = function (color, result) {
  1404. result.r = this.r * color.r;
  1405. result.g = this.g * color.g;
  1406. result.b = this.b * color.b;
  1407. result.a = this.a * color.a;
  1408. return result;
  1409. };
  1410. /**
  1411. * Returns a string with the Color4 values.
  1412. */
  1413. Color4.prototype.toString = function () {
  1414. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1415. };
  1416. /**
  1417. * Returns the string "Color4"
  1418. */
  1419. Color4.prototype.getClassName = function () {
  1420. return "Color4";
  1421. };
  1422. /**
  1423. * Return the Color4 hash code as a number.
  1424. */
  1425. Color4.prototype.getHashCode = function () {
  1426. var hash = this.r || 0;
  1427. hash = (hash * 397) ^ (this.g || 0);
  1428. hash = (hash * 397) ^ (this.b || 0);
  1429. hash = (hash * 397) ^ (this.a || 0);
  1430. return hash;
  1431. };
  1432. /**
  1433. * Creates a new Color4 copied from the current one.
  1434. */
  1435. Color4.prototype.clone = function () {
  1436. return new Color4(this.r, this.g, this.b, this.a);
  1437. };
  1438. /**
  1439. * Copies the passed Color4 values into the current one.
  1440. * Returns the updated Color4.
  1441. */
  1442. Color4.prototype.copyFrom = function (source) {
  1443. this.r = source.r;
  1444. this.g = source.g;
  1445. this.b = source.b;
  1446. this.a = source.a;
  1447. return this;
  1448. };
  1449. /**
  1450. * Copies the passed float values into the current one.
  1451. * Returns the updated Color4.
  1452. */
  1453. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1454. this.r = r;
  1455. this.g = g;
  1456. this.b = b;
  1457. this.a = a;
  1458. return this;
  1459. };
  1460. /**
  1461. * Copies the passed float values into the current one.
  1462. * Returns the updated Color4.
  1463. */
  1464. Color4.prototype.set = function (r, g, b, a) {
  1465. return this.copyFromFloats(r, g, b, a);
  1466. };
  1467. /**
  1468. * Returns a string containing the hexadecimal Color4 code.
  1469. */
  1470. Color4.prototype.toHexString = function () {
  1471. var intR = (this.r * 255) | 0;
  1472. var intG = (this.g * 255) | 0;
  1473. var intB = (this.b * 255) | 0;
  1474. var intA = (this.a * 255) | 0;
  1475. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1476. };
  1477. /**
  1478. * Returns a new Color4 converted to linear space.
  1479. */
  1480. Color4.prototype.toLinearSpace = function () {
  1481. var convertedColor = new Color4();
  1482. this.toLinearSpaceToRef(convertedColor);
  1483. return convertedColor;
  1484. };
  1485. /**
  1486. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1487. * Returns the unmodified Color4.
  1488. */
  1489. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1490. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1491. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1492. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1493. convertedColor.a = this.a;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new Color4 converted to gamma space.
  1498. */
  1499. Color4.prototype.toGammaSpace = function () {
  1500. var convertedColor = new Color4();
  1501. this.toGammaSpaceToRef(convertedColor);
  1502. return convertedColor;
  1503. };
  1504. /**
  1505. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1506. * Returns the unmodified Color4.
  1507. */
  1508. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1509. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1510. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1511. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1512. convertedColor.a = this.a;
  1513. return this;
  1514. };
  1515. // Statics
  1516. /**
  1517. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1518. */
  1519. Color4.FromHexString = function (hex) {
  1520. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1521. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1522. return new Color4(0.0, 0.0, 0.0, 0.0);
  1523. }
  1524. var r = parseInt(hex.substring(1, 3), 16);
  1525. var g = parseInt(hex.substring(3, 5), 16);
  1526. var b = parseInt(hex.substring(5, 7), 16);
  1527. var a = parseInt(hex.substring(7, 9), 16);
  1528. return Color4.FromInts(r, g, b, a);
  1529. };
  1530. /**
  1531. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1532. */
  1533. Color4.Lerp = function (left, right, amount) {
  1534. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1535. Color4.LerpToRef(left, right, amount, result);
  1536. return result;
  1537. };
  1538. /**
  1539. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1540. */
  1541. Color4.LerpToRef = function (left, right, amount, result) {
  1542. result.r = left.r + (right.r - left.r) * amount;
  1543. result.g = left.g + (right.g - left.g) * amount;
  1544. result.b = left.b + (right.b - left.b) * amount;
  1545. result.a = left.a + (right.a - left.a) * amount;
  1546. };
  1547. /**
  1548. * Creates a new Color4 from the starting index element of the passed array.
  1549. */
  1550. Color4.FromArray = function (array, offset) {
  1551. if (offset === void 0) { offset = 0; }
  1552. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1553. };
  1554. /**
  1555. * Creates a new Color4 from the passed integers ( < 256 ).
  1556. */
  1557. Color4.FromInts = function (r, g, b, a) {
  1558. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1559. };
  1560. Color4.CheckColors4 = function (colors, count) {
  1561. // Check if color3 was used
  1562. if (colors.length === count * 3) {
  1563. var colors4 = [];
  1564. for (var index = 0; index < colors.length; index += 3) {
  1565. var newIndex = (index / 3) * 4;
  1566. colors4[newIndex] = colors[index];
  1567. colors4[newIndex + 1] = colors[index + 1];
  1568. colors4[newIndex + 2] = colors[index + 2];
  1569. colors4[newIndex + 3] = 1.0;
  1570. }
  1571. return colors4;
  1572. }
  1573. return colors;
  1574. };
  1575. return Color4;
  1576. }());
  1577. BABYLON.Color4 = Color4;
  1578. var Vector2 = /** @class */ (function () {
  1579. /**
  1580. * Creates a new Vector2 from the passed x and y coordinates.
  1581. */
  1582. function Vector2(x, y) {
  1583. this.x = x;
  1584. this.y = y;
  1585. }
  1586. /**
  1587. * Returns a string with the Vector2 coordinates.
  1588. */
  1589. Vector2.prototype.toString = function () {
  1590. return "{X: " + this.x + " Y:" + this.y + "}";
  1591. };
  1592. /**
  1593. * Returns the string "Vector2"
  1594. */
  1595. Vector2.prototype.getClassName = function () {
  1596. return "Vector2";
  1597. };
  1598. /**
  1599. * Returns the Vector2 hash code as a number.
  1600. */
  1601. Vector2.prototype.getHashCode = function () {
  1602. var hash = this.x || 0;
  1603. hash = (hash * 397) ^ (this.y || 0);
  1604. return hash;
  1605. };
  1606. // Operators
  1607. /**
  1608. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1609. * Returns the Vector2.
  1610. */
  1611. Vector2.prototype.toArray = function (array, index) {
  1612. if (index === void 0) { index = 0; }
  1613. array[index] = this.x;
  1614. array[index + 1] = this.y;
  1615. return this;
  1616. };
  1617. /**
  1618. * Returns a new array with 2 elements : the Vector2 coordinates.
  1619. */
  1620. Vector2.prototype.asArray = function () {
  1621. var result = new Array();
  1622. this.toArray(result, 0);
  1623. return result;
  1624. };
  1625. /**
  1626. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1627. * Returns the updated Vector2.
  1628. */
  1629. Vector2.prototype.copyFrom = function (source) {
  1630. this.x = source.x;
  1631. this.y = source.y;
  1632. return this;
  1633. };
  1634. /**
  1635. * Sets the Vector2 coordinates with the passed floats.
  1636. * Returns the updated Vector2.
  1637. */
  1638. Vector2.prototype.copyFromFloats = function (x, y) {
  1639. this.x = x;
  1640. this.y = y;
  1641. return this;
  1642. };
  1643. /**
  1644. * Sets the Vector2 coordinates with the passed floats.
  1645. * Returns the updated Vector2.
  1646. */
  1647. Vector2.prototype.set = function (x, y) {
  1648. return this.copyFromFloats(x, y);
  1649. };
  1650. /**
  1651. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1652. */
  1653. Vector2.prototype.add = function (otherVector) {
  1654. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1655. };
  1656. /**
  1657. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1658. * Returns the Vector2.
  1659. */
  1660. Vector2.prototype.addToRef = function (otherVector, result) {
  1661. result.x = this.x + otherVector.x;
  1662. result.y = this.y + otherVector.y;
  1663. return this;
  1664. };
  1665. /**
  1666. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1667. * Returns the updated Vector2.
  1668. */
  1669. Vector2.prototype.addInPlace = function (otherVector) {
  1670. this.x += otherVector.x;
  1671. this.y += otherVector.y;
  1672. return this;
  1673. };
  1674. /**
  1675. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1676. */
  1677. Vector2.prototype.addVector3 = function (otherVector) {
  1678. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1679. };
  1680. /**
  1681. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1682. */
  1683. Vector2.prototype.subtract = function (otherVector) {
  1684. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1685. };
  1686. /**
  1687. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1688. * Returns the Vector2.
  1689. */
  1690. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1691. result.x = this.x - otherVector.x;
  1692. result.y = this.y - otherVector.y;
  1693. return this;
  1694. };
  1695. /**
  1696. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1697. * Returns the updated Vector2.
  1698. */
  1699. Vector2.prototype.subtractInPlace = function (otherVector) {
  1700. this.x -= otherVector.x;
  1701. this.y -= otherVector.y;
  1702. return this;
  1703. };
  1704. /**
  1705. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1706. * Returns the updated Vector2.
  1707. */
  1708. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1709. this.x *= otherVector.x;
  1710. this.y *= otherVector.y;
  1711. return this;
  1712. };
  1713. /**
  1714. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1715. */
  1716. Vector2.prototype.multiply = function (otherVector) {
  1717. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1718. };
  1719. /**
  1720. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1721. * Returns the Vector2.
  1722. */
  1723. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1724. result.x = this.x * otherVector.x;
  1725. result.y = this.y * otherVector.y;
  1726. return this;
  1727. };
  1728. /**
  1729. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1730. */
  1731. Vector2.prototype.multiplyByFloats = function (x, y) {
  1732. return new Vector2(this.x * x, this.y * y);
  1733. };
  1734. /**
  1735. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1736. */
  1737. Vector2.prototype.divide = function (otherVector) {
  1738. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1739. };
  1740. /**
  1741. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1742. * Returns the Vector2.
  1743. */
  1744. Vector2.prototype.divideToRef = function (otherVector, result) {
  1745. result.x = this.x / otherVector.x;
  1746. result.y = this.y / otherVector.y;
  1747. return this;
  1748. };
  1749. /**
  1750. * Divides the current Vector3 coordinates by the passed ones.
  1751. * Returns the updated Vector3.
  1752. */
  1753. Vector2.prototype.divideInPlace = function (otherVector) {
  1754. return this.divideToRef(otherVector, this);
  1755. };
  1756. /**
  1757. * Returns a new Vector2 with current Vector2 negated coordinates.
  1758. */
  1759. Vector2.prototype.negate = function () {
  1760. return new Vector2(-this.x, -this.y);
  1761. };
  1762. /**
  1763. * Multiply the Vector2 coordinates by scale.
  1764. * Returns the updated Vector2.
  1765. */
  1766. Vector2.prototype.scaleInPlace = function (scale) {
  1767. this.x *= scale;
  1768. this.y *= scale;
  1769. return this;
  1770. };
  1771. /**
  1772. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1773. */
  1774. Vector2.prototype.scale = function (scale) {
  1775. return new Vector2(this.x * scale, this.y * scale);
  1776. };
  1777. /**
  1778. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1779. */
  1780. Vector2.prototype.equals = function (otherVector) {
  1781. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1782. };
  1783. /**
  1784. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1785. */
  1786. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1787. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1788. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1789. };
  1790. // Properties
  1791. /**
  1792. * Returns the vector length (float).
  1793. */
  1794. Vector2.prototype.length = function () {
  1795. return Math.sqrt(this.x * this.x + this.y * this.y);
  1796. };
  1797. /**
  1798. * Returns the vector squared length (float);
  1799. */
  1800. Vector2.prototype.lengthSquared = function () {
  1801. return (this.x * this.x + this.y * this.y);
  1802. };
  1803. // Methods
  1804. /**
  1805. * Normalize the vector.
  1806. * Returns the updated Vector2.
  1807. */
  1808. Vector2.prototype.normalize = function () {
  1809. var len = this.length();
  1810. if (len === 0)
  1811. return this;
  1812. var num = 1.0 / len;
  1813. this.x *= num;
  1814. this.y *= num;
  1815. return this;
  1816. };
  1817. /**
  1818. * Returns a new Vector2 copied from the Vector2.
  1819. */
  1820. Vector2.prototype.clone = function () {
  1821. return new Vector2(this.x, this.y);
  1822. };
  1823. // Statics
  1824. /**
  1825. * Returns a new Vector2(0, 0)
  1826. */
  1827. Vector2.Zero = function () {
  1828. return new Vector2(0, 0);
  1829. };
  1830. /**
  1831. * Returns a new Vector2(1, 1)
  1832. */
  1833. Vector2.One = function () {
  1834. return new Vector2(1, 1);
  1835. };
  1836. /**
  1837. * Returns a new Vector2 set from the passed index element of the passed array.
  1838. */
  1839. Vector2.FromArray = function (array, offset) {
  1840. if (offset === void 0) { offset = 0; }
  1841. return new Vector2(array[offset], array[offset + 1]);
  1842. };
  1843. /**
  1844. * Sets "result" from the passed index element of the passed array.
  1845. */
  1846. Vector2.FromArrayToRef = function (array, offset, result) {
  1847. result.x = array[offset];
  1848. result.y = array[offset + 1];
  1849. };
  1850. /**
  1851. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1852. */
  1853. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1854. var squared = amount * amount;
  1855. var cubed = amount * squared;
  1856. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1857. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1858. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1859. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1860. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1861. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1862. return new Vector2(x, y);
  1863. };
  1864. /**
  1865. * 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".
  1866. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1867. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1868. */
  1869. Vector2.Clamp = function (value, min, max) {
  1870. var x = value.x;
  1871. x = (x > max.x) ? max.x : x;
  1872. x = (x < min.x) ? min.x : x;
  1873. var y = value.y;
  1874. y = (y > max.y) ? max.y : y;
  1875. y = (y < min.y) ? min.y : y;
  1876. return new Vector2(x, y);
  1877. };
  1878. /**
  1879. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1880. */
  1881. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1882. var squared = amount * amount;
  1883. var cubed = amount * squared;
  1884. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1885. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1886. var part3 = (cubed - (2.0 * squared)) + amount;
  1887. var part4 = cubed - squared;
  1888. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1889. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1890. return new Vector2(x, y);
  1891. };
  1892. /**
  1893. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1894. */
  1895. Vector2.Lerp = function (start, end, amount) {
  1896. var x = start.x + ((end.x - start.x) * amount);
  1897. var y = start.y + ((end.y - start.y) * amount);
  1898. return new Vector2(x, y);
  1899. };
  1900. /**
  1901. * Returns the dot product (float) of the vector "left" and the vector "right".
  1902. */
  1903. Vector2.Dot = function (left, right) {
  1904. return left.x * right.x + left.y * right.y;
  1905. };
  1906. /**
  1907. * Returns a new Vector2 equal to the normalized passed vector.
  1908. */
  1909. Vector2.Normalize = function (vector) {
  1910. var newVector = vector.clone();
  1911. newVector.normalize();
  1912. return newVector;
  1913. };
  1914. /**
  1915. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1916. */
  1917. Vector2.Minimize = function (left, right) {
  1918. var x = (left.x < right.x) ? left.x : right.x;
  1919. var y = (left.y < right.y) ? left.y : right.y;
  1920. return new Vector2(x, y);
  1921. };
  1922. /**
  1923. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1924. */
  1925. Vector2.Maximize = function (left, right) {
  1926. var x = (left.x > right.x) ? left.x : right.x;
  1927. var y = (left.y > right.y) ? left.y : right.y;
  1928. return new Vector2(x, y);
  1929. };
  1930. /**
  1931. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1932. */
  1933. Vector2.Transform = function (vector, transformation) {
  1934. var r = Vector2.Zero();
  1935. Vector2.TransformToRef(vector, transformation, r);
  1936. return r;
  1937. };
  1938. /**
  1939. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1940. */
  1941. Vector2.TransformToRef = function (vector, transformation, result) {
  1942. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1943. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1944. result.x = x;
  1945. result.y = y;
  1946. };
  1947. /**
  1948. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1949. */
  1950. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1951. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1952. var sign = a < 0 ? -1 : 1;
  1953. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1954. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1955. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1956. };
  1957. /**
  1958. * Returns the distance (float) between the vectors "value1" and "value2".
  1959. */
  1960. Vector2.Distance = function (value1, value2) {
  1961. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1962. };
  1963. /**
  1964. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1965. */
  1966. Vector2.DistanceSquared = function (value1, value2) {
  1967. var x = value1.x - value2.x;
  1968. var y = value1.y - value2.y;
  1969. return (x * x) + (y * y);
  1970. };
  1971. /**
  1972. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1973. */
  1974. Vector2.Center = function (value1, value2) {
  1975. var center = value1.add(value2);
  1976. center.scaleInPlace(0.5);
  1977. return center;
  1978. };
  1979. /**
  1980. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1981. */
  1982. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1983. var l2 = Vector2.DistanceSquared(segA, segB);
  1984. if (l2 === 0.0) {
  1985. return Vector2.Distance(p, segA);
  1986. }
  1987. var v = segB.subtract(segA);
  1988. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1989. var proj = segA.add(v.multiplyByFloats(t, t));
  1990. return Vector2.Distance(p, proj);
  1991. };
  1992. return Vector2;
  1993. }());
  1994. BABYLON.Vector2 = Vector2;
  1995. var Vector3 = /** @class */ (function () {
  1996. /**
  1997. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1998. * A Vector3 is the main object used in 3D geometry.
  1999. * It can represent etiher the coordinates of a point the space, either a direction.
  2000. */
  2001. function Vector3(x, y, z) {
  2002. this.x = x;
  2003. this.y = y;
  2004. this.z = z;
  2005. }
  2006. /**
  2007. * Returns a string with the Vector3 coordinates.
  2008. */
  2009. Vector3.prototype.toString = function () {
  2010. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2011. };
  2012. /**
  2013. * Returns the string "Vector3"
  2014. */
  2015. Vector3.prototype.getClassName = function () {
  2016. return "Vector3";
  2017. };
  2018. /**
  2019. * Returns the Vector hash code.
  2020. */
  2021. Vector3.prototype.getHashCode = function () {
  2022. var hash = this.x || 0;
  2023. hash = (hash * 397) ^ (this.y || 0);
  2024. hash = (hash * 397) ^ (this.z || 0);
  2025. return hash;
  2026. };
  2027. // Operators
  2028. /**
  2029. * Returns a new array with three elements : the coordinates the Vector3.
  2030. */
  2031. Vector3.prototype.asArray = function () {
  2032. var result = [];
  2033. this.toArray(result, 0);
  2034. return result;
  2035. };
  2036. /**
  2037. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2038. * Returns the Vector3.
  2039. */
  2040. Vector3.prototype.toArray = function (array, index) {
  2041. if (index === void 0) { index = 0; }
  2042. array[index] = this.x;
  2043. array[index + 1] = this.y;
  2044. array[index + 2] = this.z;
  2045. return this;
  2046. };
  2047. /**
  2048. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2049. */
  2050. Vector3.prototype.toQuaternion = function () {
  2051. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2052. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2053. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2054. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2055. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2056. var cosy = Math.cos(this.y * 0.5);
  2057. var siny = Math.sin(this.y * 0.5);
  2058. result.x = coszMinusx * siny;
  2059. result.y = -sinzMinusx * siny;
  2060. result.z = sinxPlusz * cosy;
  2061. result.w = cosxPlusz * cosy;
  2062. return result;
  2063. };
  2064. /**
  2065. * Adds the passed vector to the current Vector3.
  2066. * Returns the updated Vector3.
  2067. */
  2068. Vector3.prototype.addInPlace = function (otherVector) {
  2069. this.x += otherVector.x;
  2070. this.y += otherVector.y;
  2071. this.z += otherVector.z;
  2072. return this;
  2073. };
  2074. /**
  2075. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2076. */
  2077. Vector3.prototype.add = function (otherVector) {
  2078. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2079. };
  2080. /**
  2081. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2082. * Returns the current Vector3.
  2083. */
  2084. Vector3.prototype.addToRef = function (otherVector, result) {
  2085. result.x = this.x + otherVector.x;
  2086. result.y = this.y + otherVector.y;
  2087. result.z = this.z + otherVector.z;
  2088. return this;
  2089. };
  2090. /**
  2091. * Subtract the passed vector from the current Vector3.
  2092. * Returns the updated Vector3.
  2093. */
  2094. Vector3.prototype.subtractInPlace = function (otherVector) {
  2095. this.x -= otherVector.x;
  2096. this.y -= otherVector.y;
  2097. this.z -= otherVector.z;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2102. */
  2103. Vector3.prototype.subtract = function (otherVector) {
  2104. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2105. };
  2106. /**
  2107. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2108. * Returns the current Vector3.
  2109. */
  2110. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2111. result.x = this.x - otherVector.x;
  2112. result.y = this.y - otherVector.y;
  2113. result.z = this.z - otherVector.z;
  2114. return this;
  2115. };
  2116. /**
  2117. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2118. */
  2119. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2120. return new Vector3(this.x - x, this.y - y, this.z - z);
  2121. };
  2122. /**
  2123. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2124. * Returns the current Vector3.
  2125. */
  2126. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2127. result.x = this.x - x;
  2128. result.y = this.y - y;
  2129. result.z = this.z - z;
  2130. return this;
  2131. };
  2132. /**
  2133. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2134. */
  2135. Vector3.prototype.negate = function () {
  2136. return new Vector3(-this.x, -this.y, -this.z);
  2137. };
  2138. /**
  2139. * Multiplies the Vector3 coordinates by the float "scale".
  2140. * Returns the updated Vector3.
  2141. */
  2142. Vector3.prototype.scaleInPlace = function (scale) {
  2143. this.x *= scale;
  2144. this.y *= scale;
  2145. this.z *= scale;
  2146. return this;
  2147. };
  2148. /**
  2149. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2150. */
  2151. Vector3.prototype.scale = function (scale) {
  2152. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2153. };
  2154. /**
  2155. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2156. * Returns the current Vector3.
  2157. */
  2158. Vector3.prototype.scaleToRef = function (scale, result) {
  2159. result.x = this.x * scale;
  2160. result.y = this.y * scale;
  2161. result.z = this.z * scale;
  2162. return this;
  2163. };
  2164. /**
  2165. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2166. */
  2167. Vector3.prototype.equals = function (otherVector) {
  2168. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2169. };
  2170. /**
  2171. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2172. */
  2173. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2174. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2175. 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);
  2176. };
  2177. /**
  2178. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2179. */
  2180. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2181. return this.x === x && this.y === y && this.z === z;
  2182. };
  2183. /**
  2184. * Muliplies the current Vector3 coordinates by the passed ones.
  2185. * Returns the updated Vector3.
  2186. */
  2187. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2188. this.x *= otherVector.x;
  2189. this.y *= otherVector.y;
  2190. this.z *= otherVector.z;
  2191. return this;
  2192. };
  2193. /**
  2194. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2195. */
  2196. Vector3.prototype.multiply = function (otherVector) {
  2197. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2198. };
  2199. /**
  2200. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2201. * Returns the current Vector3.
  2202. */
  2203. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2204. result.x = this.x * otherVector.x;
  2205. result.y = this.y * otherVector.y;
  2206. result.z = this.z * otherVector.z;
  2207. return this;
  2208. };
  2209. /**
  2210. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2211. */
  2212. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2213. return new Vector3(this.x * x, this.y * y, this.z * z);
  2214. };
  2215. /**
  2216. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2217. */
  2218. Vector3.prototype.divide = function (otherVector) {
  2219. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2220. };
  2221. /**
  2222. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2223. * Returns the current Vector3.
  2224. */
  2225. Vector3.prototype.divideToRef = function (otherVector, result) {
  2226. result.x = this.x / otherVector.x;
  2227. result.y = this.y / otherVector.y;
  2228. result.z = this.z / otherVector.z;
  2229. return this;
  2230. };
  2231. /**
  2232. * Divides the current Vector3 coordinates by the passed ones.
  2233. * Returns the updated Vector3.
  2234. */
  2235. Vector3.prototype.divideInPlace = function (otherVector) {
  2236. return this.divideToRef(otherVector, this);
  2237. };
  2238. /**
  2239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2240. * Returns the updated Vector3.
  2241. */
  2242. Vector3.prototype.MinimizeInPlace = function (other) {
  2243. if (other.x < this.x)
  2244. this.x = other.x;
  2245. if (other.y < this.y)
  2246. this.y = other.y;
  2247. if (other.z < this.z)
  2248. this.z = other.z;
  2249. return this;
  2250. };
  2251. /**
  2252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2253. * Returns the updated Vector3.
  2254. */
  2255. Vector3.prototype.MaximizeInPlace = function (other) {
  2256. if (other.x > this.x)
  2257. this.x = other.x;
  2258. if (other.y > this.y)
  2259. this.y = other.y;
  2260. if (other.z > this.z)
  2261. this.z = other.z;
  2262. return this;
  2263. };
  2264. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2265. /**
  2266. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2267. */
  2268. get: function () {
  2269. var absX = Math.abs(this.x);
  2270. var absY = Math.abs(this.y);
  2271. if (absX !== absY) {
  2272. return true;
  2273. }
  2274. var absZ = Math.abs(this.z);
  2275. if (absX !== absZ) {
  2276. return true;
  2277. }
  2278. if (absY !== absZ) {
  2279. return true;
  2280. }
  2281. return false;
  2282. },
  2283. enumerable: true,
  2284. configurable: true
  2285. });
  2286. // Properties
  2287. /**
  2288. * Returns the length of the Vector3 (float).
  2289. */
  2290. Vector3.prototype.length = function () {
  2291. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2292. };
  2293. /**
  2294. * Returns the squared length of the Vector3 (float).
  2295. */
  2296. Vector3.prototype.lengthSquared = function () {
  2297. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2298. };
  2299. /**
  2300. * Normalize the current Vector3.
  2301. * Returns the updated Vector3.
  2302. * /!\ In place operation.
  2303. */
  2304. Vector3.prototype.normalize = function () {
  2305. var len = this.length();
  2306. if (len === 0 || len === 1.0)
  2307. return this;
  2308. var num = 1.0 / len;
  2309. this.x *= num;
  2310. this.y *= num;
  2311. this.z *= num;
  2312. return this;
  2313. };
  2314. /**
  2315. * Normalize the current Vector3 to a new vector.
  2316. * @returns the new Vector3.
  2317. */
  2318. Vector3.prototype.normalizeToNew = function () {
  2319. var normalized = new Vector3(0, 0, 0);
  2320. this.normalizeToRef(normalized);
  2321. return normalized;
  2322. };
  2323. /**
  2324. * Normalize the current Vector3 to the reference.
  2325. * @param the reference to update.
  2326. * @returns the updated Vector3.
  2327. */
  2328. Vector3.prototype.normalizeToRef = function (reference) {
  2329. var len = this.length();
  2330. if (len === 0 || len === 1.0) {
  2331. reference.set(this.x, this.y, this.z);
  2332. return reference;
  2333. }
  2334. var scale = 1.0 / len;
  2335. this.scaleToRef(scale, reference);
  2336. return reference;
  2337. };
  2338. /**
  2339. * Returns a new Vector3 copied from the current Vector3.
  2340. */
  2341. Vector3.prototype.clone = function () {
  2342. return new Vector3(this.x, this.y, this.z);
  2343. };
  2344. /**
  2345. * Copies the passed vector coordinates to the current Vector3 ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector3.prototype.copyFrom = function (source) {
  2349. this.x = source.x;
  2350. this.y = source.y;
  2351. this.z = source.z;
  2352. return this;
  2353. };
  2354. /**
  2355. * Copies the passed floats to the current Vector3 coordinates.
  2356. * Returns the updated Vector3.
  2357. */
  2358. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2359. this.x = x;
  2360. this.y = y;
  2361. this.z = z;
  2362. return this;
  2363. };
  2364. /**
  2365. * Copies the passed floats to the current Vector3 coordinates.
  2366. * Returns the updated Vector3.
  2367. */
  2368. Vector3.prototype.set = function (x, y, z) {
  2369. return this.copyFromFloats(x, y, z);
  2370. };
  2371. // Statics
  2372. /**
  2373. *
  2374. */
  2375. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2376. var d0 = Vector3.Dot(vector0, axis) - size;
  2377. var d1 = Vector3.Dot(vector1, axis) - size;
  2378. var s = d0 / (d0 - d1);
  2379. return s;
  2380. };
  2381. /**
  2382. * Get angle between two vectors.
  2383. * @param vector0 angle between vector0 and vector1
  2384. * @param vector1 angle between vector0 and vector1
  2385. * @param normal direction of the normal.
  2386. * @return the angle between vector0 and vector1.
  2387. */
  2388. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2389. var v0 = vector0.clone().normalize();
  2390. var v1 = vector1.clone().normalize();
  2391. var dot = Vector3.Dot(v0, v1);
  2392. var n = Vector3.Cross(v0, v1);
  2393. if (Vector3.Dot(n, normal) > 0) {
  2394. return Math.acos(dot);
  2395. }
  2396. return -Math.acos(dot);
  2397. };
  2398. /**
  2399. * Returns a new Vector3 set from the index "offset" of the passed array.
  2400. */
  2401. Vector3.FromArray = function (array, offset) {
  2402. if (!offset) {
  2403. offset = 0;
  2404. }
  2405. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2406. };
  2407. /**
  2408. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2409. * This function is deprecated. Use FromArray instead.
  2410. */
  2411. Vector3.FromFloatArray = function (array, offset) {
  2412. return Vector3.FromArray(array, offset);
  2413. };
  2414. /**
  2415. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2416. */
  2417. Vector3.FromArrayToRef = function (array, offset, result) {
  2418. result.x = array[offset];
  2419. result.y = array[offset + 1];
  2420. result.z = array[offset + 2];
  2421. };
  2422. /**
  2423. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2424. * This function is deprecated. Use FromArrayToRef instead.
  2425. */
  2426. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2427. return Vector3.FromArrayToRef(array, offset, result);
  2428. };
  2429. /**
  2430. * Sets the passed vector "result" with the passed floats.
  2431. */
  2432. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2433. result.x = x;
  2434. result.y = y;
  2435. result.z = z;
  2436. };
  2437. /**
  2438. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2439. */
  2440. Vector3.Zero = function () {
  2441. return new Vector3(0.0, 0.0, 0.0);
  2442. };
  2443. /**
  2444. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2445. */
  2446. Vector3.One = function () {
  2447. return new Vector3(1.0, 1.0, 1.0);
  2448. };
  2449. /**
  2450. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2451. */
  2452. Vector3.Up = function () {
  2453. return new Vector3(0.0, 1.0, 0.0);
  2454. };
  2455. /**
  2456. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2457. */
  2458. Vector3.Forward = function () {
  2459. return new Vector3(0.0, 0.0, 1.0);
  2460. };
  2461. /**
  2462. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2463. */
  2464. Vector3.Right = function () {
  2465. return new Vector3(1.0, 0.0, 0.0);
  2466. };
  2467. /**
  2468. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2469. */
  2470. Vector3.Left = function () {
  2471. return new Vector3(-1.0, 0.0, 0.0);
  2472. };
  2473. /**
  2474. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2475. * This method computes tranformed coordinates only, not transformed direction vectors.
  2476. */
  2477. Vector3.TransformCoordinates = function (vector, transformation) {
  2478. var result = Vector3.Zero();
  2479. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2480. return result;
  2481. };
  2482. /**
  2483. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2484. * This method computes tranformed coordinates only, not transformed direction vectors.
  2485. */
  2486. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2487. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2488. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2489. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2490. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2491. result.x = x / w;
  2492. result.y = y / w;
  2493. result.z = z / w;
  2494. };
  2495. /**
  2496. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2497. * This method computes tranformed coordinates only, not transformed direction vectors.
  2498. */
  2499. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2500. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2501. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2502. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2503. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2504. result.x = rx / rw;
  2505. result.y = ry / rw;
  2506. result.z = rz / rw;
  2507. };
  2508. /**
  2509. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2510. * This methods computes transformed normalized direction vectors only.
  2511. */
  2512. Vector3.TransformNormal = function (vector, transformation) {
  2513. var result = Vector3.Zero();
  2514. Vector3.TransformNormalToRef(vector, transformation, result);
  2515. return result;
  2516. };
  2517. /**
  2518. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2519. * This methods computes transformed normalized direction vectors only.
  2520. */
  2521. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2522. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2523. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2524. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2525. result.x = x;
  2526. result.y = y;
  2527. result.z = z;
  2528. };
  2529. /**
  2530. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2531. * This methods computes transformed normalized direction vectors only.
  2532. */
  2533. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2534. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2535. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2536. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2537. };
  2538. /**
  2539. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2540. */
  2541. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2542. var squared = amount * amount;
  2543. var cubed = amount * squared;
  2544. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2545. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2546. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2547. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2548. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2549. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2550. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2551. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2552. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2553. return new Vector3(x, y, z);
  2554. };
  2555. /**
  2556. * 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".
  2557. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2558. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2559. */
  2560. Vector3.Clamp = function (value, min, max) {
  2561. var x = value.x;
  2562. x = (x > max.x) ? max.x : x;
  2563. x = (x < min.x) ? min.x : x;
  2564. var y = value.y;
  2565. y = (y > max.y) ? max.y : y;
  2566. y = (y < min.y) ? min.y : y;
  2567. var z = value.z;
  2568. z = (z > max.z) ? max.z : z;
  2569. z = (z < min.z) ? min.z : z;
  2570. return new Vector3(x, y, z);
  2571. };
  2572. /**
  2573. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2574. */
  2575. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2576. var squared = amount * amount;
  2577. var cubed = amount * squared;
  2578. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2579. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2580. var part3 = (cubed - (2.0 * squared)) + amount;
  2581. var part4 = cubed - squared;
  2582. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2583. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2584. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2585. return new Vector3(x, y, z);
  2586. };
  2587. /**
  2588. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2589. */
  2590. Vector3.Lerp = function (start, end, amount) {
  2591. var result = new Vector3(0, 0, 0);
  2592. Vector3.LerpToRef(start, end, amount, result);
  2593. return result;
  2594. };
  2595. /**
  2596. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2597. */
  2598. Vector3.LerpToRef = function (start, end, amount, result) {
  2599. result.x = start.x + ((end.x - start.x) * amount);
  2600. result.y = start.y + ((end.y - start.y) * amount);
  2601. result.z = start.z + ((end.z - start.z) * amount);
  2602. };
  2603. /**
  2604. * Returns the dot product (float) between the vectors "left" and "right".
  2605. */
  2606. Vector3.Dot = function (left, right) {
  2607. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2608. };
  2609. /**
  2610. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2611. * The cross product is then orthogonal to both "left" and "right".
  2612. */
  2613. Vector3.Cross = function (left, right) {
  2614. var result = Vector3.Zero();
  2615. Vector3.CrossToRef(left, right, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed vector "result" with the cross product of "left" and "right".
  2620. * The cross product is then orthogonal to both "left" and "right".
  2621. */
  2622. Vector3.CrossToRef = function (left, right, result) {
  2623. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2624. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2625. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2626. result.copyFrom(MathTmp.Vector3[0]);
  2627. };
  2628. /**
  2629. * Returns a new Vector3 as the normalization of the passed vector.
  2630. */
  2631. Vector3.Normalize = function (vector) {
  2632. var result = Vector3.Zero();
  2633. Vector3.NormalizeToRef(vector, result);
  2634. return result;
  2635. };
  2636. /**
  2637. * Sets the passed vector "result" with the normalization of the passed first vector.
  2638. */
  2639. Vector3.NormalizeToRef = function (vector, result) {
  2640. result.copyFrom(vector);
  2641. result.normalize();
  2642. };
  2643. Vector3.Project = function (vector, world, transform, viewport) {
  2644. var cw = viewport.width;
  2645. var ch = viewport.height;
  2646. var cx = viewport.x;
  2647. var cy = viewport.y;
  2648. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2649. 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);
  2650. var matrix = MathTmp.Matrix[0];
  2651. world.multiplyToRef(transform, matrix);
  2652. matrix.multiplyToRef(viewportMatrix, matrix);
  2653. return Vector3.TransformCoordinates(vector, matrix);
  2654. };
  2655. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2656. var matrix = MathTmp.Matrix[0];
  2657. world.multiplyToRef(transform, matrix);
  2658. matrix.invert();
  2659. source.x = source.x / viewportWidth * 2 - 1;
  2660. source.y = -(source.y / viewportHeight * 2 - 1);
  2661. var vector = Vector3.TransformCoordinates(source, matrix);
  2662. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2663. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2664. vector = vector.scale(1.0 / num);
  2665. }
  2666. return vector;
  2667. };
  2668. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2669. var result = Vector3.Zero();
  2670. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2671. return result;
  2672. };
  2673. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2674. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2675. };
  2676. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2677. var matrix = MathTmp.Matrix[0];
  2678. world.multiplyToRef(view, matrix);
  2679. matrix.multiplyToRef(projection, matrix);
  2680. matrix.invert();
  2681. var screenSource = MathTmp.Vector3[0];
  2682. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2683. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2684. screenSource.z = 2 * sourceZ - 1.0;
  2685. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2686. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2687. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2688. result.scaleInPlace(1.0 / num);
  2689. }
  2690. };
  2691. Vector3.Minimize = function (left, right) {
  2692. var min = left.clone();
  2693. min.MinimizeInPlace(right);
  2694. return min;
  2695. };
  2696. Vector3.Maximize = function (left, right) {
  2697. var max = left.clone();
  2698. max.MaximizeInPlace(right);
  2699. return max;
  2700. };
  2701. /**
  2702. * Returns the distance (float) between the vectors "value1" and "value2".
  2703. */
  2704. Vector3.Distance = function (value1, value2) {
  2705. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2706. };
  2707. /**
  2708. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2709. */
  2710. Vector3.DistanceSquared = function (value1, value2) {
  2711. var x = value1.x - value2.x;
  2712. var y = value1.y - value2.y;
  2713. var z = value1.z - value2.z;
  2714. return (x * x) + (y * y) + (z * z);
  2715. };
  2716. /**
  2717. * Returns a new Vector3 located at the center between "value1" and "value2".
  2718. */
  2719. Vector3.Center = function (value1, value2) {
  2720. var center = value1.add(value2);
  2721. center.scaleInPlace(0.5);
  2722. return center;
  2723. };
  2724. /**
  2725. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2726. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2727. * to something in order to rotate it from its local system to the given target system.
  2728. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2729. * Returns a new Vector3.
  2730. */
  2731. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2732. var rotation = Vector3.Zero();
  2733. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2734. return rotation;
  2735. };
  2736. /**
  2737. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2738. */
  2739. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2740. var quat = MathTmp.Quaternion[0];
  2741. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2742. quat.toEulerAnglesToRef(ref);
  2743. };
  2744. return Vector3;
  2745. }());
  2746. BABYLON.Vector3 = Vector3;
  2747. //Vector4 class created for EulerAngle class conversion to Quaternion
  2748. var Vector4 = /** @class */ (function () {
  2749. /**
  2750. * Creates a Vector4 object from the passed floats.
  2751. */
  2752. function Vector4(x, y, z, w) {
  2753. this.x = x;
  2754. this.y = y;
  2755. this.z = z;
  2756. this.w = w;
  2757. }
  2758. /**
  2759. * Returns the string with the Vector4 coordinates.
  2760. */
  2761. Vector4.prototype.toString = function () {
  2762. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2763. };
  2764. /**
  2765. * Returns the string "Vector4".
  2766. */
  2767. Vector4.prototype.getClassName = function () {
  2768. return "Vector4";
  2769. };
  2770. /**
  2771. * Returns the Vector4 hash code.
  2772. */
  2773. Vector4.prototype.getHashCode = function () {
  2774. var hash = this.x || 0;
  2775. hash = (hash * 397) ^ (this.y || 0);
  2776. hash = (hash * 397) ^ (this.z || 0);
  2777. hash = (hash * 397) ^ (this.w || 0);
  2778. return hash;
  2779. };
  2780. // Operators
  2781. /**
  2782. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2783. */
  2784. Vector4.prototype.asArray = function () {
  2785. var result = new Array();
  2786. this.toArray(result, 0);
  2787. return result;
  2788. };
  2789. /**
  2790. * Populates the passed array from the passed index with the Vector4 coordinates.
  2791. * Returns the Vector4.
  2792. */
  2793. Vector4.prototype.toArray = function (array, index) {
  2794. if (index === undefined) {
  2795. index = 0;
  2796. }
  2797. array[index] = this.x;
  2798. array[index + 1] = this.y;
  2799. array[index + 2] = this.z;
  2800. array[index + 3] = this.w;
  2801. return this;
  2802. };
  2803. /**
  2804. * Adds the passed vector to the current Vector4.
  2805. * Returns the updated Vector4.
  2806. */
  2807. Vector4.prototype.addInPlace = function (otherVector) {
  2808. this.x += otherVector.x;
  2809. this.y += otherVector.y;
  2810. this.z += otherVector.z;
  2811. this.w += otherVector.w;
  2812. return this;
  2813. };
  2814. /**
  2815. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2816. */
  2817. Vector4.prototype.add = function (otherVector) {
  2818. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2819. };
  2820. /**
  2821. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2822. * Returns the current Vector4.
  2823. */
  2824. Vector4.prototype.addToRef = function (otherVector, result) {
  2825. result.x = this.x + otherVector.x;
  2826. result.y = this.y + otherVector.y;
  2827. result.z = this.z + otherVector.z;
  2828. result.w = this.w + otherVector.w;
  2829. return this;
  2830. };
  2831. /**
  2832. * Subtract in place the passed vector from the current Vector4.
  2833. * Returns the updated Vector4.
  2834. */
  2835. Vector4.prototype.subtractInPlace = function (otherVector) {
  2836. this.x -= otherVector.x;
  2837. this.y -= otherVector.y;
  2838. this.z -= otherVector.z;
  2839. this.w -= otherVector.w;
  2840. return this;
  2841. };
  2842. /**
  2843. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2844. */
  2845. Vector4.prototype.subtract = function (otherVector) {
  2846. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2847. };
  2848. /**
  2849. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2850. * Returns the current Vector4.
  2851. */
  2852. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2853. result.x = this.x - otherVector.x;
  2854. result.y = this.y - otherVector.y;
  2855. result.z = this.z - otherVector.z;
  2856. result.w = this.w - otherVector.w;
  2857. return this;
  2858. };
  2859. /**
  2860. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2861. */
  2862. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2863. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2864. };
  2865. /**
  2866. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2867. * Returns the current Vector4.
  2868. */
  2869. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2870. result.x = this.x - x;
  2871. result.y = this.y - y;
  2872. result.z = this.z - z;
  2873. result.w = this.w - w;
  2874. return this;
  2875. };
  2876. /**
  2877. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2878. */
  2879. Vector4.prototype.negate = function () {
  2880. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2881. };
  2882. /**
  2883. * Multiplies the current Vector4 coordinates by scale (float).
  2884. * Returns the updated Vector4.
  2885. */
  2886. Vector4.prototype.scaleInPlace = function (scale) {
  2887. this.x *= scale;
  2888. this.y *= scale;
  2889. this.z *= scale;
  2890. this.w *= scale;
  2891. return this;
  2892. };
  2893. /**
  2894. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2895. */
  2896. Vector4.prototype.scale = function (scale) {
  2897. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2898. };
  2899. /**
  2900. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2901. * Returns the current Vector4.
  2902. */
  2903. Vector4.prototype.scaleToRef = function (scale, result) {
  2904. result.x = this.x * scale;
  2905. result.y = this.y * scale;
  2906. result.z = this.z * scale;
  2907. result.w = this.w * scale;
  2908. return this;
  2909. };
  2910. /**
  2911. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2912. */
  2913. Vector4.prototype.equals = function (otherVector) {
  2914. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2915. };
  2916. /**
  2917. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2918. */
  2919. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2920. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2921. return otherVector
  2922. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2923. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2924. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2925. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2926. };
  2927. /**
  2928. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2929. */
  2930. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2931. return this.x === x && this.y === y && this.z === z && this.w === w;
  2932. };
  2933. /**
  2934. * Multiplies in place the current Vector4 by the passed one.
  2935. * Returns the updated Vector4.
  2936. */
  2937. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2938. this.x *= otherVector.x;
  2939. this.y *= otherVector.y;
  2940. this.z *= otherVector.z;
  2941. this.w *= otherVector.w;
  2942. return this;
  2943. };
  2944. /**
  2945. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2946. */
  2947. Vector4.prototype.multiply = function (otherVector) {
  2948. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2949. };
  2950. /**
  2951. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2952. * Returns the current Vector4.
  2953. */
  2954. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2955. result.x = this.x * otherVector.x;
  2956. result.y = this.y * otherVector.y;
  2957. result.z = this.z * otherVector.z;
  2958. result.w = this.w * otherVector.w;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2963. */
  2964. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2965. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2966. };
  2967. /**
  2968. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2969. */
  2970. Vector4.prototype.divide = function (otherVector) {
  2971. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2972. };
  2973. /**
  2974. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2975. * Returns the current Vector4.
  2976. */
  2977. Vector4.prototype.divideToRef = function (otherVector, result) {
  2978. result.x = this.x / otherVector.x;
  2979. result.y = this.y / otherVector.y;
  2980. result.z = this.z / otherVector.z;
  2981. result.w = this.w / otherVector.w;
  2982. return this;
  2983. };
  2984. /**
  2985. * Divides the current Vector3 coordinates by the passed ones.
  2986. * Returns the updated Vector3.
  2987. */
  2988. Vector4.prototype.divideInPlace = function (otherVector) {
  2989. return this.divideToRef(otherVector, this);
  2990. };
  2991. /**
  2992. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2993. */
  2994. Vector4.prototype.MinimizeInPlace = function (other) {
  2995. if (other.x < this.x)
  2996. this.x = other.x;
  2997. if (other.y < this.y)
  2998. this.y = other.y;
  2999. if (other.z < this.z)
  3000. this.z = other.z;
  3001. if (other.w < this.w)
  3002. this.w = other.w;
  3003. return this;
  3004. };
  3005. /**
  3006. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3007. */
  3008. Vector4.prototype.MaximizeInPlace = function (other) {
  3009. if (other.x > this.x)
  3010. this.x = other.x;
  3011. if (other.y > this.y)
  3012. this.y = other.y;
  3013. if (other.z > this.z)
  3014. this.z = other.z;
  3015. if (other.w > this.w)
  3016. this.w = other.w;
  3017. return this;
  3018. };
  3019. // Properties
  3020. /**
  3021. * Returns the Vector4 length (float).
  3022. */
  3023. Vector4.prototype.length = function () {
  3024. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3025. };
  3026. /**
  3027. * Returns the Vector4 squared length (float).
  3028. */
  3029. Vector4.prototype.lengthSquared = function () {
  3030. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3031. };
  3032. // Methods
  3033. /**
  3034. * Normalizes in place the Vector4.
  3035. * Returns the updated Vector4.
  3036. */
  3037. Vector4.prototype.normalize = function () {
  3038. var len = this.length();
  3039. if (len === 0)
  3040. return this;
  3041. var num = 1.0 / len;
  3042. this.x *= num;
  3043. this.y *= num;
  3044. this.z *= num;
  3045. this.w *= num;
  3046. return this;
  3047. };
  3048. /**
  3049. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3050. */
  3051. Vector4.prototype.toVector3 = function () {
  3052. return new Vector3(this.x, this.y, this.z);
  3053. };
  3054. /**
  3055. * Returns a new Vector4 copied from the current one.
  3056. */
  3057. Vector4.prototype.clone = function () {
  3058. return new Vector4(this.x, this.y, this.z, this.w);
  3059. };
  3060. /**
  3061. * Updates the current Vector4 with the passed one coordinates.
  3062. * Returns the updated Vector4.
  3063. */
  3064. Vector4.prototype.copyFrom = function (source) {
  3065. this.x = source.x;
  3066. this.y = source.y;
  3067. this.z = source.z;
  3068. this.w = source.w;
  3069. return this;
  3070. };
  3071. /**
  3072. * Updates the current Vector4 coordinates with the passed floats.
  3073. * Returns the updated Vector4.
  3074. */
  3075. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3076. this.x = x;
  3077. this.y = y;
  3078. this.z = z;
  3079. this.w = w;
  3080. return this;
  3081. };
  3082. /**
  3083. * Updates the current Vector4 coordinates with the passed floats.
  3084. * Returns the updated Vector4.
  3085. */
  3086. Vector4.prototype.set = function (x, y, z, w) {
  3087. return this.copyFromFloats(x, y, z, w);
  3088. };
  3089. // Statics
  3090. /**
  3091. * Returns a new Vector4 set from the starting index of the passed array.
  3092. */
  3093. Vector4.FromArray = function (array, offset) {
  3094. if (!offset) {
  3095. offset = 0;
  3096. }
  3097. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3098. };
  3099. /**
  3100. * Updates the passed vector "result" from the starting index of the passed array.
  3101. */
  3102. Vector4.FromArrayToRef = function (array, offset, result) {
  3103. result.x = array[offset];
  3104. result.y = array[offset + 1];
  3105. result.z = array[offset + 2];
  3106. result.w = array[offset + 3];
  3107. };
  3108. /**
  3109. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3110. */
  3111. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3112. Vector4.FromArrayToRef(array, offset, result);
  3113. };
  3114. /**
  3115. * Updates the passed vector "result" coordinates from the passed floats.
  3116. */
  3117. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3118. result.x = x;
  3119. result.y = y;
  3120. result.z = z;
  3121. result.w = w;
  3122. };
  3123. /**
  3124. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3125. */
  3126. Vector4.Zero = function () {
  3127. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3128. };
  3129. /**
  3130. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3131. */
  3132. Vector4.One = function () {
  3133. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3134. };
  3135. /**
  3136. * Returns a new normalized Vector4 from the passed one.
  3137. */
  3138. Vector4.Normalize = function (vector) {
  3139. var result = Vector4.Zero();
  3140. Vector4.NormalizeToRef(vector, result);
  3141. return result;
  3142. };
  3143. /**
  3144. * Updates the passed vector "result" from the normalization of the passed one.
  3145. */
  3146. Vector4.NormalizeToRef = function (vector, result) {
  3147. result.copyFrom(vector);
  3148. result.normalize();
  3149. };
  3150. Vector4.Minimize = function (left, right) {
  3151. var min = left.clone();
  3152. min.MinimizeInPlace(right);
  3153. return min;
  3154. };
  3155. Vector4.Maximize = function (left, right) {
  3156. var max = left.clone();
  3157. max.MaximizeInPlace(right);
  3158. return max;
  3159. };
  3160. /**
  3161. * Returns the distance (float) between the vectors "value1" and "value2".
  3162. */
  3163. Vector4.Distance = function (value1, value2) {
  3164. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3165. };
  3166. /**
  3167. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3168. */
  3169. Vector4.DistanceSquared = function (value1, value2) {
  3170. var x = value1.x - value2.x;
  3171. var y = value1.y - value2.y;
  3172. var z = value1.z - value2.z;
  3173. var w = value1.w - value2.w;
  3174. return (x * x) + (y * y) + (z * z) + (w * w);
  3175. };
  3176. /**
  3177. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3178. */
  3179. Vector4.Center = function (value1, value2) {
  3180. var center = value1.add(value2);
  3181. center.scaleInPlace(0.5);
  3182. return center;
  3183. };
  3184. /**
  3185. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3186. * This methods computes transformed normalized direction vectors only.
  3187. */
  3188. Vector4.TransformNormal = function (vector, transformation) {
  3189. var result = Vector4.Zero();
  3190. Vector4.TransformNormalToRef(vector, transformation, result);
  3191. return result;
  3192. };
  3193. /**
  3194. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3195. * This methods computes transformed normalized direction vectors only.
  3196. */
  3197. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3198. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3199. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3200. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3201. result.x = x;
  3202. result.y = y;
  3203. result.z = z;
  3204. result.w = vector.w;
  3205. };
  3206. /**
  3207. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3208. * This methods computes transformed normalized direction vectors only.
  3209. */
  3210. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3211. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3212. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3213. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3214. result.w = w;
  3215. };
  3216. return Vector4;
  3217. }());
  3218. BABYLON.Vector4 = Vector4;
  3219. var Size = /** @class */ (function () {
  3220. /**
  3221. * Creates a Size object from the passed width and height (floats).
  3222. */
  3223. function Size(width, height) {
  3224. this.width = width;
  3225. this.height = height;
  3226. }
  3227. // Returns a string with the Size width and height.
  3228. Size.prototype.toString = function () {
  3229. return "{W: " + this.width + ", H: " + this.height + "}";
  3230. };
  3231. /**
  3232. * Returns the string "Size"
  3233. */
  3234. Size.prototype.getClassName = function () {
  3235. return "Size";
  3236. };
  3237. /**
  3238. * Returns the Size hash code.
  3239. */
  3240. Size.prototype.getHashCode = function () {
  3241. var hash = this.width || 0;
  3242. hash = (hash * 397) ^ (this.height || 0);
  3243. return hash;
  3244. };
  3245. /**
  3246. * Updates the current size from the passed one.
  3247. * Returns the updated Size.
  3248. */
  3249. Size.prototype.copyFrom = function (src) {
  3250. this.width = src.width;
  3251. this.height = src.height;
  3252. };
  3253. /**
  3254. * Updates in place the current Size from the passed floats.
  3255. * Returns the updated Size.
  3256. */
  3257. Size.prototype.copyFromFloats = function (width, height) {
  3258. this.width = width;
  3259. this.height = height;
  3260. return this;
  3261. };
  3262. /**
  3263. * Updates in place the current Size from the passed floats.
  3264. * Returns the updated Size.
  3265. */
  3266. Size.prototype.set = function (width, height) {
  3267. return this.copyFromFloats(width, height);
  3268. };
  3269. /**
  3270. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3271. */
  3272. Size.prototype.multiplyByFloats = function (w, h) {
  3273. return new Size(this.width * w, this.height * h);
  3274. };
  3275. /**
  3276. * Returns a new Size copied from the passed one.
  3277. */
  3278. Size.prototype.clone = function () {
  3279. return new Size(this.width, this.height);
  3280. };
  3281. /**
  3282. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3283. */
  3284. Size.prototype.equals = function (other) {
  3285. if (!other) {
  3286. return false;
  3287. }
  3288. return (this.width === other.width) && (this.height === other.height);
  3289. };
  3290. Object.defineProperty(Size.prototype, "surface", {
  3291. /**
  3292. * Returns the surface of the Size : width * height (float).
  3293. */
  3294. get: function () {
  3295. return this.width * this.height;
  3296. },
  3297. enumerable: true,
  3298. configurable: true
  3299. });
  3300. /**
  3301. * Returns a new Size set to (0.0, 0.0)
  3302. */
  3303. Size.Zero = function () {
  3304. return new Size(0.0, 0.0);
  3305. };
  3306. /**
  3307. * Returns a new Size set as the addition result of the current Size and the passed one.
  3308. */
  3309. Size.prototype.add = function (otherSize) {
  3310. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3311. return r;
  3312. };
  3313. /**
  3314. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3315. */
  3316. Size.prototype.subtract = function (otherSize) {
  3317. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3318. return r;
  3319. };
  3320. /**
  3321. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3322. */
  3323. Size.Lerp = function (start, end, amount) {
  3324. var w = start.width + ((end.width - start.width) * amount);
  3325. var h = start.height + ((end.height - start.height) * amount);
  3326. return new Size(w, h);
  3327. };
  3328. return Size;
  3329. }());
  3330. BABYLON.Size = Size;
  3331. var Quaternion = /** @class */ (function () {
  3332. /**
  3333. * Creates a new Quaternion from the passed floats.
  3334. */
  3335. function Quaternion(x, y, z, w) {
  3336. if (x === void 0) { x = 0.0; }
  3337. if (y === void 0) { y = 0.0; }
  3338. if (z === void 0) { z = 0.0; }
  3339. if (w === void 0) { w = 1.0; }
  3340. this.x = x;
  3341. this.y = y;
  3342. this.z = z;
  3343. this.w = w;
  3344. }
  3345. /**
  3346. * Returns a string with the Quaternion coordinates.
  3347. */
  3348. Quaternion.prototype.toString = function () {
  3349. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3350. };
  3351. /**
  3352. * Returns the string "Quaternion".
  3353. */
  3354. Quaternion.prototype.getClassName = function () {
  3355. return "Quaternion";
  3356. };
  3357. /**
  3358. * Returns the Quaternion hash code.
  3359. */
  3360. Quaternion.prototype.getHashCode = function () {
  3361. var hash = this.x || 0;
  3362. hash = (hash * 397) ^ (this.y || 0);
  3363. hash = (hash * 397) ^ (this.z || 0);
  3364. hash = (hash * 397) ^ (this.w || 0);
  3365. return hash;
  3366. };
  3367. /**
  3368. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3369. */
  3370. Quaternion.prototype.asArray = function () {
  3371. return [this.x, this.y, this.z, this.w];
  3372. };
  3373. /**
  3374. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3375. */
  3376. Quaternion.prototype.equals = function (otherQuaternion) {
  3377. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3378. };
  3379. /**
  3380. * Returns a new Quaternion copied from the current one.
  3381. */
  3382. Quaternion.prototype.clone = function () {
  3383. return new Quaternion(this.x, this.y, this.z, this.w);
  3384. };
  3385. /**
  3386. * Updates the current Quaternion from the passed one coordinates.
  3387. * Returns the updated Quaterion.
  3388. */
  3389. Quaternion.prototype.copyFrom = function (other) {
  3390. this.x = other.x;
  3391. this.y = other.y;
  3392. this.z = other.z;
  3393. this.w = other.w;
  3394. return this;
  3395. };
  3396. /**
  3397. * Updates the current Quaternion from the passed float coordinates.
  3398. * Returns the updated Quaterion.
  3399. */
  3400. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3401. this.x = x;
  3402. this.y = y;
  3403. this.z = z;
  3404. this.w = w;
  3405. return this;
  3406. };
  3407. /**
  3408. * Updates the current Quaternion from the passed float coordinates.
  3409. * Returns the updated Quaterion.
  3410. */
  3411. Quaternion.prototype.set = function (x, y, z, w) {
  3412. return this.copyFromFloats(x, y, z, w);
  3413. };
  3414. /**
  3415. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3416. */
  3417. Quaternion.prototype.add = function (other) {
  3418. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3419. };
  3420. /**
  3421. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3422. */
  3423. Quaternion.prototype.subtract = function (other) {
  3424. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3425. };
  3426. /**
  3427. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3428. */
  3429. Quaternion.prototype.scale = function (value) {
  3430. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3431. };
  3432. /**
  3433. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3434. */
  3435. Quaternion.prototype.multiply = function (q1) {
  3436. var result = new Quaternion(0, 0, 0, 1.0);
  3437. this.multiplyToRef(q1, result);
  3438. return result;
  3439. };
  3440. /**
  3441. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3442. * Returns the current Quaternion.
  3443. */
  3444. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3445. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3446. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3447. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3448. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3449. result.copyFromFloats(x, y, z, w);
  3450. return this;
  3451. };
  3452. /**
  3453. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3454. * Returns the updated Quaternion.
  3455. */
  3456. Quaternion.prototype.multiplyInPlace = function (q1) {
  3457. this.multiplyToRef(q1, this);
  3458. return this;
  3459. };
  3460. /**
  3461. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3462. * Returns the current Quaternion.
  3463. */
  3464. Quaternion.prototype.conjugateToRef = function (ref) {
  3465. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3466. return this;
  3467. };
  3468. /**
  3469. * Conjugates in place the current Quaternion.
  3470. * Returns the updated Quaternion.
  3471. */
  3472. Quaternion.prototype.conjugateInPlace = function () {
  3473. this.x *= -1;
  3474. this.y *= -1;
  3475. this.z *= -1;
  3476. return this;
  3477. };
  3478. /**
  3479. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3480. */
  3481. Quaternion.prototype.conjugate = function () {
  3482. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3483. return result;
  3484. };
  3485. /**
  3486. * Returns the Quaternion length (float).
  3487. */
  3488. Quaternion.prototype.length = function () {
  3489. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3490. };
  3491. /**
  3492. * Normalize in place the current Quaternion.
  3493. * Returns the updated Quaternion.
  3494. */
  3495. Quaternion.prototype.normalize = function () {
  3496. var length = 1.0 / this.length();
  3497. this.x *= length;
  3498. this.y *= length;
  3499. this.z *= length;
  3500. this.w *= length;
  3501. return this;
  3502. };
  3503. /**
  3504. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3505. */
  3506. Quaternion.prototype.toEulerAngles = function (order) {
  3507. if (order === void 0) { order = "YZX"; }
  3508. var result = Vector3.Zero();
  3509. this.toEulerAnglesToRef(result, order);
  3510. return result;
  3511. };
  3512. /**
  3513. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3514. * Returns the current Quaternion.
  3515. */
  3516. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3517. if (order === void 0) { order = "YZX"; }
  3518. var qz = this.z;
  3519. var qx = this.x;
  3520. var qy = this.y;
  3521. var qw = this.w;
  3522. var sqw = qw * qw;
  3523. var sqz = qz * qz;
  3524. var sqx = qx * qx;
  3525. var sqy = qy * qy;
  3526. var zAxisY = qy * qz - qx * qw;
  3527. var limit = .4999999;
  3528. if (zAxisY < -limit) {
  3529. result.y = 2 * Math.atan2(qy, qw);
  3530. result.x = Math.PI / 2;
  3531. result.z = 0;
  3532. }
  3533. else if (zAxisY > limit) {
  3534. result.y = 2 * Math.atan2(qy, qw);
  3535. result.x = -Math.PI / 2;
  3536. result.z = 0;
  3537. }
  3538. else {
  3539. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3540. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3541. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3542. }
  3543. return this;
  3544. };
  3545. /**
  3546. * Updates the passed rotation matrix with the current Quaternion values.
  3547. * Returns the current Quaternion.
  3548. */
  3549. Quaternion.prototype.toRotationMatrix = function (result) {
  3550. var xx = this.x * this.x;
  3551. var yy = this.y * this.y;
  3552. var zz = this.z * this.z;
  3553. var xy = this.x * this.y;
  3554. var zw = this.z * this.w;
  3555. var zx = this.z * this.x;
  3556. var yw = this.y * this.w;
  3557. var yz = this.y * this.z;
  3558. var xw = this.x * this.w;
  3559. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3560. result.m[1] = 2.0 * (xy + zw);
  3561. result.m[2] = 2.0 * (zx - yw);
  3562. result.m[3] = 0;
  3563. result.m[4] = 2.0 * (xy - zw);
  3564. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3565. result.m[6] = 2.0 * (yz + xw);
  3566. result.m[7] = 0;
  3567. result.m[8] = 2.0 * (zx + yw);
  3568. result.m[9] = 2.0 * (yz - xw);
  3569. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3570. result.m[11] = 0;
  3571. result.m[12] = 0;
  3572. result.m[13] = 0;
  3573. result.m[14] = 0;
  3574. result.m[15] = 1.0;
  3575. result._markAsUpdated();
  3576. return this;
  3577. };
  3578. /**
  3579. * Updates the current Quaternion from the passed rotation matrix values.
  3580. * Returns the updated Quaternion.
  3581. */
  3582. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3583. Quaternion.FromRotationMatrixToRef(matrix, this);
  3584. return this;
  3585. };
  3586. // Statics
  3587. /**
  3588. * Returns a new Quaternion set from the passed rotation matrix values.
  3589. */
  3590. Quaternion.FromRotationMatrix = function (matrix) {
  3591. var result = new Quaternion();
  3592. Quaternion.FromRotationMatrixToRef(matrix, result);
  3593. return result;
  3594. };
  3595. /**
  3596. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3597. */
  3598. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3599. var data = matrix.m;
  3600. var m11 = data[0], m12 = data[4], m13 = data[8];
  3601. var m21 = data[1], m22 = data[5], m23 = data[9];
  3602. var m31 = data[2], m32 = data[6], m33 = data[10];
  3603. var trace = m11 + m22 + m33;
  3604. var s;
  3605. if (trace > 0) {
  3606. s = 0.5 / Math.sqrt(trace + 1.0);
  3607. result.w = 0.25 / s;
  3608. result.x = (m32 - m23) * s;
  3609. result.y = (m13 - m31) * s;
  3610. result.z = (m21 - m12) * s;
  3611. }
  3612. else if (m11 > m22 && m11 > m33) {
  3613. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3614. result.w = (m32 - m23) / s;
  3615. result.x = 0.25 * s;
  3616. result.y = (m12 + m21) / s;
  3617. result.z = (m13 + m31) / s;
  3618. }
  3619. else if (m22 > m33) {
  3620. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3621. result.w = (m13 - m31) / s;
  3622. result.x = (m12 + m21) / s;
  3623. result.y = 0.25 * s;
  3624. result.z = (m23 + m32) / s;
  3625. }
  3626. else {
  3627. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3628. result.w = (m21 - m12) / s;
  3629. result.x = (m13 + m31) / s;
  3630. result.y = (m23 + m32) / s;
  3631. result.z = 0.25 * s;
  3632. }
  3633. };
  3634. /**
  3635. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3636. */
  3637. Quaternion.Zero = function () {
  3638. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3639. };
  3640. /**
  3641. * Returns a new Quaternion as the inverted current Quaternion.
  3642. */
  3643. Quaternion.Inverse = function (q) {
  3644. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3645. };
  3646. /**
  3647. * Returns the identity Quaternion.
  3648. */
  3649. Quaternion.Identity = function () {
  3650. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3651. };
  3652. Quaternion.IsIdentity = function (quaternion) {
  3653. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3654. };
  3655. /**
  3656. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3657. */
  3658. Quaternion.RotationAxis = function (axis, angle) {
  3659. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3660. };
  3661. /**
  3662. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3663. */
  3664. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3665. var sin = Math.sin(angle / 2);
  3666. axis.normalize();
  3667. result.w = Math.cos(angle / 2);
  3668. result.x = axis.x * sin;
  3669. result.y = axis.y * sin;
  3670. result.z = axis.z * sin;
  3671. return result;
  3672. };
  3673. /**
  3674. * Retuns a new Quaternion set from the starting index of the passed array.
  3675. */
  3676. Quaternion.FromArray = function (array, offset) {
  3677. if (!offset) {
  3678. offset = 0;
  3679. }
  3680. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3681. };
  3682. /**
  3683. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3684. */
  3685. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3686. var q = new Quaternion();
  3687. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3688. return q;
  3689. };
  3690. /**
  3691. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3692. */
  3693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3695. var halfRoll = roll * 0.5;
  3696. var halfPitch = pitch * 0.5;
  3697. var halfYaw = yaw * 0.5;
  3698. var sinRoll = Math.sin(halfRoll);
  3699. var cosRoll = Math.cos(halfRoll);
  3700. var sinPitch = Math.sin(halfPitch);
  3701. var cosPitch = Math.cos(halfPitch);
  3702. var sinYaw = Math.sin(halfYaw);
  3703. var cosYaw = Math.cos(halfYaw);
  3704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3708. };
  3709. /**
  3710. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3711. */
  3712. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3713. var result = new Quaternion();
  3714. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3715. return result;
  3716. };
  3717. /**
  3718. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3719. */
  3720. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3721. // Produces a quaternion from Euler angles in the z-x-z orientation
  3722. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3723. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3724. var halfBeta = beta * 0.5;
  3725. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3726. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3727. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3728. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3729. };
  3730. /**
  3731. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3732. * cf to Vector3.RotationFromAxis() documentation.
  3733. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3734. */
  3735. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3736. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3737. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3738. return quat;
  3739. };
  3740. /**
  3741. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3742. * cf to Vector3.RotationFromAxis() documentation.
  3743. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3744. */
  3745. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3746. var rotMat = MathTmp.Matrix[0];
  3747. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3748. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3749. };
  3750. Quaternion.Slerp = function (left, right, amount) {
  3751. var result = Quaternion.Identity();
  3752. Quaternion.SlerpToRef(left, right, amount, result);
  3753. return result;
  3754. };
  3755. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3756. var num2;
  3757. var num3;
  3758. var num = amount;
  3759. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3760. var flag = false;
  3761. if (num4 < 0) {
  3762. flag = true;
  3763. num4 = -num4;
  3764. }
  3765. if (num4 > 0.999999) {
  3766. num3 = 1 - num;
  3767. num2 = flag ? -num : num;
  3768. }
  3769. else {
  3770. var num5 = Math.acos(num4);
  3771. var num6 = (1.0 / Math.sin(num5));
  3772. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3773. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3774. }
  3775. result.x = (num3 * left.x) + (num2 * right.x);
  3776. result.y = (num3 * left.y) + (num2 * right.y);
  3777. result.z = (num3 * left.z) + (num2 * right.z);
  3778. result.w = (num3 * left.w) + (num2 * right.w);
  3779. };
  3780. /**
  3781. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3782. */
  3783. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3784. var squared = amount * amount;
  3785. var cubed = amount * squared;
  3786. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3787. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3788. var part3 = (cubed - (2.0 * squared)) + amount;
  3789. var part4 = cubed - squared;
  3790. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3791. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3792. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3793. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3794. return new Quaternion(x, y, z, w);
  3795. };
  3796. return Quaternion;
  3797. }());
  3798. BABYLON.Quaternion = Quaternion;
  3799. var Matrix = /** @class */ (function () {
  3800. function Matrix() {
  3801. this._isIdentity = false;
  3802. this._isIdentityDirty = true;
  3803. this.m = new Float32Array(16);
  3804. this._markAsUpdated();
  3805. }
  3806. Matrix.prototype._markAsUpdated = function () {
  3807. this.updateFlag = Matrix._updateFlagSeed++;
  3808. this._isIdentityDirty = true;
  3809. };
  3810. // Properties
  3811. /**
  3812. * Boolean : True is the matrix is the identity matrix
  3813. */
  3814. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3815. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3816. if (this._isIdentityDirty) {
  3817. this._isIdentityDirty = false;
  3818. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3819. this._isIdentity = false;
  3820. }
  3821. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3822. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3823. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3824. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3825. this._isIdentity = false;
  3826. }
  3827. else {
  3828. this._isIdentity = true;
  3829. }
  3830. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3831. this._isIdentity = false;
  3832. }
  3833. }
  3834. return this._isIdentity;
  3835. };
  3836. /**
  3837. * Returns the matrix determinant (float).
  3838. */
  3839. Matrix.prototype.determinant = function () {
  3840. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3841. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3842. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3843. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3844. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3845. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3846. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3847. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3848. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3849. };
  3850. // Methods
  3851. /**
  3852. * Returns the matrix underlying array.
  3853. */
  3854. Matrix.prototype.toArray = function () {
  3855. return this.m;
  3856. };
  3857. /**
  3858. * Returns the matrix underlying array.
  3859. */
  3860. Matrix.prototype.asArray = function () {
  3861. return this.toArray();
  3862. };
  3863. /**
  3864. * Inverts in place the Matrix.
  3865. * Returns the Matrix inverted.
  3866. */
  3867. Matrix.prototype.invert = function () {
  3868. this.invertToRef(this);
  3869. return this;
  3870. };
  3871. /**
  3872. * Sets all the matrix elements to zero.
  3873. * Returns the Matrix.
  3874. */
  3875. Matrix.prototype.reset = function () {
  3876. for (var index = 0; index < 16; index++) {
  3877. this.m[index] = 0.0;
  3878. }
  3879. this._markAsUpdated();
  3880. return this;
  3881. };
  3882. /**
  3883. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3884. */
  3885. Matrix.prototype.add = function (other) {
  3886. var result = new Matrix();
  3887. this.addToRef(other, result);
  3888. return result;
  3889. };
  3890. /**
  3891. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3892. * Returns the Matrix.
  3893. */
  3894. Matrix.prototype.addToRef = function (other, result) {
  3895. for (var index = 0; index < 16; index++) {
  3896. result.m[index] = this.m[index] + other.m[index];
  3897. }
  3898. result._markAsUpdated();
  3899. return this;
  3900. };
  3901. /**
  3902. * Adds in place the passed matrix to the current Matrix.
  3903. * Returns the updated Matrix.
  3904. */
  3905. Matrix.prototype.addToSelf = function (other) {
  3906. for (var index = 0; index < 16; index++) {
  3907. this.m[index] += other.m[index];
  3908. }
  3909. this._markAsUpdated();
  3910. return this;
  3911. };
  3912. /**
  3913. * Sets the passed matrix with the current inverted Matrix.
  3914. * Returns the unmodified current Matrix.
  3915. */
  3916. Matrix.prototype.invertToRef = function (other) {
  3917. var l1 = this.m[0];
  3918. var l2 = this.m[1];
  3919. var l3 = this.m[2];
  3920. var l4 = this.m[3];
  3921. var l5 = this.m[4];
  3922. var l6 = this.m[5];
  3923. var l7 = this.m[6];
  3924. var l8 = this.m[7];
  3925. var l9 = this.m[8];
  3926. var l10 = this.m[9];
  3927. var l11 = this.m[10];
  3928. var l12 = this.m[11];
  3929. var l13 = this.m[12];
  3930. var l14 = this.m[13];
  3931. var l15 = this.m[14];
  3932. var l16 = this.m[15];
  3933. var l17 = (l11 * l16) - (l12 * l15);
  3934. var l18 = (l10 * l16) - (l12 * l14);
  3935. var l19 = (l10 * l15) - (l11 * l14);
  3936. var l20 = (l9 * l16) - (l12 * l13);
  3937. var l21 = (l9 * l15) - (l11 * l13);
  3938. var l22 = (l9 * l14) - (l10 * l13);
  3939. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3940. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3941. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3942. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3943. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3944. var l28 = (l7 * l16) - (l8 * l15);
  3945. var l29 = (l6 * l16) - (l8 * l14);
  3946. var l30 = (l6 * l15) - (l7 * l14);
  3947. var l31 = (l5 * l16) - (l8 * l13);
  3948. var l32 = (l5 * l15) - (l7 * l13);
  3949. var l33 = (l5 * l14) - (l6 * l13);
  3950. var l34 = (l7 * l12) - (l8 * l11);
  3951. var l35 = (l6 * l12) - (l8 * l10);
  3952. var l36 = (l6 * l11) - (l7 * l10);
  3953. var l37 = (l5 * l12) - (l8 * l9);
  3954. var l38 = (l5 * l11) - (l7 * l9);
  3955. var l39 = (l5 * l10) - (l6 * l9);
  3956. other.m[0] = l23 * l27;
  3957. other.m[4] = l24 * l27;
  3958. other.m[8] = l25 * l27;
  3959. other.m[12] = l26 * l27;
  3960. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3961. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3962. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3963. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3964. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3965. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3966. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3967. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3968. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3969. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3970. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3971. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3972. other._markAsUpdated();
  3973. return this;
  3974. };
  3975. /**
  3976. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3977. * Returns the updated Matrix.
  3978. */
  3979. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3980. this.m[12] = x;
  3981. this.m[13] = y;
  3982. this.m[14] = z;
  3983. this._markAsUpdated();
  3984. return this;
  3985. };
  3986. /**
  3987. * Inserts the translation vector in the current Matrix.
  3988. * Returns the updated Matrix.
  3989. */
  3990. Matrix.prototype.setTranslation = function (vector3) {
  3991. this.m[12] = vector3.x;
  3992. this.m[13] = vector3.y;
  3993. this.m[14] = vector3.z;
  3994. this._markAsUpdated();
  3995. return this;
  3996. };
  3997. /**
  3998. * Returns a new Vector3 as the extracted translation from the Matrix.
  3999. */
  4000. Matrix.prototype.getTranslation = function () {
  4001. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4002. };
  4003. /**
  4004. * Fill a Vector3 with the extracted translation from the Matrix.
  4005. */
  4006. Matrix.prototype.getTranslationToRef = function (result) {
  4007. result.x = this.m[12];
  4008. result.y = this.m[13];
  4009. result.z = this.m[14];
  4010. return this;
  4011. };
  4012. /**
  4013. * Remove rotation and scaling part from the Matrix.
  4014. * Returns the updated Matrix.
  4015. */
  4016. Matrix.prototype.removeRotationAndScaling = function () {
  4017. this.setRowFromFloats(0, 1, 0, 0, 0);
  4018. this.setRowFromFloats(1, 0, 1, 0, 0);
  4019. this.setRowFromFloats(2, 0, 0, 1, 0);
  4020. return this;
  4021. };
  4022. /**
  4023. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4024. */
  4025. Matrix.prototype.multiply = function (other) {
  4026. var result = new Matrix();
  4027. this.multiplyToRef(other, result);
  4028. return result;
  4029. };
  4030. /**
  4031. * Updates the current Matrix from the passed one values.
  4032. * Returns the updated Matrix.
  4033. */
  4034. Matrix.prototype.copyFrom = function (other) {
  4035. for (var index = 0; index < 16; index++) {
  4036. this.m[index] = other.m[index];
  4037. }
  4038. this._markAsUpdated();
  4039. return this;
  4040. };
  4041. /**
  4042. * Populates the passed array from the starting index with the Matrix values.
  4043. * Returns the Matrix.
  4044. */
  4045. Matrix.prototype.copyToArray = function (array, offset) {
  4046. if (offset === void 0) { offset = 0; }
  4047. for (var index = 0; index < 16; index++) {
  4048. array[offset + index] = this.m[index];
  4049. }
  4050. return this;
  4051. };
  4052. /**
  4053. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4054. */
  4055. Matrix.prototype.multiplyToRef = function (other, result) {
  4056. this.multiplyToArray(other, result.m, 0);
  4057. result._markAsUpdated();
  4058. return this;
  4059. };
  4060. /**
  4061. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4062. */
  4063. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4064. var tm0 = this.m[0];
  4065. var tm1 = this.m[1];
  4066. var tm2 = this.m[2];
  4067. var tm3 = this.m[3];
  4068. var tm4 = this.m[4];
  4069. var tm5 = this.m[5];
  4070. var tm6 = this.m[6];
  4071. var tm7 = this.m[7];
  4072. var tm8 = this.m[8];
  4073. var tm9 = this.m[9];
  4074. var tm10 = this.m[10];
  4075. var tm11 = this.m[11];
  4076. var tm12 = this.m[12];
  4077. var tm13 = this.m[13];
  4078. var tm14 = this.m[14];
  4079. var tm15 = this.m[15];
  4080. var om0 = other.m[0];
  4081. var om1 = other.m[1];
  4082. var om2 = other.m[2];
  4083. var om3 = other.m[3];
  4084. var om4 = other.m[4];
  4085. var om5 = other.m[5];
  4086. var om6 = other.m[6];
  4087. var om7 = other.m[7];
  4088. var om8 = other.m[8];
  4089. var om9 = other.m[9];
  4090. var om10 = other.m[10];
  4091. var om11 = other.m[11];
  4092. var om12 = other.m[12];
  4093. var om13 = other.m[13];
  4094. var om14 = other.m[14];
  4095. var om15 = other.m[15];
  4096. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4097. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4098. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4099. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4100. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4101. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4102. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4103. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4104. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4105. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4106. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4107. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4108. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4109. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4110. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4111. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4112. return this;
  4113. };
  4114. /**
  4115. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4116. */
  4117. Matrix.prototype.equals = function (value) {
  4118. return value &&
  4119. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4120. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4121. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4122. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4123. };
  4124. /**
  4125. * Returns a new Matrix from the current Matrix.
  4126. */
  4127. Matrix.prototype.clone = function () {
  4128. 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]);
  4129. };
  4130. /**
  4131. * Returns the string "Matrix"
  4132. */
  4133. Matrix.prototype.getClassName = function () {
  4134. return "Matrix";
  4135. };
  4136. /**
  4137. * Returns the Matrix hash code.
  4138. */
  4139. Matrix.prototype.getHashCode = function () {
  4140. var hash = this.m[0] || 0;
  4141. for (var i = 1; i < 16; i++) {
  4142. hash = (hash * 397) ^ (this.m[i] || 0);
  4143. }
  4144. return hash;
  4145. };
  4146. /**
  4147. * Decomposes the current Matrix into :
  4148. * - a scale vector3 passed as a reference to update,
  4149. * - a rotation quaternion passed as a reference to update,
  4150. * - a translation vector3 passed as a reference to update.
  4151. * Returns the boolean `true`.
  4152. */
  4153. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4154. translation.x = this.m[12];
  4155. translation.y = this.m[13];
  4156. translation.z = this.m[14];
  4157. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4158. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4159. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4160. if (this.determinant() <= 0) {
  4161. scale.y *= -1;
  4162. }
  4163. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4164. rotation.x = 0;
  4165. rotation.y = 0;
  4166. rotation.z = 0;
  4167. rotation.w = 1;
  4168. return false;
  4169. }
  4170. 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]);
  4171. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4172. return true;
  4173. };
  4174. /**
  4175. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4176. */
  4177. Matrix.prototype.getRotationMatrix = function () {
  4178. var result = Matrix.Identity();
  4179. this.getRotationMatrixToRef(result);
  4180. return result;
  4181. };
  4182. /**
  4183. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4184. * Returns the current Matrix.
  4185. */
  4186. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4187. var m = this.m;
  4188. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4189. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4190. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4191. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4192. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4193. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4194. 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);
  4195. return this;
  4196. };
  4197. // Statics
  4198. /**
  4199. * Returns a new Matrix set from the starting index of the passed array.
  4200. */
  4201. Matrix.FromArray = function (array, offset) {
  4202. var result = new Matrix();
  4203. if (!offset) {
  4204. offset = 0;
  4205. }
  4206. Matrix.FromArrayToRef(array, offset, result);
  4207. return result;
  4208. };
  4209. /**
  4210. * Sets the passed "result" matrix from the starting index of the passed array.
  4211. */
  4212. Matrix.FromArrayToRef = function (array, offset, result) {
  4213. for (var index = 0; index < 16; index++) {
  4214. result.m[index] = array[index + offset];
  4215. }
  4216. result._markAsUpdated();
  4217. };
  4218. /**
  4219. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4220. */
  4221. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4222. for (var index = 0; index < 16; index++) {
  4223. result.m[index] = array[index + offset] * scale;
  4224. }
  4225. result._markAsUpdated();
  4226. };
  4227. /**
  4228. * Sets the passed matrix "result" with the 16 passed floats.
  4229. */
  4230. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4231. result.m[0] = initialM11;
  4232. result.m[1] = initialM12;
  4233. result.m[2] = initialM13;
  4234. result.m[3] = initialM14;
  4235. result.m[4] = initialM21;
  4236. result.m[5] = initialM22;
  4237. result.m[6] = initialM23;
  4238. result.m[7] = initialM24;
  4239. result.m[8] = initialM31;
  4240. result.m[9] = initialM32;
  4241. result.m[10] = initialM33;
  4242. result.m[11] = initialM34;
  4243. result.m[12] = initialM41;
  4244. result.m[13] = initialM42;
  4245. result.m[14] = initialM43;
  4246. result.m[15] = initialM44;
  4247. result._markAsUpdated();
  4248. };
  4249. /**
  4250. * Returns the index-th row of the current matrix as a new Vector4.
  4251. */
  4252. Matrix.prototype.getRow = function (index) {
  4253. if (index < 0 || index > 3) {
  4254. return null;
  4255. }
  4256. var i = index * 4;
  4257. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4258. };
  4259. /**
  4260. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4261. * Returns the updated Matrix.
  4262. */
  4263. Matrix.prototype.setRow = function (index, row) {
  4264. if (index < 0 || index > 3) {
  4265. return this;
  4266. }
  4267. var i = index * 4;
  4268. this.m[i + 0] = row.x;
  4269. this.m[i + 1] = row.y;
  4270. this.m[i + 2] = row.z;
  4271. this.m[i + 3] = row.w;
  4272. this._markAsUpdated();
  4273. return this;
  4274. };
  4275. /**
  4276. * Compute the transpose of the matrix.
  4277. * Returns a new Matrix.
  4278. */
  4279. Matrix.prototype.transpose = function () {
  4280. return Matrix.Transpose(this);
  4281. };
  4282. /**
  4283. * Compute the transpose of the matrix.
  4284. * Returns the current matrix.
  4285. */
  4286. Matrix.prototype.transposeToRef = function (result) {
  4287. Matrix.TransposeToRef(this, result);
  4288. return this;
  4289. };
  4290. /**
  4291. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4292. * Returns the updated Matrix.
  4293. */
  4294. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4295. if (index < 0 || index > 3) {
  4296. return this;
  4297. }
  4298. var i = index * 4;
  4299. this.m[i + 0] = x;
  4300. this.m[i + 1] = y;
  4301. this.m[i + 2] = z;
  4302. this.m[i + 3] = w;
  4303. this._markAsUpdated();
  4304. return this;
  4305. };
  4306. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4307. /**
  4308. * Static identity matrix to be used as readonly matrix
  4309. * Must not be updated.
  4310. */
  4311. get: function () {
  4312. return Matrix._identityReadOnly;
  4313. },
  4314. enumerable: true,
  4315. configurable: true
  4316. });
  4317. /**
  4318. * Returns a new Matrix set from the 16 passed floats.
  4319. */
  4320. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4321. var result = new Matrix();
  4322. result.m[0] = initialM11;
  4323. result.m[1] = initialM12;
  4324. result.m[2] = initialM13;
  4325. result.m[3] = initialM14;
  4326. result.m[4] = initialM21;
  4327. result.m[5] = initialM22;
  4328. result.m[6] = initialM23;
  4329. result.m[7] = initialM24;
  4330. result.m[8] = initialM31;
  4331. result.m[9] = initialM32;
  4332. result.m[10] = initialM33;
  4333. result.m[11] = initialM34;
  4334. result.m[12] = initialM41;
  4335. result.m[13] = initialM42;
  4336. result.m[14] = initialM43;
  4337. result.m[15] = initialM44;
  4338. return result;
  4339. };
  4340. /**
  4341. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4342. */
  4343. Matrix.Compose = function (scale, rotation, translation) {
  4344. var result = Matrix.Identity();
  4345. Matrix.ComposeToRef(scale, rotation, translation, result);
  4346. return result;
  4347. };
  4348. /**
  4349. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4350. */
  4351. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4352. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4353. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4354. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4355. result.setTranslation(translation);
  4356. };
  4357. /**
  4358. * Returns a new indentity Matrix.
  4359. */
  4360. Matrix.Identity = function () {
  4361. 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);
  4362. };
  4363. /**
  4364. * Sets the passed "result" as an identity matrix.
  4365. */
  4366. Matrix.IdentityToRef = function (result) {
  4367. 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);
  4368. };
  4369. /**
  4370. * Returns a new zero Matrix.
  4371. */
  4372. Matrix.Zero = function () {
  4373. 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);
  4374. };
  4375. /**
  4376. * Returns a new rotation matrix for "angle" radians around the X axis.
  4377. */
  4378. Matrix.RotationX = function (angle) {
  4379. var result = new Matrix();
  4380. Matrix.RotationXToRef(angle, result);
  4381. return result;
  4382. };
  4383. /**
  4384. * Returns a new Matrix as the passed inverted one.
  4385. */
  4386. Matrix.Invert = function (source) {
  4387. var result = new Matrix();
  4388. source.invertToRef(result);
  4389. return result;
  4390. };
  4391. /**
  4392. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4393. */
  4394. Matrix.RotationXToRef = function (angle, result) {
  4395. var s = Math.sin(angle);
  4396. var c = Math.cos(angle);
  4397. result.m[0] = 1.0;
  4398. result.m[15] = 1.0;
  4399. result.m[5] = c;
  4400. result.m[10] = c;
  4401. result.m[9] = -s;
  4402. result.m[6] = s;
  4403. result.m[1] = 0.0;
  4404. result.m[2] = 0.0;
  4405. result.m[3] = 0.0;
  4406. result.m[4] = 0.0;
  4407. result.m[7] = 0.0;
  4408. result.m[8] = 0.0;
  4409. result.m[11] = 0.0;
  4410. result.m[12] = 0.0;
  4411. result.m[13] = 0.0;
  4412. result.m[14] = 0.0;
  4413. result._markAsUpdated();
  4414. };
  4415. /**
  4416. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4417. */
  4418. Matrix.RotationY = function (angle) {
  4419. var result = new Matrix();
  4420. Matrix.RotationYToRef(angle, result);
  4421. return result;
  4422. };
  4423. /**
  4424. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4425. */
  4426. Matrix.RotationYToRef = function (angle, result) {
  4427. var s = Math.sin(angle);
  4428. var c = Math.cos(angle);
  4429. result.m[5] = 1.0;
  4430. result.m[15] = 1.0;
  4431. result.m[0] = c;
  4432. result.m[2] = -s;
  4433. result.m[8] = s;
  4434. result.m[10] = c;
  4435. result.m[1] = 0.0;
  4436. result.m[3] = 0.0;
  4437. result.m[4] = 0.0;
  4438. result.m[6] = 0.0;
  4439. result.m[7] = 0.0;
  4440. result.m[9] = 0.0;
  4441. result.m[11] = 0.0;
  4442. result.m[12] = 0.0;
  4443. result.m[13] = 0.0;
  4444. result.m[14] = 0.0;
  4445. result._markAsUpdated();
  4446. };
  4447. /**
  4448. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4449. */
  4450. Matrix.RotationZ = function (angle) {
  4451. var result = new Matrix();
  4452. Matrix.RotationZToRef(angle, result);
  4453. return result;
  4454. };
  4455. /**
  4456. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4457. */
  4458. Matrix.RotationZToRef = function (angle, result) {
  4459. var s = Math.sin(angle);
  4460. var c = Math.cos(angle);
  4461. result.m[10] = 1.0;
  4462. result.m[15] = 1.0;
  4463. result.m[0] = c;
  4464. result.m[1] = s;
  4465. result.m[4] = -s;
  4466. result.m[5] = c;
  4467. result.m[2] = 0.0;
  4468. result.m[3] = 0.0;
  4469. result.m[6] = 0.0;
  4470. result.m[7] = 0.0;
  4471. result.m[8] = 0.0;
  4472. result.m[9] = 0.0;
  4473. result.m[11] = 0.0;
  4474. result.m[12] = 0.0;
  4475. result.m[13] = 0.0;
  4476. result.m[14] = 0.0;
  4477. result._markAsUpdated();
  4478. };
  4479. /**
  4480. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4481. */
  4482. Matrix.RotationAxis = function (axis, angle) {
  4483. var result = Matrix.Zero();
  4484. Matrix.RotationAxisToRef(axis, angle, result);
  4485. return result;
  4486. };
  4487. /**
  4488. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4489. */
  4490. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4491. var s = Math.sin(-angle);
  4492. var c = Math.cos(-angle);
  4493. var c1 = 1 - c;
  4494. axis.normalize();
  4495. result.m[0] = (axis.x * axis.x) * c1 + c;
  4496. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4497. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4498. result.m[3] = 0.0;
  4499. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4500. result.m[5] = (axis.y * axis.y) * c1 + c;
  4501. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4502. result.m[7] = 0.0;
  4503. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4504. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4505. result.m[10] = (axis.z * axis.z) * c1 + c;
  4506. result.m[11] = 0.0;
  4507. result.m[15] = 1.0;
  4508. result._markAsUpdated();
  4509. };
  4510. /**
  4511. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4512. */
  4513. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4514. var result = new Matrix();
  4515. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4516. return result;
  4517. };
  4518. /**
  4519. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4520. */
  4521. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4522. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4523. this._tempQuaternion.toRotationMatrix(result);
  4524. };
  4525. /**
  4526. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4527. */
  4528. Matrix.Scaling = function (x, y, z) {
  4529. var result = Matrix.Zero();
  4530. Matrix.ScalingToRef(x, y, z, result);
  4531. return result;
  4532. };
  4533. /**
  4534. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4535. */
  4536. Matrix.ScalingToRef = function (x, y, z, result) {
  4537. result.m[0] = x;
  4538. result.m[1] = 0.0;
  4539. result.m[2] = 0.0;
  4540. result.m[3] = 0.0;
  4541. result.m[4] = 0.0;
  4542. result.m[5] = y;
  4543. result.m[6] = 0.0;
  4544. result.m[7] = 0.0;
  4545. result.m[8] = 0.0;
  4546. result.m[9] = 0.0;
  4547. result.m[10] = z;
  4548. result.m[11] = 0.0;
  4549. result.m[12] = 0.0;
  4550. result.m[13] = 0.0;
  4551. result.m[14] = 0.0;
  4552. result.m[15] = 1.0;
  4553. result._markAsUpdated();
  4554. };
  4555. /**
  4556. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4557. */
  4558. Matrix.Translation = function (x, y, z) {
  4559. var result = Matrix.Identity();
  4560. Matrix.TranslationToRef(x, y, z, result);
  4561. return result;
  4562. };
  4563. /**
  4564. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4565. */
  4566. Matrix.TranslationToRef = function (x, y, z, result) {
  4567. 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);
  4568. };
  4569. /**
  4570. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4571. */
  4572. Matrix.Lerp = function (startValue, endValue, gradient) {
  4573. var result = Matrix.Zero();
  4574. for (var index = 0; index < 16; index++) {
  4575. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4576. }
  4577. result._markAsUpdated();
  4578. return result;
  4579. };
  4580. /**
  4581. * Returns a new Matrix whose values are computed by :
  4582. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4583. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4584. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4585. */
  4586. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4587. var startScale = new Vector3(0, 0, 0);
  4588. var startRotation = new Quaternion();
  4589. var startTranslation = new Vector3(0, 0, 0);
  4590. startValue.decompose(startScale, startRotation, startTranslation);
  4591. var endScale = new Vector3(0, 0, 0);
  4592. var endRotation = new Quaternion();
  4593. var endTranslation = new Vector3(0, 0, 0);
  4594. endValue.decompose(endScale, endRotation, endTranslation);
  4595. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4596. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4597. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4598. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4599. };
  4600. /**
  4601. * 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".
  4602. * This methods works for a Left-Handed system.
  4603. */
  4604. Matrix.LookAtLH = function (eye, target, up) {
  4605. var result = Matrix.Zero();
  4606. Matrix.LookAtLHToRef(eye, target, up, result);
  4607. return result;
  4608. };
  4609. /**
  4610. * 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".
  4611. * This methods works for a Left-Handed system.
  4612. */
  4613. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4614. // Z axis
  4615. target.subtractToRef(eye, this._zAxis);
  4616. this._zAxis.normalize();
  4617. // X axis
  4618. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4619. if (this._xAxis.lengthSquared() === 0) {
  4620. this._xAxis.x = 1.0;
  4621. }
  4622. else {
  4623. this._xAxis.normalize();
  4624. }
  4625. // Y axis
  4626. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4627. this._yAxis.normalize();
  4628. // Eye angles
  4629. var ex = -Vector3.Dot(this._xAxis, eye);
  4630. var ey = -Vector3.Dot(this._yAxis, eye);
  4631. var ez = -Vector3.Dot(this._zAxis, eye);
  4632. 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);
  4633. };
  4634. /**
  4635. * 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".
  4636. * This methods works for a Right-Handed system.
  4637. */
  4638. Matrix.LookAtRH = function (eye, target, up) {
  4639. var result = Matrix.Zero();
  4640. Matrix.LookAtRHToRef(eye, target, up, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * 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".
  4645. * This methods works for a Left-Handed system.
  4646. */
  4647. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4648. // Z axis
  4649. eye.subtractToRef(target, this._zAxis);
  4650. this._zAxis.normalize();
  4651. // X axis
  4652. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4653. if (this._xAxis.lengthSquared() === 0) {
  4654. this._xAxis.x = 1.0;
  4655. }
  4656. else {
  4657. this._xAxis.normalize();
  4658. }
  4659. // Y axis
  4660. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4661. this._yAxis.normalize();
  4662. // Eye angles
  4663. var ex = -Vector3.Dot(this._xAxis, eye);
  4664. var ey = -Vector3.Dot(this._yAxis, eye);
  4665. var ez = -Vector3.Dot(this._zAxis, eye);
  4666. 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);
  4667. };
  4668. /**
  4669. * 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.
  4670. */
  4671. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4672. var matrix = Matrix.Zero();
  4673. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4674. return matrix;
  4675. };
  4676. /**
  4677. * 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.
  4678. */
  4679. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4680. var n = znear;
  4681. var f = zfar;
  4682. var a = 2.0 / width;
  4683. var b = 2.0 / height;
  4684. var c = 2.0 / (f - n);
  4685. var d = -(f + n) / (f - n);
  4686. 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);
  4687. };
  4688. /**
  4689. * 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.
  4690. */
  4691. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4692. var matrix = Matrix.Zero();
  4693. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4694. return matrix;
  4695. };
  4696. /**
  4697. * 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.
  4698. */
  4699. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4700. var n = znear;
  4701. var f = zfar;
  4702. var a = 2.0 / (right - left);
  4703. var b = 2.0 / (top - bottom);
  4704. var c = 2.0 / (f - n);
  4705. var d = -(f + n) / (f - n);
  4706. var i0 = (left + right) / (left - right);
  4707. var i1 = (top + bottom) / (bottom - top);
  4708. 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);
  4709. };
  4710. /**
  4711. * 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.
  4712. */
  4713. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4714. var matrix = Matrix.Zero();
  4715. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4716. return matrix;
  4717. };
  4718. /**
  4719. * 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.
  4720. */
  4721. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4722. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4723. result.m[10] *= -1.0;
  4724. };
  4725. /**
  4726. * 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.
  4727. */
  4728. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4729. var matrix = Matrix.Zero();
  4730. var n = znear;
  4731. var f = zfar;
  4732. var a = 2.0 * n / width;
  4733. var b = 2.0 * n / height;
  4734. var c = (f + n) / (f - n);
  4735. var d = -2.0 * f * n / (f - n);
  4736. 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);
  4737. return matrix;
  4738. };
  4739. /**
  4740. * 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.
  4741. */
  4742. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4743. var matrix = Matrix.Zero();
  4744. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4745. return matrix;
  4746. };
  4747. /**
  4748. * 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.
  4749. */
  4750. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4751. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4752. var n = znear;
  4753. var f = zfar;
  4754. var t = 1.0 / (Math.tan(fov * 0.5));
  4755. var a = isVerticalFovFixed ? (t / aspect) : t;
  4756. var b = isVerticalFovFixed ? t : (t * aspect);
  4757. var c = (f + n) / (f - n);
  4758. var d = -2.0 * f * n / (f - n);
  4759. 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);
  4760. };
  4761. /**
  4762. * 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.
  4763. */
  4764. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4765. var matrix = Matrix.Zero();
  4766. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4767. return matrix;
  4768. };
  4769. /**
  4770. * 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.
  4771. */
  4772. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4773. //alternatively this could be expressed as:
  4774. // m = PerspectiveFovLHToRef
  4775. // m[10] *= -1.0;
  4776. // m[11] *= -1.0;
  4777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4778. var n = znear;
  4779. var f = zfar;
  4780. var t = 1.0 / (Math.tan(fov * 0.5));
  4781. var a = isVerticalFovFixed ? (t / aspect) : t;
  4782. var b = isVerticalFovFixed ? t : (t * aspect);
  4783. var c = -(f + n) / (f - n);
  4784. var d = -2 * f * n / (f - n);
  4785. 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);
  4786. };
  4787. /**
  4788. * 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.
  4789. */
  4790. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4791. if (rightHanded === void 0) { rightHanded = false; }
  4792. var rightHandedFactor = rightHanded ? -1 : 1;
  4793. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4794. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4795. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4796. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4797. var xScale = 2.0 / (leftTan + rightTan);
  4798. var yScale = 2.0 / (upTan + downTan);
  4799. result.m[0] = xScale;
  4800. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4801. result.m[5] = yScale;
  4802. result.m[6] = result.m[7] = 0.0;
  4803. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4804. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4805. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4806. result.m[10] = -zfar / (znear - zfar);
  4807. result.m[11] = 1.0 * rightHandedFactor;
  4808. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4809. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4810. // result.m[14] = (znear * zfar) / (znear - zfar);
  4811. result._markAsUpdated();
  4812. };
  4813. /**
  4814. * Returns the final transformation matrix : world * view * projection * viewport
  4815. */
  4816. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4817. var cw = viewport.width;
  4818. var ch = viewport.height;
  4819. var cx = viewport.x;
  4820. var cy = viewport.y;
  4821. 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);
  4822. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4823. };
  4824. /**
  4825. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4826. */
  4827. Matrix.GetAsMatrix2x2 = function (matrix) {
  4828. return new Float32Array([
  4829. matrix.m[0], matrix.m[1],
  4830. matrix.m[4], matrix.m[5]
  4831. ]);
  4832. };
  4833. /**
  4834. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4835. */
  4836. Matrix.GetAsMatrix3x3 = function (matrix) {
  4837. return new Float32Array([
  4838. matrix.m[0], matrix.m[1], matrix.m[2],
  4839. matrix.m[4], matrix.m[5], matrix.m[6],
  4840. matrix.m[8], matrix.m[9], matrix.m[10]
  4841. ]);
  4842. };
  4843. /**
  4844. * Compute the transpose of the passed Matrix.
  4845. * Returns a new Matrix.
  4846. */
  4847. Matrix.Transpose = function (matrix) {
  4848. var result = new Matrix();
  4849. Matrix.TransposeToRef(matrix, result);
  4850. return result;
  4851. };
  4852. /**
  4853. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4854. */
  4855. Matrix.TransposeToRef = function (matrix, result) {
  4856. result.m[0] = matrix.m[0];
  4857. result.m[1] = matrix.m[4];
  4858. result.m[2] = matrix.m[8];
  4859. result.m[3] = matrix.m[12];
  4860. result.m[4] = matrix.m[1];
  4861. result.m[5] = matrix.m[5];
  4862. result.m[6] = matrix.m[9];
  4863. result.m[7] = matrix.m[13];
  4864. result.m[8] = matrix.m[2];
  4865. result.m[9] = matrix.m[6];
  4866. result.m[10] = matrix.m[10];
  4867. result.m[11] = matrix.m[14];
  4868. result.m[12] = matrix.m[3];
  4869. result.m[13] = matrix.m[7];
  4870. result.m[14] = matrix.m[11];
  4871. result.m[15] = matrix.m[15];
  4872. };
  4873. /**
  4874. * Returns a new Matrix as the reflection matrix across the passed plane.
  4875. */
  4876. Matrix.Reflection = function (plane) {
  4877. var matrix = new Matrix();
  4878. Matrix.ReflectionToRef(plane, matrix);
  4879. return matrix;
  4880. };
  4881. /**
  4882. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4883. */
  4884. Matrix.ReflectionToRef = function (plane, result) {
  4885. plane.normalize();
  4886. var x = plane.normal.x;
  4887. var y = plane.normal.y;
  4888. var z = plane.normal.z;
  4889. var temp = -2 * x;
  4890. var temp2 = -2 * y;
  4891. var temp3 = -2 * z;
  4892. result.m[0] = (temp * x) + 1;
  4893. result.m[1] = temp2 * x;
  4894. result.m[2] = temp3 * x;
  4895. result.m[3] = 0.0;
  4896. result.m[4] = temp * y;
  4897. result.m[5] = (temp2 * y) + 1;
  4898. result.m[6] = temp3 * y;
  4899. result.m[7] = 0.0;
  4900. result.m[8] = temp * z;
  4901. result.m[9] = temp2 * z;
  4902. result.m[10] = (temp3 * z) + 1;
  4903. result.m[11] = 0.0;
  4904. result.m[12] = temp * plane.d;
  4905. result.m[13] = temp2 * plane.d;
  4906. result.m[14] = temp3 * plane.d;
  4907. result.m[15] = 1.0;
  4908. result._markAsUpdated();
  4909. };
  4910. /**
  4911. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4912. */
  4913. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4914. result.m[0] = xaxis.x;
  4915. result.m[1] = xaxis.y;
  4916. result.m[2] = xaxis.z;
  4917. result.m[3] = 0.0;
  4918. result.m[4] = yaxis.x;
  4919. result.m[5] = yaxis.y;
  4920. result.m[6] = yaxis.z;
  4921. result.m[7] = 0.0;
  4922. result.m[8] = zaxis.x;
  4923. result.m[9] = zaxis.y;
  4924. result.m[10] = zaxis.z;
  4925. result.m[11] = 0.0;
  4926. result.m[12] = 0.0;
  4927. result.m[13] = 0.0;
  4928. result.m[14] = 0.0;
  4929. result.m[15] = 1.0;
  4930. result._markAsUpdated();
  4931. };
  4932. /**
  4933. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4934. */
  4935. Matrix.FromQuaternionToRef = function (quat, result) {
  4936. var xx = quat.x * quat.x;
  4937. var yy = quat.y * quat.y;
  4938. var zz = quat.z * quat.z;
  4939. var xy = quat.x * quat.y;
  4940. var zw = quat.z * quat.w;
  4941. var zx = quat.z * quat.x;
  4942. var yw = quat.y * quat.w;
  4943. var yz = quat.y * quat.z;
  4944. var xw = quat.x * quat.w;
  4945. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4946. result.m[1] = 2.0 * (xy + zw);
  4947. result.m[2] = 2.0 * (zx - yw);
  4948. result.m[3] = 0.0;
  4949. result.m[4] = 2.0 * (xy - zw);
  4950. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4951. result.m[6] = 2.0 * (yz + xw);
  4952. result.m[7] = 0.0;
  4953. result.m[8] = 2.0 * (zx + yw);
  4954. result.m[9] = 2.0 * (yz - xw);
  4955. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4956. result.m[11] = 0.0;
  4957. result.m[12] = 0.0;
  4958. result.m[13] = 0.0;
  4959. result.m[14] = 0.0;
  4960. result.m[15] = 1.0;
  4961. result._markAsUpdated();
  4962. };
  4963. Matrix._tempQuaternion = new Quaternion();
  4964. Matrix._xAxis = Vector3.Zero();
  4965. Matrix._yAxis = Vector3.Zero();
  4966. Matrix._zAxis = Vector3.Zero();
  4967. Matrix._updateFlagSeed = 0;
  4968. Matrix._identityReadOnly = Matrix.Identity();
  4969. return Matrix;
  4970. }());
  4971. BABYLON.Matrix = Matrix;
  4972. var Plane = /** @class */ (function () {
  4973. /**
  4974. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4975. */
  4976. function Plane(a, b, c, d) {
  4977. this.normal = new Vector3(a, b, c);
  4978. this.d = d;
  4979. }
  4980. /**
  4981. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4982. */
  4983. Plane.prototype.asArray = function () {
  4984. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4985. };
  4986. // Methods
  4987. /**
  4988. * Returns a new plane copied from the current Plane.
  4989. */
  4990. Plane.prototype.clone = function () {
  4991. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4992. };
  4993. /**
  4994. * Returns the string "Plane".
  4995. */
  4996. Plane.prototype.getClassName = function () {
  4997. return "Plane";
  4998. };
  4999. /**
  5000. * Returns the Plane hash code.
  5001. */
  5002. Plane.prototype.getHashCode = function () {
  5003. var hash = this.normal.getHashCode();
  5004. hash = (hash * 397) ^ (this.d || 0);
  5005. return hash;
  5006. };
  5007. /**
  5008. * Normalize the current Plane in place.
  5009. * Returns the updated Plane.
  5010. */
  5011. Plane.prototype.normalize = function () {
  5012. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5013. var magnitude = 0.0;
  5014. if (norm !== 0) {
  5015. magnitude = 1.0 / norm;
  5016. }
  5017. this.normal.x *= magnitude;
  5018. this.normal.y *= magnitude;
  5019. this.normal.z *= magnitude;
  5020. this.d *= magnitude;
  5021. return this;
  5022. };
  5023. /**
  5024. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5025. */
  5026. Plane.prototype.transform = function (transformation) {
  5027. var transposedMatrix = Matrix.Transpose(transformation);
  5028. var x = this.normal.x;
  5029. var y = this.normal.y;
  5030. var z = this.normal.z;
  5031. var d = this.d;
  5032. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5033. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5034. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5035. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5036. return new Plane(normalX, normalY, normalZ, finalD);
  5037. };
  5038. /**
  5039. * Returns the dot product (float) of the point coordinates and the plane normal.
  5040. */
  5041. Plane.prototype.dotCoordinate = function (point) {
  5042. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5043. };
  5044. /**
  5045. * Updates the current Plane from the plane defined by the three passed points.
  5046. * Returns the updated Plane.
  5047. */
  5048. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5049. var x1 = point2.x - point1.x;
  5050. var y1 = point2.y - point1.y;
  5051. var z1 = point2.z - point1.z;
  5052. var x2 = point3.x - point1.x;
  5053. var y2 = point3.y - point1.y;
  5054. var z2 = point3.z - point1.z;
  5055. var yz = (y1 * z2) - (z1 * y2);
  5056. var xz = (z1 * x2) - (x1 * z2);
  5057. var xy = (x1 * y2) - (y1 * x2);
  5058. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5059. var invPyth;
  5060. if (pyth !== 0) {
  5061. invPyth = 1.0 / pyth;
  5062. }
  5063. else {
  5064. invPyth = 0.0;
  5065. }
  5066. this.normal.x = yz * invPyth;
  5067. this.normal.y = xz * invPyth;
  5068. this.normal.z = xy * invPyth;
  5069. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5070. return this;
  5071. };
  5072. /**
  5073. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5074. */
  5075. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5076. var dot = Vector3.Dot(this.normal, direction);
  5077. return (dot <= epsilon);
  5078. };
  5079. /**
  5080. * Returns the signed distance (float) from the passed point to the Plane.
  5081. */
  5082. Plane.prototype.signedDistanceTo = function (point) {
  5083. return Vector3.Dot(point, this.normal) + this.d;
  5084. };
  5085. // Statics
  5086. /**
  5087. * Returns a new Plane from the passed array.
  5088. */
  5089. Plane.FromArray = function (array) {
  5090. return new Plane(array[0], array[1], array[2], array[3]);
  5091. };
  5092. /**
  5093. * Returns a new Plane defined by the three passed points.
  5094. */
  5095. Plane.FromPoints = function (point1, point2, point3) {
  5096. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5097. result.copyFromPoints(point1, point2, point3);
  5098. return result;
  5099. };
  5100. /**
  5101. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5102. * Note : the vector "normal" is updated because normalized.
  5103. */
  5104. Plane.FromPositionAndNormal = function (origin, normal) {
  5105. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5106. normal.normalize();
  5107. result.normal = normal;
  5108. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5109. return result;
  5110. };
  5111. /**
  5112. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5113. */
  5114. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5115. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5116. return Vector3.Dot(point, normal) + d;
  5117. };
  5118. return Plane;
  5119. }());
  5120. BABYLON.Plane = Plane;
  5121. var Viewport = /** @class */ (function () {
  5122. /**
  5123. * Creates a Viewport object located at (x, y) and sized (width, height).
  5124. */
  5125. function Viewport(x, y, width, height) {
  5126. this.x = x;
  5127. this.y = y;
  5128. this.width = width;
  5129. this.height = height;
  5130. }
  5131. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5132. if (renderWidthOrEngine.getRenderWidth) {
  5133. var engine = renderWidthOrEngine;
  5134. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5135. }
  5136. var renderWidth = renderWidthOrEngine;
  5137. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5138. };
  5139. /**
  5140. * Returns a new Viewport copied from the current one.
  5141. */
  5142. Viewport.prototype.clone = function () {
  5143. return new Viewport(this.x, this.y, this.width, this.height);
  5144. };
  5145. return Viewport;
  5146. }());
  5147. BABYLON.Viewport = Viewport;
  5148. var Frustum = /** @class */ (function () {
  5149. function Frustum() {
  5150. }
  5151. /**
  5152. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5153. */
  5154. Frustum.GetPlanes = function (transform) {
  5155. var frustumPlanes = [];
  5156. for (var index = 0; index < 6; index++) {
  5157. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5158. }
  5159. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5160. return frustumPlanes;
  5161. };
  5162. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5163. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5164. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5165. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5166. frustumPlane.d = transform.m[15] + transform.m[14];
  5167. frustumPlane.normalize();
  5168. };
  5169. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5170. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5171. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5172. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5173. frustumPlane.d = transform.m[15] - transform.m[14];
  5174. frustumPlane.normalize();
  5175. };
  5176. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5177. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5178. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5179. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5180. frustumPlane.d = transform.m[15] + transform.m[12];
  5181. frustumPlane.normalize();
  5182. };
  5183. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5184. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5185. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5186. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5187. frustumPlane.d = transform.m[15] - transform.m[12];
  5188. frustumPlane.normalize();
  5189. };
  5190. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5191. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5192. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5193. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5194. frustumPlane.d = transform.m[15] - transform.m[13];
  5195. frustumPlane.normalize();
  5196. };
  5197. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5198. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5199. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5200. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5201. frustumPlane.d = transform.m[15] + transform.m[13];
  5202. frustumPlane.normalize();
  5203. };
  5204. /**
  5205. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5206. */
  5207. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5208. // Near
  5209. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5210. // Far
  5211. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5212. // Left
  5213. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5214. // Right
  5215. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5216. // Top
  5217. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5218. // Bottom
  5219. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5220. };
  5221. return Frustum;
  5222. }());
  5223. BABYLON.Frustum = Frustum;
  5224. var Space;
  5225. (function (Space) {
  5226. Space[Space["LOCAL"] = 0] = "LOCAL";
  5227. Space[Space["WORLD"] = 1] = "WORLD";
  5228. Space[Space["BONE"] = 2] = "BONE";
  5229. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5230. var Axis = /** @class */ (function () {
  5231. function Axis() {
  5232. }
  5233. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5234. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5235. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5236. return Axis;
  5237. }());
  5238. BABYLON.Axis = Axis;
  5239. ;
  5240. var BezierCurve = /** @class */ (function () {
  5241. function BezierCurve() {
  5242. }
  5243. /**
  5244. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5245. */
  5246. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5247. // Extract X (which is equal to time here)
  5248. var f0 = 1 - 3 * x2 + 3 * x1;
  5249. var f1 = 3 * x2 - 6 * x1;
  5250. var f2 = 3 * x1;
  5251. var refinedT = t;
  5252. for (var i = 0; i < 5; i++) {
  5253. var refinedT2 = refinedT * refinedT;
  5254. var refinedT3 = refinedT2 * refinedT;
  5255. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5256. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5257. refinedT -= (x - t) * slope;
  5258. refinedT = Math.min(1, Math.max(0, refinedT));
  5259. }
  5260. // Resolve cubic bezier for the given x
  5261. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5262. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5263. Math.pow(refinedT, 3);
  5264. };
  5265. return BezierCurve;
  5266. }());
  5267. BABYLON.BezierCurve = BezierCurve;
  5268. var Orientation;
  5269. (function (Orientation) {
  5270. Orientation[Orientation["CW"] = 0] = "CW";
  5271. Orientation[Orientation["CCW"] = 1] = "CCW";
  5272. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5273. var Angle = /** @class */ (function () {
  5274. /**
  5275. * Creates an Angle object of "radians" radians (float).
  5276. */
  5277. function Angle(radians) {
  5278. var _this = this;
  5279. /**
  5280. * Returns the Angle value in degrees (float).
  5281. */
  5282. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5283. /**
  5284. * Returns the Angle value in radians (float).
  5285. */
  5286. this.radians = function () { return _this._radians; };
  5287. this._radians = radians;
  5288. if (this._radians < 0.0)
  5289. this._radians += (2.0 * Math.PI);
  5290. }
  5291. /**
  5292. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5293. */
  5294. Angle.BetweenTwoPoints = function (a, b) {
  5295. var delta = b.subtract(a);
  5296. var theta = Math.atan2(delta.y, delta.x);
  5297. return new Angle(theta);
  5298. };
  5299. /**
  5300. * Returns a new Angle object from the passed float in radians.
  5301. */
  5302. Angle.FromRadians = function (radians) {
  5303. return new Angle(radians);
  5304. };
  5305. /**
  5306. * Returns a new Angle object from the passed float in degrees.
  5307. */
  5308. Angle.FromDegrees = function (degrees) {
  5309. return new Angle(degrees * Math.PI / 180.0);
  5310. };
  5311. return Angle;
  5312. }());
  5313. BABYLON.Angle = Angle;
  5314. var Arc2 = /** @class */ (function () {
  5315. /**
  5316. * Creates an Arc object from the three passed points : start, middle and end.
  5317. */
  5318. function Arc2(startPoint, midPoint, endPoint) {
  5319. this.startPoint = startPoint;
  5320. this.midPoint = midPoint;
  5321. this.endPoint = endPoint;
  5322. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5323. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5324. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5325. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5326. 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);
  5327. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5328. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5329. var a1 = this.startAngle.degrees();
  5330. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5331. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5332. // angles correction
  5333. if (a2 - a1 > +180.0)
  5334. a2 -= 360.0;
  5335. if (a2 - a1 < -180.0)
  5336. a2 += 360.0;
  5337. if (a3 - a2 > +180.0)
  5338. a3 -= 360.0;
  5339. if (a3 - a2 < -180.0)
  5340. a3 += 360.0;
  5341. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5342. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5343. }
  5344. return Arc2;
  5345. }());
  5346. BABYLON.Arc2 = Arc2;
  5347. var Path2 = /** @class */ (function () {
  5348. /**
  5349. * Creates a Path2 object from the starting 2D coordinates x and y.
  5350. */
  5351. function Path2(x, y) {
  5352. this._points = new Array();
  5353. this._length = 0.0;
  5354. this.closed = false;
  5355. this._points.push(new Vector2(x, y));
  5356. }
  5357. /**
  5358. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5359. * Returns the updated Path2.
  5360. */
  5361. Path2.prototype.addLineTo = function (x, y) {
  5362. if (this.closed) {
  5363. //Tools.Error("cannot add lines to closed paths");
  5364. return this;
  5365. }
  5366. var newPoint = new Vector2(x, y);
  5367. var previousPoint = this._points[this._points.length - 1];
  5368. this._points.push(newPoint);
  5369. this._length += newPoint.subtract(previousPoint).length();
  5370. return this;
  5371. };
  5372. /**
  5373. * 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.
  5374. * Returns the updated Path2.
  5375. */
  5376. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5377. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5378. if (this.closed) {
  5379. //Tools.Error("cannot add arcs to closed paths");
  5380. return this;
  5381. }
  5382. var startPoint = this._points[this._points.length - 1];
  5383. var midPoint = new Vector2(midX, midY);
  5384. var endPoint = new Vector2(endX, endY);
  5385. var arc = new Arc2(startPoint, midPoint, endPoint);
  5386. var increment = arc.angle.radians() / numberOfSegments;
  5387. if (arc.orientation === Orientation.CW)
  5388. increment *= -1;
  5389. var currentAngle = arc.startAngle.radians() + increment;
  5390. for (var i = 0; i < numberOfSegments; i++) {
  5391. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5392. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5393. this.addLineTo(x, y);
  5394. currentAngle += increment;
  5395. }
  5396. return this;
  5397. };
  5398. /**
  5399. * Closes the Path2.
  5400. * Returns the Path2.
  5401. */
  5402. Path2.prototype.close = function () {
  5403. this.closed = true;
  5404. return this;
  5405. };
  5406. /**
  5407. * Returns the Path2 total length (float).
  5408. */
  5409. Path2.prototype.length = function () {
  5410. var result = this._length;
  5411. if (!this.closed) {
  5412. var lastPoint = this._points[this._points.length - 1];
  5413. var firstPoint = this._points[0];
  5414. result += (firstPoint.subtract(lastPoint).length());
  5415. }
  5416. return result;
  5417. };
  5418. /**
  5419. * Returns the Path2 internal array of points.
  5420. */
  5421. Path2.prototype.getPoints = function () {
  5422. return this._points;
  5423. };
  5424. /**
  5425. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5426. */
  5427. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5428. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5429. //Tools.Error("normalized length position should be between 0 and 1.");
  5430. return Vector2.Zero();
  5431. }
  5432. var lengthPosition = normalizedLengthPosition * this.length();
  5433. var previousOffset = 0;
  5434. for (var i = 0; i < this._points.length; i++) {
  5435. var j = (i + 1) % this._points.length;
  5436. var a = this._points[i];
  5437. var b = this._points[j];
  5438. var bToA = b.subtract(a);
  5439. var nextOffset = (bToA.length() + previousOffset);
  5440. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5441. var dir = bToA.normalize();
  5442. var localOffset = lengthPosition - previousOffset;
  5443. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5444. }
  5445. previousOffset = nextOffset;
  5446. }
  5447. //Tools.Error("internal error");
  5448. return Vector2.Zero();
  5449. };
  5450. /**
  5451. * Returns a new Path2 starting at the coordinates (x, y).
  5452. */
  5453. Path2.StartingAt = function (x, y) {
  5454. return new Path2(x, y);
  5455. };
  5456. return Path2;
  5457. }());
  5458. BABYLON.Path2 = Path2;
  5459. var Path3D = /** @class */ (function () {
  5460. /**
  5461. * new Path3D(path, normal, raw)
  5462. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5463. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5464. * path : an array of Vector3, the curve axis of the Path3D
  5465. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5466. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5467. */
  5468. function Path3D(path, firstNormal, raw) {
  5469. if (firstNormal === void 0) { firstNormal = null; }
  5470. this.path = path;
  5471. this._curve = new Array();
  5472. this._distances = new Array();
  5473. this._tangents = new Array();
  5474. this._normals = new Array();
  5475. this._binormals = new Array();
  5476. for (var p = 0; p < path.length; p++) {
  5477. this._curve[p] = path[p].clone(); // hard copy
  5478. }
  5479. this._raw = raw || false;
  5480. this._compute(firstNormal);
  5481. }
  5482. /**
  5483. * Returns the Path3D array of successive Vector3 designing its curve.
  5484. */
  5485. Path3D.prototype.getCurve = function () {
  5486. return this._curve;
  5487. };
  5488. /**
  5489. * Returns an array populated with tangent vectors on each Path3D curve point.
  5490. */
  5491. Path3D.prototype.getTangents = function () {
  5492. return this._tangents;
  5493. };
  5494. /**
  5495. * Returns an array populated with normal vectors on each Path3D curve point.
  5496. */
  5497. Path3D.prototype.getNormals = function () {
  5498. return this._normals;
  5499. };
  5500. /**
  5501. * Returns an array populated with binormal vectors on each Path3D curve point.
  5502. */
  5503. Path3D.prototype.getBinormals = function () {
  5504. return this._binormals;
  5505. };
  5506. /**
  5507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5508. */
  5509. Path3D.prototype.getDistances = function () {
  5510. return this._distances;
  5511. };
  5512. /**
  5513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5514. * Returns the same object updated.
  5515. */
  5516. Path3D.prototype.update = function (path, firstNormal) {
  5517. if (firstNormal === void 0) { firstNormal = null; }
  5518. for (var p = 0; p < path.length; p++) {
  5519. this._curve[p].x = path[p].x;
  5520. this._curve[p].y = path[p].y;
  5521. this._curve[p].z = path[p].z;
  5522. }
  5523. this._compute(firstNormal);
  5524. return this;
  5525. };
  5526. // private function compute() : computes tangents, normals and binormals
  5527. Path3D.prototype._compute = function (firstNormal) {
  5528. var l = this._curve.length;
  5529. // first and last tangents
  5530. this._tangents[0] = this._getFirstNonNullVector(0);
  5531. if (!this._raw) {
  5532. this._tangents[0].normalize();
  5533. }
  5534. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5535. if (!this._raw) {
  5536. this._tangents[l - 1].normalize();
  5537. }
  5538. // normals and binormals at first point : arbitrary vector with _normalVector()
  5539. var tg0 = this._tangents[0];
  5540. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5541. this._normals[0] = pp0;
  5542. if (!this._raw) {
  5543. this._normals[0].normalize();
  5544. }
  5545. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5546. if (!this._raw) {
  5547. this._binormals[0].normalize();
  5548. }
  5549. this._distances[0] = 0.0;
  5550. // normals and binormals : next points
  5551. var prev; // previous vector (segment)
  5552. var cur; // current vector (segment)
  5553. var curTang; // current tangent
  5554. // previous normal
  5555. var prevBinor; // previous binormal
  5556. for (var i = 1; i < l; i++) {
  5557. // tangents
  5558. prev = this._getLastNonNullVector(i);
  5559. if (i < l - 1) {
  5560. cur = this._getFirstNonNullVector(i);
  5561. this._tangents[i] = prev.add(cur);
  5562. this._tangents[i].normalize();
  5563. }
  5564. this._distances[i] = this._distances[i - 1] + prev.length();
  5565. // normals and binormals
  5566. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5567. curTang = this._tangents[i];
  5568. prevBinor = this._binormals[i - 1];
  5569. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5570. if (!this._raw) {
  5571. this._normals[i].normalize();
  5572. }
  5573. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5574. if (!this._raw) {
  5575. this._binormals[i].normalize();
  5576. }
  5577. }
  5578. };
  5579. // private function getFirstNonNullVector(index)
  5580. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5581. Path3D.prototype._getFirstNonNullVector = function (index) {
  5582. var i = 1;
  5583. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5584. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5585. i++;
  5586. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5587. }
  5588. return nNVector;
  5589. };
  5590. // private function getLastNonNullVector(index)
  5591. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5592. Path3D.prototype._getLastNonNullVector = function (index) {
  5593. var i = 1;
  5594. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5595. while (nLVector.length() === 0 && index > i + 1) {
  5596. i++;
  5597. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5598. }
  5599. return nLVector;
  5600. };
  5601. // private function normalVector(v0, vt, va) :
  5602. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5603. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5604. Path3D.prototype._normalVector = function (v0, vt, va) {
  5605. var normal0;
  5606. var tgl = vt.length();
  5607. if (tgl === 0.0) {
  5608. tgl = 1.0;
  5609. }
  5610. if (va === undefined || va === null) {
  5611. var point;
  5612. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5613. point = new Vector3(0.0, -1.0, 0.0);
  5614. }
  5615. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5616. point = new Vector3(1.0, 0.0, 0.0);
  5617. }
  5618. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5619. point = new Vector3(0.0, 0.0, 1.0);
  5620. }
  5621. else {
  5622. point = Vector3.Zero();
  5623. }
  5624. normal0 = Vector3.Cross(vt, point);
  5625. }
  5626. else {
  5627. normal0 = Vector3.Cross(vt, va);
  5628. Vector3.CrossToRef(normal0, vt, normal0);
  5629. }
  5630. normal0.normalize();
  5631. return normal0;
  5632. };
  5633. return Path3D;
  5634. }());
  5635. BABYLON.Path3D = Path3D;
  5636. var Curve3 = /** @class */ (function () {
  5637. /**
  5638. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5639. * A Curve3 is designed from a series of successive Vector3.
  5640. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5641. */
  5642. function Curve3(points) {
  5643. this._length = 0.0;
  5644. this._points = points;
  5645. this._length = this._computeLength(points);
  5646. }
  5647. /**
  5648. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5649. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5650. * @param v1 (Vector3) the control point
  5651. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5652. * @param nbPoints (integer) the wanted number of points in the curve
  5653. */
  5654. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5655. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5656. var bez = new Array();
  5657. var equation = function (t, val0, val1, val2) {
  5658. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5659. return res;
  5660. };
  5661. for (var i = 0; i <= nbPoints; i++) {
  5662. 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)));
  5663. }
  5664. return new Curve3(bez);
  5665. };
  5666. /**
  5667. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5668. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5669. * @param v1 (Vector3) the first control point
  5670. * @param v2 (Vector3) the second control point
  5671. * @param v3 (Vector3) the end point of the Cubic Bezier
  5672. * @param nbPoints (integer) the wanted number of points in the curve
  5673. */
  5674. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5675. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5676. var bez = new Array();
  5677. var equation = function (t, val0, val1, val2, val3) {
  5678. 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;
  5679. return res;
  5680. };
  5681. for (var i = 0; i <= nbPoints; i++) {
  5682. 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)));
  5683. }
  5684. return new Curve3(bez);
  5685. };
  5686. /**
  5687. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5688. * @param p1 (Vector3) the origin point of the Hermite Spline
  5689. * @param t1 (Vector3) the tangent vector at the origin point
  5690. * @param p2 (Vector3) the end point of the Hermite Spline
  5691. * @param t2 (Vector3) the tangent vector at the end point
  5692. * @param nbPoints (integer) the wanted number of points in the curve
  5693. */
  5694. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5695. var hermite = new Array();
  5696. var step = 1.0 / nbPoints;
  5697. for (var i = 0; i <= nbPoints; i++) {
  5698. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5699. }
  5700. return new Curve3(hermite);
  5701. };
  5702. /**
  5703. * Returns a Curve3 object along a CatmullRom Spline curve :
  5704. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5705. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5706. */
  5707. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5708. var totalPoints = new Array();
  5709. totalPoints.push(points[0].clone());
  5710. Array.prototype.push.apply(totalPoints, points);
  5711. totalPoints.push(points[points.length - 1].clone());
  5712. var catmullRom = new Array();
  5713. var step = 1.0 / nbPoints;
  5714. var amount = 0.0;
  5715. for (var i = 0; i < totalPoints.length - 3; i++) {
  5716. amount = 0;
  5717. for (var c = 0; c < nbPoints; c++) {
  5718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5719. amount += step;
  5720. }
  5721. }
  5722. i--;
  5723. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5724. return new Curve3(catmullRom);
  5725. };
  5726. /**
  5727. * Returns the Curve3 stored array of successive Vector3
  5728. */
  5729. Curve3.prototype.getPoints = function () {
  5730. return this._points;
  5731. };
  5732. /**
  5733. * Returns the computed length (float) of the curve.
  5734. */
  5735. Curve3.prototype.length = function () {
  5736. return this._length;
  5737. };
  5738. /**
  5739. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5740. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5741. * curveA and curveB keep unchanged.
  5742. */
  5743. Curve3.prototype.continue = function (curve) {
  5744. var lastPoint = this._points[this._points.length - 1];
  5745. var continuedPoints = this._points.slice();
  5746. var curvePoints = curve.getPoints();
  5747. for (var i = 1; i < curvePoints.length; i++) {
  5748. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5749. }
  5750. var continuedCurve = new Curve3(continuedPoints);
  5751. return continuedCurve;
  5752. };
  5753. Curve3.prototype._computeLength = function (path) {
  5754. var l = 0;
  5755. for (var i = 1; i < path.length; i++) {
  5756. l += (path[i].subtract(path[i - 1])).length();
  5757. }
  5758. return l;
  5759. };
  5760. return Curve3;
  5761. }());
  5762. BABYLON.Curve3 = Curve3;
  5763. // Vertex formats
  5764. var PositionNormalVertex = /** @class */ (function () {
  5765. function PositionNormalVertex(position, normal) {
  5766. if (position === void 0) { position = Vector3.Zero(); }
  5767. if (normal === void 0) { normal = Vector3.Up(); }
  5768. this.position = position;
  5769. this.normal = normal;
  5770. }
  5771. PositionNormalVertex.prototype.clone = function () {
  5772. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5773. };
  5774. return PositionNormalVertex;
  5775. }());
  5776. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5777. var PositionNormalTextureVertex = /** @class */ (function () {
  5778. function PositionNormalTextureVertex(position, normal, uv) {
  5779. if (position === void 0) { position = Vector3.Zero(); }
  5780. if (normal === void 0) { normal = Vector3.Up(); }
  5781. if (uv === void 0) { uv = Vector2.Zero(); }
  5782. this.position = position;
  5783. this.normal = normal;
  5784. this.uv = uv;
  5785. }
  5786. PositionNormalTextureVertex.prototype.clone = function () {
  5787. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5788. };
  5789. return PositionNormalTextureVertex;
  5790. }());
  5791. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5792. // Temporary pre-allocated objects for engine internal use
  5793. // usage in any internal function :
  5794. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5795. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5796. var Tmp = /** @class */ (function () {
  5797. function Tmp() {
  5798. }
  5799. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5800. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5801. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5802. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5803. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5804. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5805. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5806. Matrix.Zero(), Matrix.Zero(),
  5807. Matrix.Zero(), Matrix.Zero(),
  5808. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5809. return Tmp;
  5810. }());
  5811. BABYLON.Tmp = Tmp;
  5812. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5813. var MathTmp = /** @class */ (function () {
  5814. function MathTmp() {
  5815. }
  5816. MathTmp.Vector3 = [Vector3.Zero()];
  5817. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5818. MathTmp.Quaternion = [Quaternion.Zero()];
  5819. return MathTmp;
  5820. }());
  5821. })(BABYLON || (BABYLON = {}));
  5822. //# sourceMappingURL=babylon.math.js.map
  5823. var BABYLON;
  5824. (function (BABYLON) {
  5825. var Scalar = /** @class */ (function () {
  5826. function Scalar() {
  5827. }
  5828. /**
  5829. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5830. */
  5831. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5832. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5833. var num = a - b;
  5834. return -epsilon <= num && num <= epsilon;
  5835. };
  5836. /**
  5837. * Returns a string : the upper case translation of the number i to hexadecimal.
  5838. */
  5839. Scalar.ToHex = function (i) {
  5840. var str = i.toString(16);
  5841. if (i <= 15) {
  5842. return ("0" + str).toUpperCase();
  5843. }
  5844. return str.toUpperCase();
  5845. };
  5846. /**
  5847. * Returns -1 if value is negative and +1 is value is positive.
  5848. * Returns the value itself if it's equal to zero.
  5849. */
  5850. Scalar.Sign = function (value) {
  5851. value = +value; // convert to a number
  5852. if (value === 0 || isNaN(value))
  5853. return value;
  5854. return value > 0 ? 1 : -1;
  5855. };
  5856. /**
  5857. * Returns the value itself if it's between min and max.
  5858. * Returns min if the value is lower than min.
  5859. * Returns max if the value is greater than max.
  5860. */
  5861. Scalar.Clamp = function (value, min, max) {
  5862. if (min === void 0) { min = 0; }
  5863. if (max === void 0) { max = 1; }
  5864. return Math.min(max, Math.max(min, value));
  5865. };
  5866. /**
  5867. * Returns the log2 of value.
  5868. */
  5869. Scalar.Log2 = function (value) {
  5870. return Math.log(value) * Math.LOG2E;
  5871. };
  5872. /**
  5873. * Loops the value, so that it is never larger than length and never smaller than 0.
  5874. *
  5875. * This is similar to the modulo operator but it works with floating point numbers.
  5876. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5877. * With t = 5 and length = 2.5, the result would be 0.0.
  5878. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5879. */
  5880. Scalar.Repeat = function (value, length) {
  5881. return value - Math.floor(value / length) * length;
  5882. };
  5883. /**
  5884. * Normalize the value between 0.0 and 1.0 using min and max values
  5885. */
  5886. Scalar.Normalize = function (value, min, max) {
  5887. return (value - min) / (max - min);
  5888. };
  5889. /**
  5890. * Denormalize the value from 0.0 and 1.0 using min and max values
  5891. */
  5892. Scalar.Denormalize = function (normalized, min, max) {
  5893. return (normalized * (max - min) + min);
  5894. };
  5895. /**
  5896. * Calculates the shortest difference between two given angles given in degrees.
  5897. */
  5898. Scalar.DeltaAngle = function (current, target) {
  5899. var num = Scalar.Repeat(target - current, 360.0);
  5900. if (num > 180.0) {
  5901. num -= 360.0;
  5902. }
  5903. return num;
  5904. };
  5905. /**
  5906. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5907. *
  5908. * The returned value will move back and forth between 0 and length
  5909. */
  5910. Scalar.PingPong = function (tx, length) {
  5911. var t = Scalar.Repeat(tx, length * 2.0);
  5912. return length - Math.abs(t - length);
  5913. };
  5914. /**
  5915. * Interpolates between min and max with smoothing at the limits.
  5916. *
  5917. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5918. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5919. */
  5920. Scalar.SmoothStep = function (from, to, tx) {
  5921. var t = Scalar.Clamp(tx);
  5922. t = -2.0 * t * t * t + 3.0 * t * t;
  5923. return to * t + from * (1.0 - t);
  5924. };
  5925. /**
  5926. * Moves a value current towards target.
  5927. *
  5928. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5929. * Negative values of maxDelta pushes the value away from target.
  5930. */
  5931. Scalar.MoveTowards = function (current, target, maxDelta) {
  5932. var result = 0;
  5933. if (Math.abs(target - current) <= maxDelta) {
  5934. result = target;
  5935. }
  5936. else {
  5937. result = current + Scalar.Sign(target - current) * maxDelta;
  5938. }
  5939. return result;
  5940. };
  5941. /**
  5942. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5943. *
  5944. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5945. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5946. */
  5947. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5948. var num = Scalar.DeltaAngle(current, target);
  5949. var result = 0;
  5950. if (-maxDelta < num && num < maxDelta) {
  5951. result = target;
  5952. }
  5953. else {
  5954. target = current + num;
  5955. result = Scalar.MoveTowards(current, target, maxDelta);
  5956. }
  5957. return result;
  5958. };
  5959. /**
  5960. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5961. */
  5962. Scalar.Lerp = function (start, end, amount) {
  5963. return start + ((end - start) * amount);
  5964. };
  5965. /**
  5966. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5967. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5968. */
  5969. Scalar.LerpAngle = function (start, end, amount) {
  5970. var num = Scalar.Repeat(end - start, 360.0);
  5971. if (num > 180.0) {
  5972. num -= 360.0;
  5973. }
  5974. return start + num * Scalar.Clamp(amount);
  5975. };
  5976. /**
  5977. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5978. */
  5979. Scalar.InverseLerp = function (a, b, value) {
  5980. var result = 0;
  5981. if (a != b) {
  5982. result = Scalar.Clamp((value - a) / (b - a));
  5983. }
  5984. else {
  5985. result = 0.0;
  5986. }
  5987. return result;
  5988. };
  5989. /**
  5990. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5991. */
  5992. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5993. var squared = amount * amount;
  5994. var cubed = amount * squared;
  5995. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5996. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5997. var part3 = (cubed - (2.0 * squared)) + amount;
  5998. var part4 = cubed - squared;
  5999. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6000. };
  6001. /**
  6002. * Returns a random float number between and min and max values
  6003. */
  6004. Scalar.RandomRange = function (min, max) {
  6005. if (min === max)
  6006. return min;
  6007. return ((Math.random() * (max - min)) + min);
  6008. };
  6009. /**
  6010. * This function returns percentage of a number in a given range.
  6011. *
  6012. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6013. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6014. */
  6015. Scalar.RangeToPercent = function (number, min, max) {
  6016. return ((number - min) / (max - min));
  6017. };
  6018. /**
  6019. * This function returns number that corresponds to the percentage in a given range.
  6020. *
  6021. * PercentToRange(0.34,0,100) will return 34.
  6022. */
  6023. Scalar.PercentToRange = function (percent, min, max) {
  6024. return ((max - min) * percent + min);
  6025. };
  6026. /**
  6027. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6028. * @param angle The angle to normalize in radian.
  6029. * @return The converted angle.
  6030. */
  6031. Scalar.NormalizeRadians = function (angle) {
  6032. // More precise but slower version kept for reference.
  6033. // angle = angle % Tools.TwoPi;
  6034. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6035. //if (angle > Math.PI) {
  6036. // angle -= Tools.TwoPi;
  6037. //}
  6038. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6039. return angle;
  6040. };
  6041. /**
  6042. * Two pi constants convenient for computation.
  6043. */
  6044. Scalar.TwoPi = Math.PI * 2;
  6045. return Scalar;
  6046. }());
  6047. BABYLON.Scalar = Scalar;
  6048. })(BABYLON || (BABYLON = {}));
  6049. //# sourceMappingURL=babylon.math.scalar.js.map
  6050. //# sourceMappingURL=babylon.mixins.js.map
  6051. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6052. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6053. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6054. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6055. //# sourceMappingURL=babylon.webgl2.js.map
  6056. var BABYLON;
  6057. (function (BABYLON) {
  6058. var __decoratorInitialStore = {};
  6059. var __mergedStore = {};
  6060. var _copySource = function (creationFunction, source, instanciate) {
  6061. var destination = creationFunction();
  6062. // Tags
  6063. if (BABYLON.Tags) {
  6064. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6065. }
  6066. var classStore = getMergedStore(destination);
  6067. // Properties
  6068. for (var property in classStore) {
  6069. var propertyDescriptor = classStore[property];
  6070. var sourceProperty = source[property];
  6071. var propertyType = propertyDescriptor.type;
  6072. if (sourceProperty !== undefined && sourceProperty !== null) {
  6073. switch (propertyType) {
  6074. case 0: // Value
  6075. case 6:// Mesh reference
  6076. destination[property] = sourceProperty;
  6077. break;
  6078. case 1:// Texture
  6079. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6080. break;
  6081. case 2: // Color3
  6082. case 3: // FresnelParameters
  6083. case 4: // Vector2
  6084. case 5: // Vector3
  6085. case 7: // Color Curves
  6086. case 10:// Quaternion
  6087. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6088. break;
  6089. }
  6090. }
  6091. }
  6092. return destination;
  6093. };
  6094. function getDirectStore(target) {
  6095. var classKey = target.getClassName();
  6096. if (!__decoratorInitialStore[classKey]) {
  6097. __decoratorInitialStore[classKey] = {};
  6098. }
  6099. return __decoratorInitialStore[classKey];
  6100. }
  6101. /**
  6102. * Return the list of properties flagged as serializable
  6103. * @param target: host object
  6104. */
  6105. function getMergedStore(target) {
  6106. var classKey = target.getClassName();
  6107. if (__mergedStore[classKey]) {
  6108. return __mergedStore[classKey];
  6109. }
  6110. __mergedStore[classKey] = {};
  6111. var store = __mergedStore[classKey];
  6112. var currentTarget = target;
  6113. var currentKey = classKey;
  6114. while (currentKey) {
  6115. var initialStore = __decoratorInitialStore[currentKey];
  6116. for (var property in initialStore) {
  6117. store[property] = initialStore[property];
  6118. }
  6119. var parent_1 = void 0;
  6120. var done = false;
  6121. do {
  6122. parent_1 = Object.getPrototypeOf(currentTarget);
  6123. if (!parent_1.getClassName) {
  6124. done = true;
  6125. break;
  6126. }
  6127. if (parent_1.getClassName() !== currentKey) {
  6128. break;
  6129. }
  6130. currentTarget = parent_1;
  6131. } while (parent_1);
  6132. if (done) {
  6133. break;
  6134. }
  6135. currentKey = parent_1.getClassName();
  6136. currentTarget = parent_1;
  6137. }
  6138. return store;
  6139. }
  6140. function generateSerializableMember(type, sourceName) {
  6141. return function (target, propertyKey) {
  6142. var classStore = getDirectStore(target);
  6143. if (!classStore[propertyKey]) {
  6144. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6145. }
  6146. };
  6147. }
  6148. function generateExpandMember(setCallback, targetKey) {
  6149. if (targetKey === void 0) { targetKey = null; }
  6150. return function (target, propertyKey) {
  6151. var key = targetKey || ("_" + propertyKey);
  6152. Object.defineProperty(target, propertyKey, {
  6153. get: function () {
  6154. return this[key];
  6155. },
  6156. set: function (value) {
  6157. if (this[key] === value) {
  6158. return;
  6159. }
  6160. this[key] = value;
  6161. target[setCallback].apply(this);
  6162. },
  6163. enumerable: true,
  6164. configurable: true
  6165. });
  6166. };
  6167. }
  6168. function expandToProperty(callback, targetKey) {
  6169. if (targetKey === void 0) { targetKey = null; }
  6170. return generateExpandMember(callback, targetKey);
  6171. }
  6172. BABYLON.expandToProperty = expandToProperty;
  6173. function serialize(sourceName) {
  6174. return generateSerializableMember(0, sourceName); // value member
  6175. }
  6176. BABYLON.serialize = serialize;
  6177. function serializeAsTexture(sourceName) {
  6178. return generateSerializableMember(1, sourceName); // texture member
  6179. }
  6180. BABYLON.serializeAsTexture = serializeAsTexture;
  6181. function serializeAsColor3(sourceName) {
  6182. return generateSerializableMember(2, sourceName); // color3 member
  6183. }
  6184. BABYLON.serializeAsColor3 = serializeAsColor3;
  6185. function serializeAsFresnelParameters(sourceName) {
  6186. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6187. }
  6188. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6189. function serializeAsVector2(sourceName) {
  6190. return generateSerializableMember(4, sourceName); // vector2 member
  6191. }
  6192. BABYLON.serializeAsVector2 = serializeAsVector2;
  6193. function serializeAsVector3(sourceName) {
  6194. return generateSerializableMember(5, sourceName); // vector3 member
  6195. }
  6196. BABYLON.serializeAsVector3 = serializeAsVector3;
  6197. function serializeAsMeshReference(sourceName) {
  6198. return generateSerializableMember(6, sourceName); // mesh reference member
  6199. }
  6200. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6201. function serializeAsColorCurves(sourceName) {
  6202. return generateSerializableMember(7, sourceName); // color curves
  6203. }
  6204. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6205. function serializeAsColor4(sourceName) {
  6206. return generateSerializableMember(8, sourceName); // color 4
  6207. }
  6208. BABYLON.serializeAsColor4 = serializeAsColor4;
  6209. function serializeAsImageProcessingConfiguration(sourceName) {
  6210. return generateSerializableMember(9, sourceName); // image processing
  6211. }
  6212. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6213. function serializeAsQuaternion(sourceName) {
  6214. return generateSerializableMember(10, sourceName); // quaternion member
  6215. }
  6216. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6217. var SerializationHelper = /** @class */ (function () {
  6218. function SerializationHelper() {
  6219. }
  6220. SerializationHelper.Serialize = function (entity, serializationObject) {
  6221. if (!serializationObject) {
  6222. serializationObject = {};
  6223. }
  6224. // Tags
  6225. if (BABYLON.Tags) {
  6226. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6227. }
  6228. var serializedProperties = getMergedStore(entity);
  6229. // Properties
  6230. for (var property in serializedProperties) {
  6231. var propertyDescriptor = serializedProperties[property];
  6232. var targetPropertyName = propertyDescriptor.sourceName || property;
  6233. var propertyType = propertyDescriptor.type;
  6234. var sourceProperty = entity[property];
  6235. if (sourceProperty !== undefined && sourceProperty !== null) {
  6236. switch (propertyType) {
  6237. case 0:// Value
  6238. serializationObject[targetPropertyName] = sourceProperty;
  6239. break;
  6240. case 1:// Texture
  6241. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6242. break;
  6243. case 2:// Color3
  6244. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6245. break;
  6246. case 3:// FresnelParameters
  6247. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6248. break;
  6249. case 4:// Vector2
  6250. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6251. break;
  6252. case 5:// Vector3
  6253. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6254. break;
  6255. case 6:// Mesh reference
  6256. serializationObject[targetPropertyName] = sourceProperty.id;
  6257. break;
  6258. case 7:// Color Curves
  6259. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6260. break;
  6261. case 8:// Color 4
  6262. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6263. break;
  6264. case 9:// Image Processing
  6265. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6266. break;
  6267. }
  6268. }
  6269. }
  6270. return serializationObject;
  6271. };
  6272. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6273. if (rootUrl === void 0) { rootUrl = null; }
  6274. var destination = creationFunction();
  6275. if (!rootUrl) {
  6276. rootUrl = "";
  6277. }
  6278. // Tags
  6279. if (BABYLON.Tags) {
  6280. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6281. }
  6282. var classStore = getMergedStore(destination);
  6283. // Properties
  6284. for (var property in classStore) {
  6285. var propertyDescriptor = classStore[property];
  6286. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6287. var propertyType = propertyDescriptor.type;
  6288. if (sourceProperty !== undefined && sourceProperty !== null) {
  6289. var dest = destination;
  6290. switch (propertyType) {
  6291. case 0:// Value
  6292. dest[property] = sourceProperty;
  6293. break;
  6294. case 1:// Texture
  6295. if (scene) {
  6296. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6297. }
  6298. break;
  6299. case 2:// Color3
  6300. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6301. break;
  6302. case 3:// FresnelParameters
  6303. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6304. break;
  6305. case 4:// Vector2
  6306. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6307. break;
  6308. case 5:// Vector3
  6309. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6310. break;
  6311. case 6:// Mesh reference
  6312. if (scene) {
  6313. dest[property] = scene.getLastMeshByID(sourceProperty);
  6314. }
  6315. break;
  6316. case 7:// Color Curves
  6317. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6318. break;
  6319. case 8:// Color 4
  6320. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6321. break;
  6322. case 9:// Image Processing
  6323. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6324. break;
  6325. }
  6326. }
  6327. }
  6328. return destination;
  6329. };
  6330. SerializationHelper.Clone = function (creationFunction, source) {
  6331. return _copySource(creationFunction, source, false);
  6332. };
  6333. SerializationHelper.Instanciate = function (creationFunction, source) {
  6334. return _copySource(creationFunction, source, true);
  6335. };
  6336. return SerializationHelper;
  6337. }());
  6338. BABYLON.SerializationHelper = SerializationHelper;
  6339. })(BABYLON || (BABYLON = {}));
  6340. //# sourceMappingURL=babylon.decorators.js.map
  6341. var BABYLON;
  6342. (function (BABYLON) {
  6343. /**
  6344. * A class serves as a medium between the observable and its observers
  6345. */
  6346. var EventState = /** @class */ (function () {
  6347. /**
  6348. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6349. */
  6350. function EventState(mask, skipNextObservers, target, currentTarget) {
  6351. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6352. this.initalize(mask, skipNextObservers, target, currentTarget);
  6353. }
  6354. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6355. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6356. this.mask = mask;
  6357. this.skipNextObservers = skipNextObservers;
  6358. this.target = target;
  6359. this.currentTarget = currentTarget;
  6360. return this;
  6361. };
  6362. return EventState;
  6363. }());
  6364. BABYLON.EventState = EventState;
  6365. /**
  6366. * Represent an Observer registered to a given Observable object.
  6367. */
  6368. var Observer = /** @class */ (function () {
  6369. function Observer(callback, mask, scope) {
  6370. if (scope === void 0) { scope = null; }
  6371. this.callback = callback;
  6372. this.mask = mask;
  6373. this.scope = scope;
  6374. }
  6375. return Observer;
  6376. }());
  6377. BABYLON.Observer = Observer;
  6378. /**
  6379. * Represent a list of observers registered to multiple Observables object.
  6380. */
  6381. var MultiObserver = /** @class */ (function () {
  6382. function MultiObserver() {
  6383. }
  6384. MultiObserver.prototype.dispose = function () {
  6385. if (this._observers && this._observables) {
  6386. for (var index = 0; index < this._observers.length; index++) {
  6387. this._observables[index].remove(this._observers[index]);
  6388. }
  6389. }
  6390. this._observers = null;
  6391. this._observables = null;
  6392. };
  6393. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6394. if (mask === void 0) { mask = -1; }
  6395. if (scope === void 0) { scope = null; }
  6396. var result = new MultiObserver();
  6397. result._observers = new Array();
  6398. result._observables = observables;
  6399. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6400. var observable = observables_1[_i];
  6401. var observer = observable.add(callback, mask, false, scope);
  6402. if (observer) {
  6403. result._observers.push(observer);
  6404. }
  6405. }
  6406. return result;
  6407. };
  6408. return MultiObserver;
  6409. }());
  6410. BABYLON.MultiObserver = MultiObserver;
  6411. /**
  6412. * The Observable class is a simple implementation of the Observable pattern.
  6413. * 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.
  6414. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6415. * 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).
  6416. * 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.
  6417. */
  6418. var Observable = /** @class */ (function () {
  6419. function Observable(onObserverAdded) {
  6420. this._observers = new Array();
  6421. this._eventState = new EventState(0);
  6422. if (onObserverAdded) {
  6423. this._onObserverAdded = onObserverAdded;
  6424. }
  6425. }
  6426. /**
  6427. * Create a new Observer with the specified callback
  6428. * @param callback the callback that will be executed for that Observer
  6429. * @param mask the mask used to filter observers
  6430. * @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.
  6431. * @param scope optional scope for the callback to be called from
  6432. */
  6433. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6434. if (mask === void 0) { mask = -1; }
  6435. if (insertFirst === void 0) { insertFirst = false; }
  6436. if (scope === void 0) { scope = null; }
  6437. if (!callback) {
  6438. return null;
  6439. }
  6440. var observer = new Observer(callback, mask, scope);
  6441. if (insertFirst) {
  6442. this._observers.unshift(observer);
  6443. }
  6444. else {
  6445. this._observers.push(observer);
  6446. }
  6447. if (this._onObserverAdded) {
  6448. this._onObserverAdded(observer);
  6449. }
  6450. return observer;
  6451. };
  6452. /**
  6453. * Remove an Observer from the Observable object
  6454. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6455. */
  6456. Observable.prototype.remove = function (observer) {
  6457. if (!observer) {
  6458. return false;
  6459. }
  6460. var index = this._observers.indexOf(observer);
  6461. if (index !== -1) {
  6462. this._observers.splice(index, 1);
  6463. return true;
  6464. }
  6465. return false;
  6466. };
  6467. /**
  6468. * Remove a callback from the Observable object
  6469. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6470. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6471. */
  6472. Observable.prototype.removeCallback = function (callback, scope) {
  6473. for (var index = 0; index < this._observers.length; index++) {
  6474. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6475. this._observers.splice(index, 1);
  6476. return true;
  6477. }
  6478. }
  6479. return false;
  6480. };
  6481. /**
  6482. * Notify all Observers by calling their respective callback with the given data
  6483. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6484. * @param eventData
  6485. * @param mask
  6486. */
  6487. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6488. if (mask === void 0) { mask = -1; }
  6489. if (!this._observers.length) {
  6490. return true;
  6491. }
  6492. var state = this._eventState;
  6493. state.mask = mask;
  6494. state.target = target;
  6495. state.currentTarget = currentTarget;
  6496. state.skipNextObservers = false;
  6497. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6498. var obs = _a[_i];
  6499. if (obs.mask & mask) {
  6500. if (obs.scope) {
  6501. obs.callback.apply(obs.scope, [eventData, state]);
  6502. }
  6503. else {
  6504. obs.callback(eventData, state);
  6505. }
  6506. }
  6507. if (state.skipNextObservers) {
  6508. return false;
  6509. }
  6510. }
  6511. return true;
  6512. };
  6513. /**
  6514. * Notify a specific observer
  6515. * @param eventData
  6516. * @param mask
  6517. */
  6518. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6519. if (mask === void 0) { mask = -1; }
  6520. var state = this._eventState;
  6521. state.mask = mask;
  6522. state.skipNextObservers = false;
  6523. observer.callback(eventData, state);
  6524. };
  6525. /**
  6526. * return true is the Observable has at least one Observer registered
  6527. */
  6528. Observable.prototype.hasObservers = function () {
  6529. return this._observers.length > 0;
  6530. };
  6531. /**
  6532. * Clear the list of observers
  6533. */
  6534. Observable.prototype.clear = function () {
  6535. this._observers = new Array();
  6536. this._onObserverAdded = null;
  6537. };
  6538. /**
  6539. * Clone the current observable
  6540. */
  6541. Observable.prototype.clone = function () {
  6542. var result = new Observable();
  6543. result._observers = this._observers.slice(0);
  6544. return result;
  6545. };
  6546. /**
  6547. * Does this observable handles observer registered with a given mask
  6548. * @param {number} trigger - the mask to be tested
  6549. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6550. **/
  6551. Observable.prototype.hasSpecificMask = function (mask) {
  6552. if (mask === void 0) { mask = -1; }
  6553. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6554. var obs = _a[_i];
  6555. if (obs.mask & mask || obs.mask === mask) {
  6556. return true;
  6557. }
  6558. }
  6559. return false;
  6560. };
  6561. return Observable;
  6562. }());
  6563. BABYLON.Observable = Observable;
  6564. })(BABYLON || (BABYLON = {}));
  6565. //# sourceMappingURL=babylon.observable.js.map
  6566. var BABYLON;
  6567. (function (BABYLON) {
  6568. var SmartArray = /** @class */ (function () {
  6569. function SmartArray(capacity) {
  6570. this.length = 0;
  6571. this.data = new Array(capacity);
  6572. this._id = SmartArray._GlobalId++;
  6573. }
  6574. SmartArray.prototype.push = function (value) {
  6575. this.data[this.length++] = value;
  6576. if (this.length > this.data.length) {
  6577. this.data.length *= 2;
  6578. }
  6579. };
  6580. SmartArray.prototype.forEach = function (func) {
  6581. for (var index = 0; index < this.length; index++) {
  6582. func(this.data[index]);
  6583. }
  6584. };
  6585. SmartArray.prototype.sort = function (compareFn) {
  6586. this.data.sort(compareFn);
  6587. };
  6588. SmartArray.prototype.reset = function () {
  6589. this.length = 0;
  6590. };
  6591. SmartArray.prototype.dispose = function () {
  6592. this.reset();
  6593. if (this.data) {
  6594. this.data.length = 0;
  6595. this.data = [];
  6596. }
  6597. };
  6598. SmartArray.prototype.concat = function (array) {
  6599. if (array.length === 0) {
  6600. return;
  6601. }
  6602. if (this.length + array.length > this.data.length) {
  6603. this.data.length = (this.length + array.length) * 2;
  6604. }
  6605. for (var index = 0; index < array.length; index++) {
  6606. this.data[this.length++] = (array.data || array)[index];
  6607. }
  6608. };
  6609. SmartArray.prototype.indexOf = function (value) {
  6610. var position = this.data.indexOf(value);
  6611. if (position >= this.length) {
  6612. return -1;
  6613. }
  6614. return position;
  6615. };
  6616. SmartArray.prototype.contains = function (value) {
  6617. return this.data.indexOf(value) !== -1;
  6618. };
  6619. // Statics
  6620. SmartArray._GlobalId = 0;
  6621. return SmartArray;
  6622. }());
  6623. BABYLON.SmartArray = SmartArray;
  6624. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6625. __extends(SmartArrayNoDuplicate, _super);
  6626. function SmartArrayNoDuplicate() {
  6627. var _this = _super !== null && _super.apply(this, arguments) || this;
  6628. _this._duplicateId = 0;
  6629. return _this;
  6630. }
  6631. SmartArrayNoDuplicate.prototype.push = function (value) {
  6632. _super.prototype.push.call(this, value);
  6633. if (!value.__smartArrayFlags) {
  6634. value.__smartArrayFlags = {};
  6635. }
  6636. value.__smartArrayFlags[this._id] = this._duplicateId;
  6637. };
  6638. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6639. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6640. return false;
  6641. }
  6642. this.push(value);
  6643. return true;
  6644. };
  6645. SmartArrayNoDuplicate.prototype.reset = function () {
  6646. _super.prototype.reset.call(this);
  6647. this._duplicateId++;
  6648. };
  6649. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6650. if (array.length === 0) {
  6651. return;
  6652. }
  6653. if (this.length + array.length > this.data.length) {
  6654. this.data.length = (this.length + array.length) * 2;
  6655. }
  6656. for (var index = 0; index < array.length; index++) {
  6657. var item = (array.data || array)[index];
  6658. this.pushNoDuplicate(item);
  6659. }
  6660. };
  6661. return SmartArrayNoDuplicate;
  6662. }(SmartArray));
  6663. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6664. })(BABYLON || (BABYLON = {}));
  6665. //# sourceMappingURL=babylon.smartArray.js.map
  6666. var BABYLON;
  6667. (function (BABYLON) {
  6668. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6669. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6670. var LoadFileError = /** @class */ (function (_super) {
  6671. __extends(LoadFileError, _super);
  6672. function LoadFileError(message, request) {
  6673. var _this = _super.call(this, message) || this;
  6674. _this.request = request;
  6675. _this.name = "LoadFileError";
  6676. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6677. return _this;
  6678. }
  6679. // Polyfill for Object.setPrototypeOf if necessary.
  6680. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6681. return LoadFileError;
  6682. }(Error));
  6683. BABYLON.LoadFileError = LoadFileError;
  6684. var RetryStrategy = /** @class */ (function () {
  6685. function RetryStrategy() {
  6686. }
  6687. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6688. if (maxRetries === void 0) { maxRetries = 3; }
  6689. if (baseInterval === void 0) { baseInterval = 500; }
  6690. return function (url, request, retryIndex) {
  6691. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6692. return -1;
  6693. }
  6694. return Math.pow(2, retryIndex) * baseInterval;
  6695. };
  6696. };
  6697. return RetryStrategy;
  6698. }());
  6699. BABYLON.RetryStrategy = RetryStrategy;
  6700. // Screenshots
  6701. var screenshotCanvas;
  6702. var cloneValue = function (source, destinationObject) {
  6703. if (!source)
  6704. return null;
  6705. if (source instanceof BABYLON.Mesh) {
  6706. return null;
  6707. }
  6708. if (source instanceof BABYLON.SubMesh) {
  6709. return source.clone(destinationObject);
  6710. }
  6711. else if (source.clone) {
  6712. return source.clone();
  6713. }
  6714. return null;
  6715. };
  6716. var Tools = /** @class */ (function () {
  6717. function Tools() {
  6718. }
  6719. /**
  6720. * Interpolates between a and b via alpha
  6721. * @param a The lower value (returned when alpha = 0)
  6722. * @param b The upper value (returned when alpha = 1)
  6723. * @param alpha The interpolation-factor
  6724. * @return The mixed value
  6725. */
  6726. Tools.Mix = function (a, b, alpha) {
  6727. return a * (1 - alpha) + b * alpha;
  6728. };
  6729. Tools.Instantiate = function (className) {
  6730. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6731. return Tools.RegisteredExternalClasses[className];
  6732. }
  6733. var arr = className.split(".");
  6734. var fn = (window || this);
  6735. for (var i = 0, len = arr.length; i < len; i++) {
  6736. fn = fn[arr[i]];
  6737. }
  6738. if (typeof fn !== "function") {
  6739. return null;
  6740. }
  6741. return fn;
  6742. };
  6743. /**
  6744. * Provides a slice function that will work even on IE
  6745. * @param data defines the array to slice
  6746. * @returns the new sliced array
  6747. */
  6748. Tools.Slice = function (data) {
  6749. if (data.slice) {
  6750. return data.slice();
  6751. }
  6752. return Array.prototype.slice.call(data);
  6753. };
  6754. Tools.SetImmediate = function (action) {
  6755. if (window.setImmediate) {
  6756. window.setImmediate(action);
  6757. }
  6758. else {
  6759. setTimeout(action, 1);
  6760. }
  6761. };
  6762. Tools.IsExponentOfTwo = function (value) {
  6763. var count = 1;
  6764. do {
  6765. count *= 2;
  6766. } while (count < value);
  6767. return count === value;
  6768. };
  6769. /**
  6770. * Find the next highest power of two.
  6771. * @param x Number to start search from.
  6772. * @return Next highest power of two.
  6773. */
  6774. Tools.CeilingPOT = function (x) {
  6775. x--;
  6776. x |= x >> 1;
  6777. x |= x >> 2;
  6778. x |= x >> 4;
  6779. x |= x >> 8;
  6780. x |= x >> 16;
  6781. x++;
  6782. return x;
  6783. };
  6784. /**
  6785. * Find the next lowest power of two.
  6786. * @param x Number to start search from.
  6787. * @return Next lowest power of two.
  6788. */
  6789. Tools.FloorPOT = function (x) {
  6790. x = x | (x >> 1);
  6791. x = x | (x >> 2);
  6792. x = x | (x >> 4);
  6793. x = x | (x >> 8);
  6794. x = x | (x >> 16);
  6795. return x - (x >> 1);
  6796. };
  6797. /**
  6798. * Find the nearest power of two.
  6799. * @param x Number to start search from.
  6800. * @return Next nearest power of two.
  6801. */
  6802. Tools.NearestPOT = function (x) {
  6803. var c = Tools.CeilingPOT(x);
  6804. var f = Tools.FloorPOT(x);
  6805. return (c - x) > (x - f) ? f : c;
  6806. };
  6807. Tools.GetExponentOfTwo = function (value, max, mode) {
  6808. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6809. var pot;
  6810. switch (mode) {
  6811. case BABYLON.Engine.SCALEMODE_FLOOR:
  6812. pot = Tools.FloorPOT(value);
  6813. break;
  6814. case BABYLON.Engine.SCALEMODE_NEAREST:
  6815. pot = Tools.NearestPOT(value);
  6816. break;
  6817. case BABYLON.Engine.SCALEMODE_CEILING:
  6818. default:
  6819. pot = Tools.CeilingPOT(value);
  6820. break;
  6821. }
  6822. return Math.min(pot, max);
  6823. };
  6824. Tools.GetFilename = function (path) {
  6825. var index = path.lastIndexOf("/");
  6826. if (index < 0)
  6827. return path;
  6828. return path.substring(index + 1);
  6829. };
  6830. Tools.GetFolderPath = function (uri) {
  6831. var index = uri.lastIndexOf("/");
  6832. if (index < 0)
  6833. return "";
  6834. return uri.substring(0, index + 1);
  6835. };
  6836. Tools.GetDOMTextContent = function (element) {
  6837. var result = "";
  6838. var child = element.firstChild;
  6839. while (child) {
  6840. if (child.nodeType === 3) {
  6841. result += child.textContent;
  6842. }
  6843. child = child.nextSibling;
  6844. }
  6845. return result;
  6846. };
  6847. Tools.ToDegrees = function (angle) {
  6848. return angle * 180 / Math.PI;
  6849. };
  6850. Tools.ToRadians = function (angle) {
  6851. return angle * Math.PI / 180;
  6852. };
  6853. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6854. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6855. var output = "";
  6856. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6857. var i = 0;
  6858. var bytes = new Uint8Array(buffer);
  6859. while (i < bytes.length) {
  6860. chr1 = bytes[i++];
  6861. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6862. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6863. enc1 = chr1 >> 2;
  6864. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6865. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6866. enc4 = chr3 & 63;
  6867. if (isNaN(chr2)) {
  6868. enc3 = enc4 = 64;
  6869. }
  6870. else if (isNaN(chr3)) {
  6871. enc4 = 64;
  6872. }
  6873. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6874. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6875. }
  6876. return "data:image/png;base64," + output;
  6877. };
  6878. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6879. if (bias === void 0) { bias = null; }
  6880. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6881. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6882. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6883. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6884. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6885. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6886. }
  6887. if (bias) {
  6888. minimum.x -= minimum.x * bias.x + bias.y;
  6889. minimum.y -= minimum.y * bias.x + bias.y;
  6890. minimum.z -= minimum.z * bias.x + bias.y;
  6891. maximum.x += maximum.x * bias.x + bias.y;
  6892. maximum.y += maximum.y * bias.x + bias.y;
  6893. maximum.z += maximum.z * bias.x + bias.y;
  6894. }
  6895. return {
  6896. minimum: minimum,
  6897. maximum: maximum
  6898. };
  6899. };
  6900. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6901. if (bias === void 0) { bias = null; }
  6902. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6903. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6904. if (!stride) {
  6905. stride = 3;
  6906. }
  6907. for (var index = start; index < start + count; index++) {
  6908. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6909. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6910. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6911. }
  6912. if (bias) {
  6913. minimum.x -= minimum.x * bias.x + bias.y;
  6914. minimum.y -= minimum.y * bias.x + bias.y;
  6915. minimum.z -= minimum.z * bias.x + bias.y;
  6916. maximum.x += maximum.x * bias.x + bias.y;
  6917. maximum.y += maximum.y * bias.x + bias.y;
  6918. maximum.z += maximum.z * bias.x + bias.y;
  6919. }
  6920. return {
  6921. minimum: minimum,
  6922. maximum: maximum
  6923. };
  6924. };
  6925. Tools.Vector2ArrayFeeder = function (array) {
  6926. return function (index) {
  6927. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6928. var length = isFloatArray ? array.length / 2 : array.length;
  6929. if (index >= length) {
  6930. return null;
  6931. }
  6932. if (isFloatArray) {
  6933. var fa = array;
  6934. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6935. }
  6936. var a = array;
  6937. return a[index];
  6938. };
  6939. };
  6940. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6941. if (bias === void 0) { bias = null; }
  6942. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6943. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6944. var i = 0;
  6945. var cur = feeder(i++);
  6946. while (cur) {
  6947. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6948. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6949. cur = feeder(i++);
  6950. }
  6951. if (bias) {
  6952. minimum.x -= minimum.x * bias.x + bias.y;
  6953. minimum.y -= minimum.y * bias.x + bias.y;
  6954. maximum.x += maximum.x * bias.x + bias.y;
  6955. maximum.y += maximum.y * bias.x + bias.y;
  6956. }
  6957. return {
  6958. minimum: minimum,
  6959. maximum: maximum
  6960. };
  6961. };
  6962. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6963. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6964. return null;
  6965. return Array.isArray(obj) ? obj : [obj];
  6966. };
  6967. // Misc.
  6968. Tools.GetPointerPrefix = function () {
  6969. var eventPrefix = "pointer";
  6970. // Check if pointer events are supported
  6971. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6972. eventPrefix = "mouse";
  6973. }
  6974. return eventPrefix;
  6975. };
  6976. /**
  6977. * @param func - the function to be called
  6978. * @param requester - the object that will request the next frame. Falls back to window.
  6979. */
  6980. Tools.QueueNewFrame = function (func, requester) {
  6981. if (!Tools.IsWindowObjectExist()) {
  6982. return setTimeout(func, 16);
  6983. }
  6984. if (!requester) {
  6985. requester = window;
  6986. }
  6987. if (requester.requestAnimationFrame) {
  6988. return requester.requestAnimationFrame(func);
  6989. }
  6990. else if (requester.msRequestAnimationFrame) {
  6991. return requester.msRequestAnimationFrame(func);
  6992. }
  6993. else if (requester.webkitRequestAnimationFrame) {
  6994. return requester.webkitRequestAnimationFrame(func);
  6995. }
  6996. else if (requester.mozRequestAnimationFrame) {
  6997. return requester.mozRequestAnimationFrame(func);
  6998. }
  6999. else if (requester.oRequestAnimationFrame) {
  7000. return requester.oRequestAnimationFrame(func);
  7001. }
  7002. else {
  7003. return window.setTimeout(func, 16);
  7004. }
  7005. };
  7006. Tools.RequestFullscreen = function (element) {
  7007. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7008. if (!requestFunction)
  7009. return;
  7010. requestFunction.call(element);
  7011. };
  7012. Tools.ExitFullscreen = function () {
  7013. if (document.exitFullscreen) {
  7014. document.exitFullscreen();
  7015. }
  7016. else if (document.mozCancelFullScreen) {
  7017. document.mozCancelFullScreen();
  7018. }
  7019. else if (document.webkitCancelFullScreen) {
  7020. document.webkitCancelFullScreen();
  7021. }
  7022. else if (document.msCancelFullScreen) {
  7023. document.msCancelFullScreen();
  7024. }
  7025. };
  7026. Tools.SetCorsBehavior = function (url, element) {
  7027. if (url && url.indexOf("data:") === 0) {
  7028. return;
  7029. }
  7030. if (Tools.CorsBehavior) {
  7031. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7032. element.crossOrigin = Tools.CorsBehavior;
  7033. }
  7034. else {
  7035. var result = Tools.CorsBehavior(url);
  7036. if (result) {
  7037. element.crossOrigin = result;
  7038. }
  7039. }
  7040. }
  7041. };
  7042. // External files
  7043. Tools.CleanUrl = function (url) {
  7044. url = url.replace(/#/mg, "%23");
  7045. return url;
  7046. };
  7047. Tools.LoadImage = function (url, onLoad, onError, database) {
  7048. if (url instanceof ArrayBuffer) {
  7049. url = Tools.EncodeArrayBufferTobase64(url);
  7050. }
  7051. url = Tools.CleanUrl(url);
  7052. url = Tools.PreprocessUrl(url);
  7053. var img = new Image();
  7054. Tools.SetCorsBehavior(url, img);
  7055. img.onload = function () {
  7056. onLoad(img);
  7057. };
  7058. img.onerror = function (err) {
  7059. Tools.Error("Error while trying to load image: " + url);
  7060. if (onError) {
  7061. onError("Error while trying to load image: " + url, err);
  7062. }
  7063. };
  7064. var noIndexedDB = function () {
  7065. img.src = url;
  7066. };
  7067. var loadFromIndexedDB = function () {
  7068. if (database) {
  7069. database.loadImageFromDB(url, img);
  7070. }
  7071. };
  7072. //ANY database to do!
  7073. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7074. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7075. }
  7076. else {
  7077. if (url.indexOf("file:") !== -1) {
  7078. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7079. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7080. try {
  7081. var blobURL;
  7082. try {
  7083. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7084. }
  7085. catch (ex) {
  7086. // Chrome doesn't support oneTimeOnly parameter
  7087. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7088. }
  7089. img.src = blobURL;
  7090. }
  7091. catch (e) {
  7092. img.src = "";
  7093. }
  7094. return img;
  7095. }
  7096. }
  7097. noIndexedDB();
  7098. }
  7099. return img;
  7100. };
  7101. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7102. url = Tools.CleanUrl(url);
  7103. url = Tools.PreprocessUrl(url);
  7104. // If file and file input are set
  7105. if (url.indexOf("file:") !== -1) {
  7106. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7107. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7108. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7109. }
  7110. }
  7111. var loadUrl = Tools.BaseUrl + url;
  7112. var aborted = false;
  7113. var fileRequest = {
  7114. onCompleteObservable: new BABYLON.Observable(),
  7115. abort: function () { return aborted = true; },
  7116. };
  7117. var requestFile = function () {
  7118. var request = new XMLHttpRequest();
  7119. var retryHandle = null;
  7120. fileRequest.abort = function () {
  7121. aborted = true;
  7122. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7123. request.abort();
  7124. }
  7125. if (retryHandle !== null) {
  7126. clearTimeout(retryHandle);
  7127. retryHandle = null;
  7128. }
  7129. };
  7130. var retryLoop = function (retryIndex) {
  7131. request.open('GET', loadUrl, true);
  7132. if (useArrayBuffer) {
  7133. request.responseType = "arraybuffer";
  7134. }
  7135. if (onProgress) {
  7136. request.addEventListener("progress", onProgress);
  7137. }
  7138. var onLoadEnd = function () {
  7139. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7140. };
  7141. request.addEventListener("loadend", onLoadEnd);
  7142. var onReadyStateChange = function () {
  7143. if (aborted) {
  7144. return;
  7145. }
  7146. // In case of undefined state in some browsers.
  7147. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7148. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7149. request.removeEventListener("readystatechange", onReadyStateChange);
  7150. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7151. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7152. return;
  7153. }
  7154. var retryStrategy = Tools.DefaultRetryStrategy;
  7155. if (retryStrategy) {
  7156. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7157. if (waitTime !== -1) {
  7158. // Prevent the request from completing for retry.
  7159. request.removeEventListener("loadend", onLoadEnd);
  7160. request = new XMLHttpRequest();
  7161. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7162. return;
  7163. }
  7164. }
  7165. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7166. if (onError) {
  7167. onError(request, e);
  7168. }
  7169. else {
  7170. throw e;
  7171. }
  7172. }
  7173. };
  7174. request.addEventListener("readystatechange", onReadyStateChange);
  7175. request.send();
  7176. };
  7177. retryLoop(0);
  7178. };
  7179. // Caching all files
  7180. if (database && database.enableSceneOffline) {
  7181. var noIndexedDB_1 = function () {
  7182. if (!aborted) {
  7183. requestFile();
  7184. }
  7185. };
  7186. var loadFromIndexedDB = function () {
  7187. // TODO: database needs to support aborting and should return a IFileRequest
  7188. if (aborted) {
  7189. return;
  7190. }
  7191. if (database) {
  7192. database.loadFileFromDB(url, function (data) {
  7193. if (!aborted) {
  7194. onSuccess(data);
  7195. }
  7196. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7197. }, onProgress ? function (event) {
  7198. if (!aborted) {
  7199. onProgress(event);
  7200. }
  7201. } : undefined, noIndexedDB_1, useArrayBuffer);
  7202. }
  7203. };
  7204. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7205. }
  7206. else {
  7207. requestFile();
  7208. }
  7209. return fileRequest;
  7210. };
  7211. /**
  7212. * Load a script (identified by an url). When the url returns, the
  7213. * content of this file is added into a new script element, attached to the DOM (body element)
  7214. */
  7215. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7216. var head = document.getElementsByTagName('head')[0];
  7217. var script = document.createElement('script');
  7218. script.type = 'text/javascript';
  7219. script.src = scriptUrl;
  7220. script.onload = function () {
  7221. if (onSuccess) {
  7222. onSuccess();
  7223. }
  7224. };
  7225. script.onerror = function (e) {
  7226. if (onError) {
  7227. onError("Unable to load script", e);
  7228. }
  7229. };
  7230. head.appendChild(script);
  7231. };
  7232. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7233. var reader = new FileReader();
  7234. var request = {
  7235. onCompleteObservable: new BABYLON.Observable(),
  7236. abort: function () { return reader.abort(); },
  7237. };
  7238. reader.onloadend = function (e) {
  7239. request.onCompleteObservable.notifyObservers(request);
  7240. };
  7241. reader.onload = function (e) {
  7242. //target doesn't have result from ts 1.3
  7243. callback(e.target['result']);
  7244. };
  7245. reader.onprogress = progressCallback;
  7246. reader.readAsDataURL(fileToLoad);
  7247. return request;
  7248. };
  7249. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7250. var reader = new FileReader();
  7251. var request = {
  7252. onCompleteObservable: new BABYLON.Observable(),
  7253. abort: function () { return reader.abort(); },
  7254. };
  7255. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7256. reader.onerror = function (e) {
  7257. Tools.Log("Error while reading file: " + fileToLoad.name);
  7258. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7259. };
  7260. reader.onload = function (e) {
  7261. //target doesn't have result from ts 1.3
  7262. callback(e.target['result']);
  7263. };
  7264. if (progressCallBack) {
  7265. reader.onprogress = progressCallBack;
  7266. }
  7267. if (!useArrayBuffer) {
  7268. // Asynchronous read
  7269. reader.readAsText(fileToLoad);
  7270. }
  7271. else {
  7272. reader.readAsArrayBuffer(fileToLoad);
  7273. }
  7274. return request;
  7275. };
  7276. //returns a downloadable url to a file content.
  7277. Tools.FileAsURL = function (content) {
  7278. var fileBlob = new Blob([content]);
  7279. var url = window.URL || window.webkitURL;
  7280. var link = url.createObjectURL(fileBlob);
  7281. return link;
  7282. };
  7283. // Misc.
  7284. Tools.Format = function (value, decimals) {
  7285. if (decimals === void 0) { decimals = 2; }
  7286. return value.toFixed(decimals);
  7287. };
  7288. Tools.CheckExtends = function (v, min, max) {
  7289. if (v.x < min.x)
  7290. min.x = v.x;
  7291. if (v.y < min.y)
  7292. min.y = v.y;
  7293. if (v.z < min.z)
  7294. min.z = v.z;
  7295. if (v.x > max.x)
  7296. max.x = v.x;
  7297. if (v.y > max.y)
  7298. max.y = v.y;
  7299. if (v.z > max.z)
  7300. max.z = v.z;
  7301. };
  7302. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7303. for (var prop in source) {
  7304. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7305. continue;
  7306. }
  7307. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7308. continue;
  7309. }
  7310. var sourceValue = source[prop];
  7311. var typeOfSourceValue = typeof sourceValue;
  7312. if (typeOfSourceValue === "function") {
  7313. continue;
  7314. }
  7315. if (typeOfSourceValue === "object") {
  7316. if (sourceValue instanceof Array) {
  7317. destination[prop] = [];
  7318. if (sourceValue.length > 0) {
  7319. if (typeof sourceValue[0] == "object") {
  7320. for (var index = 0; index < sourceValue.length; index++) {
  7321. var clonedValue = cloneValue(sourceValue[index], destination);
  7322. if (destination[prop].indexOf(clonedValue) === -1) {
  7323. destination[prop].push(clonedValue);
  7324. }
  7325. }
  7326. }
  7327. else {
  7328. destination[prop] = sourceValue.slice(0);
  7329. }
  7330. }
  7331. }
  7332. else {
  7333. destination[prop] = cloneValue(sourceValue, destination);
  7334. }
  7335. }
  7336. else {
  7337. destination[prop] = sourceValue;
  7338. }
  7339. }
  7340. };
  7341. Tools.IsEmpty = function (obj) {
  7342. for (var i in obj) {
  7343. if (obj.hasOwnProperty(i)) {
  7344. return false;
  7345. }
  7346. }
  7347. return true;
  7348. };
  7349. Tools.RegisterTopRootEvents = function (events) {
  7350. for (var index = 0; index < events.length; index++) {
  7351. var event = events[index];
  7352. window.addEventListener(event.name, event.handler, false);
  7353. try {
  7354. if (window.parent) {
  7355. window.parent.addEventListener(event.name, event.handler, false);
  7356. }
  7357. }
  7358. catch (e) {
  7359. // Silently fails...
  7360. }
  7361. }
  7362. };
  7363. Tools.UnregisterTopRootEvents = function (events) {
  7364. for (var index = 0; index < events.length; index++) {
  7365. var event = events[index];
  7366. window.removeEventListener(event.name, event.handler);
  7367. try {
  7368. if (window.parent) {
  7369. window.parent.removeEventListener(event.name, event.handler);
  7370. }
  7371. }
  7372. catch (e) {
  7373. // Silently fails...
  7374. }
  7375. }
  7376. };
  7377. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7378. if (mimeType === void 0) { mimeType = "image/png"; }
  7379. // Read the contents of the framebuffer
  7380. var numberOfChannelsByLine = width * 4;
  7381. var halfHeight = height / 2;
  7382. //Reading datas from WebGL
  7383. var data = engine.readPixels(0, 0, width, height);
  7384. //To flip image on Y axis.
  7385. for (var i = 0; i < halfHeight; i++) {
  7386. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7387. var currentCell = j + i * numberOfChannelsByLine;
  7388. var targetLine = height - i - 1;
  7389. var targetCell = j + targetLine * numberOfChannelsByLine;
  7390. var temp = data[currentCell];
  7391. data[currentCell] = data[targetCell];
  7392. data[targetCell] = temp;
  7393. }
  7394. }
  7395. // Create a 2D canvas to store the result
  7396. if (!screenshotCanvas) {
  7397. screenshotCanvas = document.createElement('canvas');
  7398. }
  7399. screenshotCanvas.width = width;
  7400. screenshotCanvas.height = height;
  7401. var context = screenshotCanvas.getContext('2d');
  7402. if (context) {
  7403. // Copy the pixels to a 2D canvas
  7404. var imageData = context.createImageData(width, height);
  7405. var castData = (imageData.data);
  7406. castData.set(data);
  7407. context.putImageData(imageData, 0, 0);
  7408. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7409. }
  7410. };
  7411. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7412. if (mimeType === void 0) { mimeType = "image/png"; }
  7413. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7414. if (successCallback) {
  7415. successCallback(base64Image);
  7416. }
  7417. else {
  7418. // We need HTMLCanvasElement.toBlob for HD screenshots
  7419. if (!screenshotCanvas.toBlob) {
  7420. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7421. screenshotCanvas.toBlob = function (callback, type, quality) {
  7422. var _this = this;
  7423. setTimeout(function () {
  7424. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7425. for (var i = 0; i < len; i++) {
  7426. arr[i] = binStr.charCodeAt(i);
  7427. }
  7428. callback(new Blob([arr], { type: type || 'image/png' }));
  7429. });
  7430. };
  7431. }
  7432. screenshotCanvas.toBlob(function (blob) {
  7433. var url = URL.createObjectURL(blob);
  7434. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7435. if (("download" in document.createElement("a"))) {
  7436. var a = window.document.createElement("a");
  7437. a.href = url;
  7438. if (fileName) {
  7439. a.setAttribute("download", fileName);
  7440. }
  7441. else {
  7442. var date = new Date();
  7443. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7444. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7445. }
  7446. window.document.body.appendChild(a);
  7447. a.addEventListener("click", function () {
  7448. if (a.parentElement) {
  7449. a.parentElement.removeChild(a);
  7450. }
  7451. });
  7452. a.click();
  7453. }
  7454. else {
  7455. var newWindow = window.open("");
  7456. if (!newWindow)
  7457. return;
  7458. var img = newWindow.document.createElement("img");
  7459. img.onload = function () {
  7460. // no longer need to read the blob so it's revoked
  7461. URL.revokeObjectURL(url);
  7462. };
  7463. img.src = url;
  7464. newWindow.document.body.appendChild(img);
  7465. }
  7466. });
  7467. }
  7468. };
  7469. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7470. if (mimeType === void 0) { mimeType = "image/png"; }
  7471. var width;
  7472. var height;
  7473. // If a precision value is specified
  7474. if (size.precision) {
  7475. width = Math.round(engine.getRenderWidth() * size.precision);
  7476. height = Math.round(width / engine.getAspectRatio(camera));
  7477. }
  7478. else if (size.width && size.height) {
  7479. width = size.width;
  7480. height = size.height;
  7481. }
  7482. else if (size.width && !size.height) {
  7483. width = size.width;
  7484. height = Math.round(width / engine.getAspectRatio(camera));
  7485. }
  7486. else if (size.height && !size.width) {
  7487. height = size.height;
  7488. width = Math.round(height * engine.getAspectRatio(camera));
  7489. }
  7490. else if (!isNaN(size)) {
  7491. height = size;
  7492. width = size;
  7493. }
  7494. else {
  7495. Tools.Error("Invalid 'size' parameter !");
  7496. return;
  7497. }
  7498. if (!screenshotCanvas) {
  7499. screenshotCanvas = document.createElement('canvas');
  7500. }
  7501. screenshotCanvas.width = width;
  7502. screenshotCanvas.height = height;
  7503. var renderContext = screenshotCanvas.getContext("2d");
  7504. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7505. var newWidth = width;
  7506. var newHeight = newWidth / ratio;
  7507. if (newHeight > height) {
  7508. newHeight = height;
  7509. newWidth = newHeight * ratio;
  7510. }
  7511. var offsetX = Math.max(0, width - newWidth) / 2;
  7512. var offsetY = Math.max(0, height - newHeight) / 2;
  7513. var renderingCanvas = engine.getRenderingCanvas();
  7514. if (renderContext && renderingCanvas) {
  7515. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7516. }
  7517. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7518. };
  7519. /**
  7520. * Generates an image screenshot from the specified camera.
  7521. *
  7522. * @param engine The engine to use for rendering
  7523. * @param camera The camera to use for rendering
  7524. * @param size This parameter can be set to a single number or to an object with the
  7525. * following (optional) properties: precision, width, height. If a single number is passed,
  7526. * it will be used for both width and height. If an object is passed, the screenshot size
  7527. * will be derived from the parameters. The precision property is a multiplier allowing
  7528. * rendering at a higher or lower resolution.
  7529. * @param successCallback The callback receives a single parameter which contains the
  7530. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7531. * src parameter of an <img> to display it.
  7532. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7533. * Check your browser for supported MIME types.
  7534. * @param samples Texture samples (default: 1)
  7535. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7536. * @param fileName A name for for the downloaded file.
  7537. * @constructor
  7538. */
  7539. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7540. if (mimeType === void 0) { mimeType = "image/png"; }
  7541. if (samples === void 0) { samples = 1; }
  7542. if (antialiasing === void 0) { antialiasing = false; }
  7543. var width;
  7544. var height;
  7545. //If a precision value is specified
  7546. if (size.precision) {
  7547. width = Math.round(engine.getRenderWidth() * size.precision);
  7548. height = Math.round(width / engine.getAspectRatio(camera));
  7549. size = { width: width, height: height };
  7550. }
  7551. else if (size.width && size.height) {
  7552. width = size.width;
  7553. height = size.height;
  7554. }
  7555. else if (size.width && !size.height) {
  7556. width = size.width;
  7557. height = Math.round(width / engine.getAspectRatio(camera));
  7558. size = { width: width, height: height };
  7559. }
  7560. else if (size.height && !size.width) {
  7561. height = size.height;
  7562. width = Math.round(height * engine.getAspectRatio(camera));
  7563. size = { width: width, height: height };
  7564. }
  7565. else if (!isNaN(size)) {
  7566. height = size;
  7567. width = size;
  7568. }
  7569. else {
  7570. Tools.Error("Invalid 'size' parameter !");
  7571. return;
  7572. }
  7573. var scene = camera.getScene();
  7574. var previousCamera = null;
  7575. if (scene.activeCamera !== camera) {
  7576. previousCamera = scene.activeCamera;
  7577. scene.activeCamera = camera;
  7578. }
  7579. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7580. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7581. texture.renderList = null;
  7582. texture.samples = samples;
  7583. if (antialiasing) {
  7584. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7585. }
  7586. texture.onAfterRenderObservable.add(function () {
  7587. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7588. });
  7589. scene.incrementRenderId();
  7590. scene.resetCachedMaterial();
  7591. texture.render(true);
  7592. texture.dispose();
  7593. if (previousCamera) {
  7594. scene.activeCamera = previousCamera;
  7595. }
  7596. camera.getProjectionMatrix(true); // Force cache refresh;
  7597. };
  7598. // XHR response validator for local file scenario
  7599. Tools.ValidateXHRData = function (xhr, dataType) {
  7600. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7601. if (dataType === void 0) { dataType = 7; }
  7602. try {
  7603. if (dataType & 1) {
  7604. if (xhr.responseText && xhr.responseText.length > 0) {
  7605. return true;
  7606. }
  7607. else if (dataType === 1) {
  7608. return false;
  7609. }
  7610. }
  7611. if (dataType & 2) {
  7612. // Check header width and height since there is no "TGA" magic number
  7613. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7614. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7615. return true;
  7616. }
  7617. else if (dataType === 2) {
  7618. return false;
  7619. }
  7620. }
  7621. if (dataType & 4) {
  7622. // Check for the "DDS" magic number
  7623. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7624. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7625. return true;
  7626. }
  7627. else {
  7628. return false;
  7629. }
  7630. }
  7631. }
  7632. catch (e) {
  7633. // Global protection
  7634. }
  7635. return false;
  7636. };
  7637. /**
  7638. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7639. * Be aware Math.random() could cause collisions, but:
  7640. * "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"
  7641. */
  7642. Tools.RandomId = function () {
  7643. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7644. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7645. return v.toString(16);
  7646. });
  7647. };
  7648. Object.defineProperty(Tools, "NoneLogLevel", {
  7649. get: function () {
  7650. return Tools._NoneLogLevel;
  7651. },
  7652. enumerable: true,
  7653. configurable: true
  7654. });
  7655. Object.defineProperty(Tools, "MessageLogLevel", {
  7656. get: function () {
  7657. return Tools._MessageLogLevel;
  7658. },
  7659. enumerable: true,
  7660. configurable: true
  7661. });
  7662. Object.defineProperty(Tools, "WarningLogLevel", {
  7663. get: function () {
  7664. return Tools._WarningLogLevel;
  7665. },
  7666. enumerable: true,
  7667. configurable: true
  7668. });
  7669. Object.defineProperty(Tools, "ErrorLogLevel", {
  7670. get: function () {
  7671. return Tools._ErrorLogLevel;
  7672. },
  7673. enumerable: true,
  7674. configurable: true
  7675. });
  7676. Object.defineProperty(Tools, "AllLogLevel", {
  7677. get: function () {
  7678. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7679. },
  7680. enumerable: true,
  7681. configurable: true
  7682. });
  7683. Tools._AddLogEntry = function (entry) {
  7684. Tools._LogCache = entry + Tools._LogCache;
  7685. if (Tools.OnNewCacheEntry) {
  7686. Tools.OnNewCacheEntry(entry);
  7687. }
  7688. };
  7689. Tools._FormatMessage = function (message) {
  7690. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7691. var date = new Date();
  7692. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7693. };
  7694. Tools._LogDisabled = function (message) {
  7695. // nothing to do
  7696. };
  7697. Tools._LogEnabled = function (message) {
  7698. var formattedMessage = Tools._FormatMessage(message);
  7699. console.log("BJS - " + formattedMessage);
  7700. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7701. Tools._AddLogEntry(entry);
  7702. };
  7703. Tools._WarnDisabled = function (message) {
  7704. // nothing to do
  7705. };
  7706. Tools._WarnEnabled = function (message) {
  7707. var formattedMessage = Tools._FormatMessage(message);
  7708. console.warn("BJS - " + formattedMessage);
  7709. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7710. Tools._AddLogEntry(entry);
  7711. };
  7712. Tools._ErrorDisabled = function (message) {
  7713. // nothing to do
  7714. };
  7715. Tools._ErrorEnabled = function (message) {
  7716. Tools.errorsCount++;
  7717. var formattedMessage = Tools._FormatMessage(message);
  7718. console.error("BJS - " + formattedMessage);
  7719. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7720. Tools._AddLogEntry(entry);
  7721. };
  7722. Object.defineProperty(Tools, "LogCache", {
  7723. get: function () {
  7724. return Tools._LogCache;
  7725. },
  7726. enumerable: true,
  7727. configurable: true
  7728. });
  7729. Tools.ClearLogCache = function () {
  7730. Tools._LogCache = "";
  7731. Tools.errorsCount = 0;
  7732. };
  7733. Object.defineProperty(Tools, "LogLevels", {
  7734. set: function (level) {
  7735. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7736. Tools.Log = Tools._LogEnabled;
  7737. }
  7738. else {
  7739. Tools.Log = Tools._LogDisabled;
  7740. }
  7741. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7742. Tools.Warn = Tools._WarnEnabled;
  7743. }
  7744. else {
  7745. Tools.Warn = Tools._WarnDisabled;
  7746. }
  7747. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7748. Tools.Error = Tools._ErrorEnabled;
  7749. }
  7750. else {
  7751. Tools.Error = Tools._ErrorDisabled;
  7752. }
  7753. },
  7754. enumerable: true,
  7755. configurable: true
  7756. });
  7757. Tools.IsWindowObjectExist = function () {
  7758. return (typeof window) !== "undefined";
  7759. };
  7760. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7761. get: function () {
  7762. return Tools._PerformanceNoneLogLevel;
  7763. },
  7764. enumerable: true,
  7765. configurable: true
  7766. });
  7767. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7768. get: function () {
  7769. return Tools._PerformanceUserMarkLogLevel;
  7770. },
  7771. enumerable: true,
  7772. configurable: true
  7773. });
  7774. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7775. get: function () {
  7776. return Tools._PerformanceConsoleLogLevel;
  7777. },
  7778. enumerable: true,
  7779. configurable: true
  7780. });
  7781. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7782. set: function (level) {
  7783. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7784. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7785. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7786. return;
  7787. }
  7788. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7789. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7790. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7791. return;
  7792. }
  7793. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7794. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7795. },
  7796. enumerable: true,
  7797. configurable: true
  7798. });
  7799. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7800. };
  7801. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7802. };
  7803. Tools._StartUserMark = function (counterName, condition) {
  7804. if (condition === void 0) { condition = true; }
  7805. if (!Tools._performance) {
  7806. if (!Tools.IsWindowObjectExist()) {
  7807. return;
  7808. }
  7809. Tools._performance = window.performance;
  7810. }
  7811. if (!condition || !Tools._performance.mark) {
  7812. return;
  7813. }
  7814. Tools._performance.mark(counterName + "-Begin");
  7815. };
  7816. Tools._EndUserMark = function (counterName, condition) {
  7817. if (condition === void 0) { condition = true; }
  7818. if (!condition || !Tools._performance.mark) {
  7819. return;
  7820. }
  7821. Tools._performance.mark(counterName + "-End");
  7822. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7823. };
  7824. Tools._StartPerformanceConsole = function (counterName, condition) {
  7825. if (condition === void 0) { condition = true; }
  7826. if (!condition) {
  7827. return;
  7828. }
  7829. Tools._StartUserMark(counterName, condition);
  7830. if (console.time) {
  7831. console.time(counterName);
  7832. }
  7833. };
  7834. Tools._EndPerformanceConsole = function (counterName, condition) {
  7835. if (condition === void 0) { condition = true; }
  7836. if (!condition) {
  7837. return;
  7838. }
  7839. Tools._EndUserMark(counterName, condition);
  7840. if (console.time) {
  7841. console.timeEnd(counterName);
  7842. }
  7843. };
  7844. Object.defineProperty(Tools, "Now", {
  7845. get: function () {
  7846. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7847. return window.performance.now();
  7848. }
  7849. return new Date().getTime();
  7850. },
  7851. enumerable: true,
  7852. configurable: true
  7853. });
  7854. /**
  7855. * This method will return the name of the class used to create the instance of the given object.
  7856. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7857. * @param object the object to get the class name from
  7858. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7859. */
  7860. Tools.GetClassName = function (object, isType) {
  7861. if (isType === void 0) { isType = false; }
  7862. var name = null;
  7863. if (!isType && object.getClassName) {
  7864. name = object.getClassName();
  7865. }
  7866. else {
  7867. if (object instanceof Object) {
  7868. var classObj = isType ? object : Object.getPrototypeOf(object);
  7869. name = classObj.constructor["__bjsclassName__"];
  7870. }
  7871. if (!name) {
  7872. name = typeof object;
  7873. }
  7874. }
  7875. return name;
  7876. };
  7877. Tools.First = function (array, predicate) {
  7878. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7879. var el = array_1[_i];
  7880. if (predicate(el)) {
  7881. return el;
  7882. }
  7883. }
  7884. return null;
  7885. };
  7886. /**
  7887. * This method will return the name of the full name of the class, including its owning module (if any).
  7888. * 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).
  7889. * @param object the object to get the class name from
  7890. * @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.
  7891. */
  7892. Tools.getFullClassName = function (object, isType) {
  7893. if (isType === void 0) { isType = false; }
  7894. var className = null;
  7895. var moduleName = null;
  7896. if (!isType && object.getClassName) {
  7897. className = object.getClassName();
  7898. }
  7899. else {
  7900. if (object instanceof Object) {
  7901. var classObj = isType ? object : Object.getPrototypeOf(object);
  7902. className = classObj.constructor["__bjsclassName__"];
  7903. moduleName = classObj.constructor["__bjsmoduleName__"];
  7904. }
  7905. if (!className) {
  7906. className = typeof object;
  7907. }
  7908. }
  7909. if (!className) {
  7910. return null;
  7911. }
  7912. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7913. };
  7914. /**
  7915. * 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.
  7916. * @param array
  7917. */
  7918. Tools.arrayOrStringFeeder = function (array) {
  7919. return function (index) {
  7920. if (index >= array.length) {
  7921. return null;
  7922. }
  7923. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7924. if (val && val.getHashCode) {
  7925. val = val.getHashCode();
  7926. }
  7927. if (typeof val === "string") {
  7928. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7929. }
  7930. return val;
  7931. };
  7932. };
  7933. /**
  7934. * Compute the hashCode of a stream of number
  7935. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7936. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7937. * @return the hash code computed
  7938. */
  7939. Tools.hashCodeFromStream = function (feeder) {
  7940. // Based from here: http://stackoverflow.com/a/7616484/802124
  7941. var hash = 0;
  7942. var index = 0;
  7943. var chr = feeder(index++);
  7944. while (chr != null) {
  7945. hash = ((hash << 5) - hash) + chr;
  7946. hash |= 0; // Convert to 32bit integer
  7947. chr = feeder(index++);
  7948. }
  7949. return hash;
  7950. };
  7951. Tools.BaseUrl = "";
  7952. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7953. /**
  7954. * Default behaviour for cors in the application.
  7955. * It can be a string if the expected behavior is identical in the entire app.
  7956. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7957. */
  7958. Tools.CorsBehavior = "anonymous";
  7959. Tools.UseFallbackTexture = true;
  7960. /**
  7961. * Use this object to register external classes like custom textures or material
  7962. * to allow the laoders to instantiate them
  7963. */
  7964. Tools.RegisteredExternalClasses = {};
  7965. // Used in case of a texture loading problem
  7966. 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";
  7967. Tools.PreprocessUrl = function (url) {
  7968. return url;
  7969. };
  7970. // Logs
  7971. Tools._NoneLogLevel = 0;
  7972. Tools._MessageLogLevel = 1;
  7973. Tools._WarningLogLevel = 2;
  7974. Tools._ErrorLogLevel = 4;
  7975. Tools._LogCache = "";
  7976. Tools.errorsCount = 0;
  7977. Tools.Log = Tools._LogEnabled;
  7978. Tools.Warn = Tools._WarnEnabled;
  7979. Tools.Error = Tools._ErrorEnabled;
  7980. // Performances
  7981. Tools._PerformanceNoneLogLevel = 0;
  7982. Tools._PerformanceUserMarkLogLevel = 1;
  7983. Tools._PerformanceConsoleLogLevel = 2;
  7984. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7985. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7986. return Tools;
  7987. }());
  7988. BABYLON.Tools = Tools;
  7989. /**
  7990. * This class is used to track a performance counter which is number based.
  7991. * The user has access to many properties which give statistics of different nature
  7992. *
  7993. * The implementer can track two kinds of Performance Counter: time and count
  7994. * 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.
  7995. * 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.
  7996. */
  7997. var PerfCounter = /** @class */ (function () {
  7998. function PerfCounter() {
  7999. this._startMonitoringTime = 0;
  8000. this._min = 0;
  8001. this._max = 0;
  8002. this._average = 0;
  8003. this._lastSecAverage = 0;
  8004. this._current = 0;
  8005. this._totalValueCount = 0;
  8006. this._totalAccumulated = 0;
  8007. this._lastSecAccumulated = 0;
  8008. this._lastSecTime = 0;
  8009. this._lastSecValueCount = 0;
  8010. }
  8011. Object.defineProperty(PerfCounter.prototype, "min", {
  8012. /**
  8013. * Returns the smallest value ever
  8014. */
  8015. get: function () {
  8016. return this._min;
  8017. },
  8018. enumerable: true,
  8019. configurable: true
  8020. });
  8021. Object.defineProperty(PerfCounter.prototype, "max", {
  8022. /**
  8023. * Returns the biggest value ever
  8024. */
  8025. get: function () {
  8026. return this._max;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. Object.defineProperty(PerfCounter.prototype, "average", {
  8032. /**
  8033. * Returns the average value since the performance counter is running
  8034. */
  8035. get: function () {
  8036. return this._average;
  8037. },
  8038. enumerable: true,
  8039. configurable: true
  8040. });
  8041. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8042. /**
  8043. * Returns the average value of the last second the counter was monitored
  8044. */
  8045. get: function () {
  8046. return this._lastSecAverage;
  8047. },
  8048. enumerable: true,
  8049. configurable: true
  8050. });
  8051. Object.defineProperty(PerfCounter.prototype, "current", {
  8052. /**
  8053. * Returns the current value
  8054. */
  8055. get: function () {
  8056. return this._current;
  8057. },
  8058. enumerable: true,
  8059. configurable: true
  8060. });
  8061. Object.defineProperty(PerfCounter.prototype, "total", {
  8062. get: function () {
  8063. return this._totalAccumulated;
  8064. },
  8065. enumerable: true,
  8066. configurable: true
  8067. });
  8068. Object.defineProperty(PerfCounter.prototype, "count", {
  8069. get: function () {
  8070. return this._totalValueCount;
  8071. },
  8072. enumerable: true,
  8073. configurable: true
  8074. });
  8075. /**
  8076. * Call this method to start monitoring a new frame.
  8077. * 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.
  8078. */
  8079. PerfCounter.prototype.fetchNewFrame = function () {
  8080. this._totalValueCount++;
  8081. this._current = 0;
  8082. this._lastSecValueCount++;
  8083. };
  8084. /**
  8085. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8086. * @param newCount the count value to add to the monitored count
  8087. * @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.
  8088. */
  8089. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8090. if (!PerfCounter.Enabled) {
  8091. return;
  8092. }
  8093. this._current += newCount;
  8094. if (fetchResult) {
  8095. this._fetchResult();
  8096. }
  8097. };
  8098. /**
  8099. * Start monitoring this performance counter
  8100. */
  8101. PerfCounter.prototype.beginMonitoring = function () {
  8102. if (!PerfCounter.Enabled) {
  8103. return;
  8104. }
  8105. this._startMonitoringTime = Tools.Now;
  8106. };
  8107. /**
  8108. * Compute the time lapsed since the previous beginMonitoring() call.
  8109. * @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
  8110. */
  8111. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8112. if (newFrame === void 0) { newFrame = true; }
  8113. if (!PerfCounter.Enabled) {
  8114. return;
  8115. }
  8116. if (newFrame) {
  8117. this.fetchNewFrame();
  8118. }
  8119. var currentTime = Tools.Now;
  8120. this._current = currentTime - this._startMonitoringTime;
  8121. if (newFrame) {
  8122. this._fetchResult();
  8123. }
  8124. };
  8125. PerfCounter.prototype._fetchResult = function () {
  8126. this._totalAccumulated += this._current;
  8127. this._lastSecAccumulated += this._current;
  8128. // Min/Max update
  8129. this._min = Math.min(this._min, this._current);
  8130. this._max = Math.max(this._max, this._current);
  8131. this._average = this._totalAccumulated / this._totalValueCount;
  8132. // Reset last sec?
  8133. var now = Tools.Now;
  8134. if ((now - this._lastSecTime) > 1000) {
  8135. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8136. this._lastSecTime = now;
  8137. this._lastSecAccumulated = 0;
  8138. this._lastSecValueCount = 0;
  8139. }
  8140. };
  8141. PerfCounter.Enabled = true;
  8142. return PerfCounter;
  8143. }());
  8144. BABYLON.PerfCounter = PerfCounter;
  8145. /**
  8146. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8147. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8148. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8149. * @param name The name of the class, case should be preserved
  8150. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8151. */
  8152. function className(name, module) {
  8153. return function (target) {
  8154. target["__bjsclassName__"] = name;
  8155. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8156. };
  8157. }
  8158. BABYLON.className = className;
  8159. /**
  8160. * An implementation of a loop for asynchronous functions.
  8161. */
  8162. var AsyncLoop = /** @class */ (function () {
  8163. /**
  8164. * Constroctor.
  8165. * @param iterations the number of iterations.
  8166. * @param _fn the function to run each iteration
  8167. * @param _successCallback the callback that will be called upon succesful execution
  8168. * @param offset starting offset.
  8169. */
  8170. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8171. if (offset === void 0) { offset = 0; }
  8172. this.iterations = iterations;
  8173. this._fn = _fn;
  8174. this._successCallback = _successCallback;
  8175. this.index = offset - 1;
  8176. this._done = false;
  8177. }
  8178. /**
  8179. * Execute the next iteration. Must be called after the last iteration was finished.
  8180. */
  8181. AsyncLoop.prototype.executeNext = function () {
  8182. if (!this._done) {
  8183. if (this.index + 1 < this.iterations) {
  8184. ++this.index;
  8185. this._fn(this);
  8186. }
  8187. else {
  8188. this.breakLoop();
  8189. }
  8190. }
  8191. };
  8192. /**
  8193. * Break the loop and run the success callback.
  8194. */
  8195. AsyncLoop.prototype.breakLoop = function () {
  8196. this._done = true;
  8197. this._successCallback();
  8198. };
  8199. /**
  8200. * Helper function
  8201. */
  8202. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8203. if (offset === void 0) { offset = 0; }
  8204. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8205. loop.executeNext();
  8206. return loop;
  8207. };
  8208. /**
  8209. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8210. * @param iterations total number of iterations
  8211. * @param syncedIterations number of synchronous iterations in each async iteration.
  8212. * @param fn the function to call each iteration.
  8213. * @param callback a success call back that will be called when iterating stops.
  8214. * @param breakFunction a break condition (optional)
  8215. * @param timeout timeout settings for the setTimeout function. default - 0.
  8216. * @constructor
  8217. */
  8218. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8219. if (timeout === void 0) { timeout = 0; }
  8220. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8221. if (breakFunction && breakFunction())
  8222. loop.breakLoop();
  8223. else {
  8224. setTimeout(function () {
  8225. for (var i = 0; i < syncedIterations; ++i) {
  8226. var iteration = (loop.index * syncedIterations) + i;
  8227. if (iteration >= iterations)
  8228. break;
  8229. fn(iteration);
  8230. if (breakFunction && breakFunction()) {
  8231. loop.breakLoop();
  8232. break;
  8233. }
  8234. }
  8235. loop.executeNext();
  8236. }, timeout);
  8237. }
  8238. }, callback);
  8239. };
  8240. return AsyncLoop;
  8241. }());
  8242. BABYLON.AsyncLoop = AsyncLoop;
  8243. })(BABYLON || (BABYLON = {}));
  8244. //# sourceMappingURL=babylon.tools.js.map
  8245. var BABYLON;
  8246. (function (BABYLON) {
  8247. var PromiseStates;
  8248. (function (PromiseStates) {
  8249. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8250. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8251. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8252. })(PromiseStates || (PromiseStates = {}));
  8253. var Promise = /** @class */ (function () {
  8254. function Promise(resolver) {
  8255. var _this = this;
  8256. this._state = PromiseStates.Pending;
  8257. if (!resolver) {
  8258. return;
  8259. }
  8260. try {
  8261. resolver(function (value) {
  8262. _this._resolve(value);
  8263. }, function (reason) {
  8264. _this._reject(reason);
  8265. });
  8266. }
  8267. catch (e) {
  8268. this._reject(e.message);
  8269. }
  8270. }
  8271. Object.defineProperty(Promise.prototype, "state", {
  8272. get: function () {
  8273. return this._state;
  8274. },
  8275. enumerable: true,
  8276. configurable: true
  8277. });
  8278. Promise.prototype.isFulfilled = function () {
  8279. return this._state === PromiseStates.Fulfilled;
  8280. };
  8281. Promise.prototype.isRejected = function () {
  8282. return this._state === PromiseStates.Rejected;
  8283. };
  8284. Promise.prototype.isPending = function () {
  8285. return this._state === PromiseStates.Pending;
  8286. };
  8287. Promise.prototype.value = function () {
  8288. if (!this.isFulfilled()) {
  8289. throw new Error("Promise is not fulfilled");
  8290. }
  8291. return this._result;
  8292. };
  8293. Promise.prototype.reason = function () {
  8294. if (!this.isRejected()) {
  8295. throw new Error("Promise is not rejected");
  8296. }
  8297. return this._reason;
  8298. };
  8299. Promise.prototype.catch = function (onRejected) {
  8300. return this.then(undefined, onRejected);
  8301. };
  8302. Promise.prototype.then = function (onFulfilled, onRejected) {
  8303. var newPromise = new Promise();
  8304. newPromise._onFulfilled = onFulfilled;
  8305. newPromise._onRejected = onRejected;
  8306. // Composition
  8307. this._child = newPromise;
  8308. switch (this._state) {
  8309. case PromiseStates.Fulfilled:
  8310. var returnedPromise = newPromise._resolve(this._result);
  8311. if (returnedPromise) {
  8312. newPromise._child = returnedPromise;
  8313. newPromise = returnedPromise;
  8314. }
  8315. break;
  8316. case PromiseStates.Rejected:
  8317. newPromise._reject(this._reason);
  8318. newPromise._state = PromiseStates.Fulfilled;
  8319. break;
  8320. }
  8321. return newPromise;
  8322. };
  8323. Promise.prototype._resolve = function (value) {
  8324. try {
  8325. this._state = PromiseStates.Fulfilled;
  8326. this._result = value;
  8327. var returnedPromise = null;
  8328. if (this._onFulfilled) {
  8329. returnedPromise = this._onFulfilled(value);
  8330. }
  8331. if (this._child) {
  8332. this._child._resolve(value);
  8333. }
  8334. return returnedPromise;
  8335. }
  8336. catch (e) {
  8337. this._reject(e.message);
  8338. }
  8339. return null;
  8340. };
  8341. Promise.prototype._reject = function (reason) {
  8342. this._state = PromiseStates.Rejected;
  8343. this._reason = reason;
  8344. if (this._onRejected) {
  8345. this._onRejected(reason);
  8346. }
  8347. if (this._child) {
  8348. this._child._resolve(null);
  8349. }
  8350. };
  8351. Promise.resolve = function (value) {
  8352. var newPromise = new Promise();
  8353. newPromise._resolve(value);
  8354. return newPromise;
  8355. };
  8356. return Promise;
  8357. }());
  8358. var PromisePolyfill = /** @class */ (function () {
  8359. function PromisePolyfill() {
  8360. }
  8361. PromisePolyfill.Apply = function (force) {
  8362. if (force === void 0) { force = false; }
  8363. if (force || typeof Promise === 'undefined') {
  8364. var root = window;
  8365. root.Promise = Promise;
  8366. }
  8367. };
  8368. return PromisePolyfill;
  8369. }());
  8370. BABYLON.PromisePolyfill = PromisePolyfill;
  8371. })(BABYLON || (BABYLON = {}));
  8372. //# sourceMappingURL=babylon.promise.js.map
  8373. var BABYLON;
  8374. (function (BABYLON) {
  8375. var _AlphaState = /** @class */ (function () {
  8376. /**
  8377. * Initializes the state.
  8378. */
  8379. function _AlphaState() {
  8380. this._isAlphaBlendDirty = false;
  8381. this._isBlendFunctionParametersDirty = false;
  8382. this._isBlendEquationParametersDirty = false;
  8383. this._isBlendConstantsDirty = false;
  8384. this._alphaBlend = false;
  8385. this._blendFunctionParameters = new Array(4);
  8386. this._blendEquationParameters = new Array(2);
  8387. this._blendConstants = new Array(4);
  8388. this.reset();
  8389. }
  8390. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8391. get: function () {
  8392. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8393. },
  8394. enumerable: true,
  8395. configurable: true
  8396. });
  8397. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8398. get: function () {
  8399. return this._alphaBlend;
  8400. },
  8401. set: function (value) {
  8402. if (this._alphaBlend === value) {
  8403. return;
  8404. }
  8405. this._alphaBlend = value;
  8406. this._isAlphaBlendDirty = true;
  8407. },
  8408. enumerable: true,
  8409. configurable: true
  8410. });
  8411. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8412. if (this._blendConstants[0] === r &&
  8413. this._blendConstants[1] === g &&
  8414. this._blendConstants[2] === b &&
  8415. this._blendConstants[3] === a) {
  8416. return;
  8417. }
  8418. this._blendConstants[0] = r;
  8419. this._blendConstants[1] = g;
  8420. this._blendConstants[2] = b;
  8421. this._blendConstants[3] = a;
  8422. this._isBlendConstantsDirty = true;
  8423. };
  8424. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8425. if (this._blendFunctionParameters[0] === value0 &&
  8426. this._blendFunctionParameters[1] === value1 &&
  8427. this._blendFunctionParameters[2] === value2 &&
  8428. this._blendFunctionParameters[3] === value3) {
  8429. return;
  8430. }
  8431. this._blendFunctionParameters[0] = value0;
  8432. this._blendFunctionParameters[1] = value1;
  8433. this._blendFunctionParameters[2] = value2;
  8434. this._blendFunctionParameters[3] = value3;
  8435. this._isBlendFunctionParametersDirty = true;
  8436. };
  8437. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8438. if (this._blendEquationParameters[0] === rgb &&
  8439. this._blendEquationParameters[1] === alpha) {
  8440. return;
  8441. }
  8442. this._blendEquationParameters[0] = rgb;
  8443. this._blendEquationParameters[1] = alpha;
  8444. this._isBlendEquationParametersDirty = true;
  8445. };
  8446. _AlphaState.prototype.reset = function () {
  8447. this._alphaBlend = false;
  8448. this._blendFunctionParameters[0] = null;
  8449. this._blendFunctionParameters[1] = null;
  8450. this._blendFunctionParameters[2] = null;
  8451. this._blendFunctionParameters[3] = null;
  8452. this._blendEquationParameters[0] = null;
  8453. this._blendEquationParameters[1] = null;
  8454. this._blendConstants[0] = null;
  8455. this._blendConstants[1] = null;
  8456. this._blendConstants[2] = null;
  8457. this._blendConstants[3] = null;
  8458. this._isAlphaBlendDirty = true;
  8459. this._isBlendFunctionParametersDirty = false;
  8460. this._isBlendEquationParametersDirty = false;
  8461. this._isBlendConstantsDirty = false;
  8462. };
  8463. _AlphaState.prototype.apply = function (gl) {
  8464. if (!this.isDirty) {
  8465. return;
  8466. }
  8467. // Alpha blend
  8468. if (this._isAlphaBlendDirty) {
  8469. if (this._alphaBlend) {
  8470. gl.enable(gl.BLEND);
  8471. }
  8472. else {
  8473. gl.disable(gl.BLEND);
  8474. }
  8475. this._isAlphaBlendDirty = false;
  8476. }
  8477. // Alpha function
  8478. if (this._isBlendFunctionParametersDirty) {
  8479. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8480. this._isBlendFunctionParametersDirty = false;
  8481. }
  8482. // Alpha equation
  8483. if (this._isBlendEquationParametersDirty) {
  8484. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8485. this._isBlendEquationParametersDirty = false;
  8486. }
  8487. // Constants
  8488. if (this._isBlendConstantsDirty) {
  8489. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8490. this._isBlendConstantsDirty = false;
  8491. }
  8492. };
  8493. return _AlphaState;
  8494. }());
  8495. BABYLON._AlphaState = _AlphaState;
  8496. })(BABYLON || (BABYLON = {}));
  8497. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8498. var BABYLON;
  8499. (function (BABYLON) {
  8500. var _DepthCullingState = /** @class */ (function () {
  8501. /**
  8502. * Initializes the state.
  8503. */
  8504. function _DepthCullingState() {
  8505. this._isDepthTestDirty = false;
  8506. this._isDepthMaskDirty = false;
  8507. this._isDepthFuncDirty = false;
  8508. this._isCullFaceDirty = false;
  8509. this._isCullDirty = false;
  8510. this._isZOffsetDirty = false;
  8511. this._isFrontFaceDirty = false;
  8512. this.reset();
  8513. }
  8514. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8515. get: function () {
  8516. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8517. },
  8518. enumerable: true,
  8519. configurable: true
  8520. });
  8521. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8522. get: function () {
  8523. return this._zOffset;
  8524. },
  8525. set: function (value) {
  8526. if (this._zOffset === value) {
  8527. return;
  8528. }
  8529. this._zOffset = value;
  8530. this._isZOffsetDirty = true;
  8531. },
  8532. enumerable: true,
  8533. configurable: true
  8534. });
  8535. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8536. get: function () {
  8537. return this._cullFace;
  8538. },
  8539. set: function (value) {
  8540. if (this._cullFace === value) {
  8541. return;
  8542. }
  8543. this._cullFace = value;
  8544. this._isCullFaceDirty = true;
  8545. },
  8546. enumerable: true,
  8547. configurable: true
  8548. });
  8549. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8550. get: function () {
  8551. return this._cull;
  8552. },
  8553. set: function (value) {
  8554. if (this._cull === value) {
  8555. return;
  8556. }
  8557. this._cull = value;
  8558. this._isCullDirty = true;
  8559. },
  8560. enumerable: true,
  8561. configurable: true
  8562. });
  8563. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8564. get: function () {
  8565. return this._depthFunc;
  8566. },
  8567. set: function (value) {
  8568. if (this._depthFunc === value) {
  8569. return;
  8570. }
  8571. this._depthFunc = value;
  8572. this._isDepthFuncDirty = true;
  8573. },
  8574. enumerable: true,
  8575. configurable: true
  8576. });
  8577. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8578. get: function () {
  8579. return this._depthMask;
  8580. },
  8581. set: function (value) {
  8582. if (this._depthMask === value) {
  8583. return;
  8584. }
  8585. this._depthMask = value;
  8586. this._isDepthMaskDirty = true;
  8587. },
  8588. enumerable: true,
  8589. configurable: true
  8590. });
  8591. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8592. get: function () {
  8593. return this._depthTest;
  8594. },
  8595. set: function (value) {
  8596. if (this._depthTest === value) {
  8597. return;
  8598. }
  8599. this._depthTest = value;
  8600. this._isDepthTestDirty = true;
  8601. },
  8602. enumerable: true,
  8603. configurable: true
  8604. });
  8605. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8606. get: function () {
  8607. return this._frontFace;
  8608. },
  8609. set: function (value) {
  8610. if (this._frontFace === value) {
  8611. return;
  8612. }
  8613. this._frontFace = value;
  8614. this._isFrontFaceDirty = true;
  8615. },
  8616. enumerable: true,
  8617. configurable: true
  8618. });
  8619. _DepthCullingState.prototype.reset = function () {
  8620. this._depthMask = true;
  8621. this._depthTest = true;
  8622. this._depthFunc = null;
  8623. this._cullFace = null;
  8624. this._cull = null;
  8625. this._zOffset = 0;
  8626. this._frontFace = null;
  8627. this._isDepthTestDirty = true;
  8628. this._isDepthMaskDirty = true;
  8629. this._isDepthFuncDirty = false;
  8630. this._isCullFaceDirty = false;
  8631. this._isCullDirty = false;
  8632. this._isZOffsetDirty = false;
  8633. this._isFrontFaceDirty = false;
  8634. };
  8635. _DepthCullingState.prototype.apply = function (gl) {
  8636. if (!this.isDirty) {
  8637. return;
  8638. }
  8639. // Cull
  8640. if (this._isCullDirty) {
  8641. if (this.cull) {
  8642. gl.enable(gl.CULL_FACE);
  8643. }
  8644. else {
  8645. gl.disable(gl.CULL_FACE);
  8646. }
  8647. this._isCullDirty = false;
  8648. }
  8649. // Cull face
  8650. if (this._isCullFaceDirty) {
  8651. gl.cullFace(this.cullFace);
  8652. this._isCullFaceDirty = false;
  8653. }
  8654. // Depth mask
  8655. if (this._isDepthMaskDirty) {
  8656. gl.depthMask(this.depthMask);
  8657. this._isDepthMaskDirty = false;
  8658. }
  8659. // Depth test
  8660. if (this._isDepthTestDirty) {
  8661. if (this.depthTest) {
  8662. gl.enable(gl.DEPTH_TEST);
  8663. }
  8664. else {
  8665. gl.disable(gl.DEPTH_TEST);
  8666. }
  8667. this._isDepthTestDirty = false;
  8668. }
  8669. // Depth func
  8670. if (this._isDepthFuncDirty) {
  8671. gl.depthFunc(this.depthFunc);
  8672. this._isDepthFuncDirty = false;
  8673. }
  8674. // zOffset
  8675. if (this._isZOffsetDirty) {
  8676. if (this.zOffset) {
  8677. gl.enable(gl.POLYGON_OFFSET_FILL);
  8678. gl.polygonOffset(this.zOffset, 0);
  8679. }
  8680. else {
  8681. gl.disable(gl.POLYGON_OFFSET_FILL);
  8682. }
  8683. this._isZOffsetDirty = false;
  8684. }
  8685. // Front face
  8686. if (this._isFrontFaceDirty) {
  8687. gl.frontFace(this.frontFace);
  8688. this._isFrontFaceDirty = false;
  8689. }
  8690. };
  8691. return _DepthCullingState;
  8692. }());
  8693. BABYLON._DepthCullingState = _DepthCullingState;
  8694. })(BABYLON || (BABYLON = {}));
  8695. //# sourceMappingURL=babylon.depthCullingState.js.map
  8696. var BABYLON;
  8697. (function (BABYLON) {
  8698. var _StencilState = /** @class */ (function () {
  8699. function _StencilState() {
  8700. this._isStencilTestDirty = false;
  8701. this._isStencilMaskDirty = false;
  8702. this._isStencilFuncDirty = false;
  8703. this._isStencilOpDirty = false;
  8704. this.reset();
  8705. }
  8706. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8707. get: function () {
  8708. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8709. },
  8710. enumerable: true,
  8711. configurable: true
  8712. });
  8713. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8714. get: function () {
  8715. return this._stencilFunc;
  8716. },
  8717. set: function (value) {
  8718. if (this._stencilFunc === value) {
  8719. return;
  8720. }
  8721. this._stencilFunc = value;
  8722. this._isStencilFuncDirty = true;
  8723. },
  8724. enumerable: true,
  8725. configurable: true
  8726. });
  8727. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8728. get: function () {
  8729. return this._stencilFuncRef;
  8730. },
  8731. set: function (value) {
  8732. if (this._stencilFuncRef === value) {
  8733. return;
  8734. }
  8735. this._stencilFuncRef = value;
  8736. this._isStencilFuncDirty = true;
  8737. },
  8738. enumerable: true,
  8739. configurable: true
  8740. });
  8741. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8742. get: function () {
  8743. return this._stencilFuncMask;
  8744. },
  8745. set: function (value) {
  8746. if (this._stencilFuncMask === value) {
  8747. return;
  8748. }
  8749. this._stencilFuncMask = value;
  8750. this._isStencilFuncDirty = true;
  8751. },
  8752. enumerable: true,
  8753. configurable: true
  8754. });
  8755. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8756. get: function () {
  8757. return this._stencilOpStencilFail;
  8758. },
  8759. set: function (value) {
  8760. if (this._stencilOpStencilFail === value) {
  8761. return;
  8762. }
  8763. this._stencilOpStencilFail = value;
  8764. this._isStencilOpDirty = true;
  8765. },
  8766. enumerable: true,
  8767. configurable: true
  8768. });
  8769. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8770. get: function () {
  8771. return this._stencilOpDepthFail;
  8772. },
  8773. set: function (value) {
  8774. if (this._stencilOpDepthFail === value) {
  8775. return;
  8776. }
  8777. this._stencilOpDepthFail = value;
  8778. this._isStencilOpDirty = true;
  8779. },
  8780. enumerable: true,
  8781. configurable: true
  8782. });
  8783. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8784. get: function () {
  8785. return this._stencilOpStencilDepthPass;
  8786. },
  8787. set: function (value) {
  8788. if (this._stencilOpStencilDepthPass === value) {
  8789. return;
  8790. }
  8791. this._stencilOpStencilDepthPass = value;
  8792. this._isStencilOpDirty = true;
  8793. },
  8794. enumerable: true,
  8795. configurable: true
  8796. });
  8797. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8798. get: function () {
  8799. return this._stencilMask;
  8800. },
  8801. set: function (value) {
  8802. if (this._stencilMask === value) {
  8803. return;
  8804. }
  8805. this._stencilMask = value;
  8806. this._isStencilMaskDirty = true;
  8807. },
  8808. enumerable: true,
  8809. configurable: true
  8810. });
  8811. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8812. get: function () {
  8813. return this._stencilTest;
  8814. },
  8815. set: function (value) {
  8816. if (this._stencilTest === value) {
  8817. return;
  8818. }
  8819. this._stencilTest = value;
  8820. this._isStencilTestDirty = true;
  8821. },
  8822. enumerable: true,
  8823. configurable: true
  8824. });
  8825. _StencilState.prototype.reset = function () {
  8826. this._stencilTest = false;
  8827. this._stencilMask = 0xFF;
  8828. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8829. this._stencilFuncRef = 1;
  8830. this._stencilFuncMask = 0xFF;
  8831. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8832. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8833. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8834. this._isStencilTestDirty = true;
  8835. this._isStencilMaskDirty = true;
  8836. this._isStencilFuncDirty = true;
  8837. this._isStencilOpDirty = true;
  8838. };
  8839. _StencilState.prototype.apply = function (gl) {
  8840. if (!this.isDirty) {
  8841. return;
  8842. }
  8843. // Stencil test
  8844. if (this._isStencilTestDirty) {
  8845. if (this.stencilTest) {
  8846. gl.enable(gl.STENCIL_TEST);
  8847. }
  8848. else {
  8849. gl.disable(gl.STENCIL_TEST);
  8850. }
  8851. this._isStencilTestDirty = false;
  8852. }
  8853. // Stencil mask
  8854. if (this._isStencilMaskDirty) {
  8855. gl.stencilMask(this.stencilMask);
  8856. this._isStencilMaskDirty = false;
  8857. }
  8858. // Stencil func
  8859. if (this._isStencilFuncDirty) {
  8860. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8861. this._isStencilFuncDirty = false;
  8862. }
  8863. // Stencil op
  8864. if (this._isStencilOpDirty) {
  8865. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8866. this._isStencilOpDirty = false;
  8867. }
  8868. };
  8869. return _StencilState;
  8870. }());
  8871. BABYLON._StencilState = _StencilState;
  8872. })(BABYLON || (BABYLON = {}));
  8873. //# sourceMappingURL=babylon.stencilState.js.map
  8874. var BABYLON;
  8875. (function (BABYLON) {
  8876. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8877. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8878. };
  8879. var compileRawShader = function (gl, source, type) {
  8880. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8881. gl.shaderSource(shader, source);
  8882. gl.compileShader(shader);
  8883. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8884. var log = gl.getShaderInfoLog(shader);
  8885. if (log) {
  8886. throw new Error(log);
  8887. }
  8888. }
  8889. if (!shader) {
  8890. throw new Error("Something went wrong while compile the shader.");
  8891. }
  8892. return shader;
  8893. };
  8894. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8895. var magFilter = gl.NEAREST;
  8896. var minFilter = gl.NEAREST;
  8897. switch (samplingMode) {
  8898. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8899. magFilter = gl.LINEAR;
  8900. if (generateMipMaps) {
  8901. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8902. }
  8903. else {
  8904. minFilter = gl.LINEAR;
  8905. }
  8906. break;
  8907. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8908. magFilter = gl.LINEAR;
  8909. if (generateMipMaps) {
  8910. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8911. }
  8912. else {
  8913. minFilter = gl.LINEAR;
  8914. }
  8915. break;
  8916. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8917. magFilter = gl.NEAREST;
  8918. if (generateMipMaps) {
  8919. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8920. }
  8921. else {
  8922. minFilter = gl.NEAREST;
  8923. }
  8924. break;
  8925. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8926. magFilter = gl.NEAREST;
  8927. if (generateMipMaps) {
  8928. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8929. }
  8930. else {
  8931. minFilter = gl.NEAREST;
  8932. }
  8933. break;
  8934. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8935. magFilter = gl.NEAREST;
  8936. if (generateMipMaps) {
  8937. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8938. }
  8939. else {
  8940. minFilter = gl.LINEAR;
  8941. }
  8942. break;
  8943. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8944. magFilter = gl.NEAREST;
  8945. if (generateMipMaps) {
  8946. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8947. }
  8948. else {
  8949. minFilter = gl.LINEAR;
  8950. }
  8951. break;
  8952. case BABYLON.Texture.NEAREST_LINEAR:
  8953. magFilter = gl.NEAREST;
  8954. minFilter = gl.LINEAR;
  8955. break;
  8956. case BABYLON.Texture.NEAREST_NEAREST:
  8957. magFilter = gl.NEAREST;
  8958. minFilter = gl.NEAREST;
  8959. break;
  8960. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8961. magFilter = gl.LINEAR;
  8962. if (generateMipMaps) {
  8963. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8964. }
  8965. else {
  8966. minFilter = gl.NEAREST;
  8967. }
  8968. break;
  8969. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8970. magFilter = gl.LINEAR;
  8971. if (generateMipMaps) {
  8972. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8973. }
  8974. else {
  8975. minFilter = gl.NEAREST;
  8976. }
  8977. break;
  8978. case BABYLON.Texture.LINEAR_LINEAR:
  8979. magFilter = gl.LINEAR;
  8980. minFilter = gl.LINEAR;
  8981. break;
  8982. case BABYLON.Texture.LINEAR_NEAREST:
  8983. magFilter = gl.LINEAR;
  8984. minFilter = gl.NEAREST;
  8985. break;
  8986. }
  8987. return {
  8988. min: minFilter,
  8989. mag: magFilter
  8990. };
  8991. };
  8992. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8993. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8994. var img;
  8995. var onload = function () {
  8996. loadedImages[index] = img;
  8997. loadedImages._internalCount++;
  8998. if (scene) {
  8999. scene._removePendingData(img);
  9000. }
  9001. if (loadedImages._internalCount === 6) {
  9002. onfinish(loadedImages);
  9003. }
  9004. };
  9005. var onerror = function (message, exception) {
  9006. if (scene) {
  9007. scene._removePendingData(img);
  9008. }
  9009. if (onErrorCallBack) {
  9010. onErrorCallBack(message, exception);
  9011. }
  9012. };
  9013. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9014. if (scene) {
  9015. scene._addPendingData(img);
  9016. }
  9017. };
  9018. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9019. if (onError === void 0) { onError = null; }
  9020. var loadedImages = [];
  9021. loadedImages._internalCount = 0;
  9022. for (var index = 0; index < 6; index++) {
  9023. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9024. }
  9025. };
  9026. var BufferPointer = /** @class */ (function () {
  9027. function BufferPointer() {
  9028. }
  9029. return BufferPointer;
  9030. }());
  9031. var InstancingAttributeInfo = /** @class */ (function () {
  9032. function InstancingAttributeInfo() {
  9033. }
  9034. return InstancingAttributeInfo;
  9035. }());
  9036. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9037. /**
  9038. * Define options used to create a render target texture
  9039. */
  9040. var RenderTargetCreationOptions = /** @class */ (function () {
  9041. function RenderTargetCreationOptions() {
  9042. }
  9043. return RenderTargetCreationOptions;
  9044. }());
  9045. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9046. /**
  9047. * Regroup several parameters relative to the browser in use
  9048. */
  9049. var EngineCapabilities = /** @class */ (function () {
  9050. function EngineCapabilities() {
  9051. }
  9052. return EngineCapabilities;
  9053. }());
  9054. BABYLON.EngineCapabilities = EngineCapabilities;
  9055. /**
  9056. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9057. */
  9058. var Engine = /** @class */ (function () {
  9059. /**
  9060. * @constructor
  9061. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9062. * @param antialias defines enable antialiasing (default: false)
  9063. * @param options defines further options to be sent to the getContext() function
  9064. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9065. */
  9066. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9067. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9068. var _this = this;
  9069. // Public members
  9070. this.forcePOTTextures = false;
  9071. this.isFullscreen = false;
  9072. this.isPointerLock = false;
  9073. this.cullBackFaces = true;
  9074. this.renderEvenInBackground = true;
  9075. this.preventCacheWipeBetweenFrames = false;
  9076. // To enable/disable IDB support and avoid XHR on .manifest
  9077. this.enableOfflineSupport = false;
  9078. this.scenes = new Array();
  9079. this.postProcesses = new Array();
  9080. // Observables
  9081. /**
  9082. * Observable event triggered each time the rendering canvas is resized
  9083. */
  9084. this.onResizeObservable = new BABYLON.Observable();
  9085. /**
  9086. * Observable event triggered each time the canvas loses focus
  9087. */
  9088. this.onCanvasBlurObservable = new BABYLON.Observable();
  9089. /**
  9090. * Observable event triggered each time the canvas gains focus
  9091. */
  9092. this.onCanvasFocusObservable = new BABYLON.Observable();
  9093. /**
  9094. * Observable event triggered each time the canvas receives pointerout event
  9095. */
  9096. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9097. /**
  9098. * Observable event triggered before each texture is initialized
  9099. */
  9100. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9101. //WebVR
  9102. this._vrDisplay = undefined;
  9103. this._vrSupported = false;
  9104. this._vrExclusivePointerMode = false;
  9105. // Uniform buffers list
  9106. this.disableUniformBuffers = false;
  9107. this._uniformBuffers = new Array();
  9108. // Observables
  9109. /**
  9110. * Observable raised when the engine begins a new frame
  9111. */
  9112. this.onBeginFrameObservable = new BABYLON.Observable();
  9113. /**
  9114. * Observable raised when the engine ends the current frame
  9115. */
  9116. this.onEndFrameObservable = new BABYLON.Observable();
  9117. /**
  9118. * Observable raised when the engine is about to compile a shader
  9119. */
  9120. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9121. /**
  9122. * Observable raised when the engine has jsut compiled a shader
  9123. */
  9124. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9125. this._windowIsBackground = false;
  9126. this._webGLVersion = 1.0;
  9127. this._badOS = false;
  9128. this._badDesktopOS = false;
  9129. /**
  9130. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9131. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9132. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9133. */
  9134. this.disableTextureBindingOptimization = false;
  9135. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9136. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9137. this.onVRRequestPresentStart = new BABYLON.Observable();
  9138. this._colorWrite = true;
  9139. this._drawCalls = new BABYLON.PerfCounter();
  9140. this._textureCollisions = new BABYLON.PerfCounter();
  9141. this._renderingQueueLaunched = false;
  9142. this._activeRenderLoops = new Array();
  9143. // Deterministic lockstepMaxSteps
  9144. this._deterministicLockstep = false;
  9145. this._lockstepMaxSteps = 4;
  9146. // Lost context
  9147. this.onContextLostObservable = new BABYLON.Observable();
  9148. this.onContextRestoredObservable = new BABYLON.Observable();
  9149. this._contextWasLost = false;
  9150. this._doNotHandleContextLost = false;
  9151. // FPS
  9152. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9153. this._fps = 60;
  9154. this._deltaTime = 0;
  9155. /**
  9156. * Turn this value on if you want to pause FPS computation when in background
  9157. */
  9158. this.disablePerformanceMonitorInBackground = false;
  9159. // States
  9160. this._depthCullingState = new BABYLON._DepthCullingState();
  9161. this._stencilState = new BABYLON._StencilState();
  9162. this._alphaState = new BABYLON._AlphaState();
  9163. this._alphaMode = Engine.ALPHA_DISABLE;
  9164. // Cache
  9165. this._internalTexturesCache = new Array();
  9166. this._activeChannel = 0;
  9167. this._currentTextureChannel = -1;
  9168. this._boundTexturesCache = {};
  9169. this._compiledEffects = {};
  9170. this._vertexAttribArraysEnabled = [];
  9171. this._uintIndicesCurrentlySet = false;
  9172. this._currentBoundBuffer = new Array();
  9173. this._currentBufferPointers = new Array();
  9174. this._currentInstanceLocations = new Array();
  9175. this._currentInstanceBuffers = new Array();
  9176. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9177. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9178. this._vaoRecordInProgress = false;
  9179. this._mustWipeVertexAttributes = false;
  9180. this._nextFreeTextureSlots = new Array();
  9181. this._maxSimultaneousTextures = 0;
  9182. this._activeRequests = new Array();
  9183. // Hardware supported Compressed Textures
  9184. this._texturesSupported = new Array();
  9185. this._onVRFullScreenTriggered = function () {
  9186. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9187. //get the old size before we change
  9188. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9189. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9190. //get the width and height, change the render size
  9191. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9192. _this.setHardwareScalingLevel(1);
  9193. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9194. }
  9195. else {
  9196. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9197. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9198. }
  9199. };
  9200. this._boundUniforms = {};
  9201. // Register promises
  9202. BABYLON.PromisePolyfill.Apply();
  9203. var canvas = null;
  9204. Engine.Instances.push(this);
  9205. if (!canvasOrContext) {
  9206. return;
  9207. }
  9208. options = options || {};
  9209. if (canvasOrContext.getContext) {
  9210. canvas = canvasOrContext;
  9211. this._renderingCanvas = canvas;
  9212. if (antialias != null) {
  9213. options.antialias = antialias;
  9214. }
  9215. if (options.deterministicLockstep === undefined) {
  9216. options.deterministicLockstep = false;
  9217. }
  9218. if (options.lockstepMaxSteps === undefined) {
  9219. options.lockstepMaxSteps = 4;
  9220. }
  9221. if (options.preserveDrawingBuffer === undefined) {
  9222. options.preserveDrawingBuffer = false;
  9223. }
  9224. if (options.audioEngine === undefined) {
  9225. options.audioEngine = true;
  9226. }
  9227. if (options.stencil === undefined) {
  9228. options.stencil = true;
  9229. }
  9230. this._deterministicLockstep = options.deterministicLockstep;
  9231. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9232. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9233. // Exceptions
  9234. if (navigator && navigator.userAgent) {
  9235. var ua = navigator.userAgent;
  9236. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9237. var exception = _a[_i];
  9238. var key = exception.key;
  9239. var targets = exception.targets;
  9240. if (ua.indexOf(key) > -1) {
  9241. if (exception.capture && exception.captureConstraint) {
  9242. var capture = exception.capture;
  9243. var constraint = exception.captureConstraint;
  9244. var regex = new RegExp(capture);
  9245. var matches = regex.exec(ua);
  9246. if (matches && matches.length > 0) {
  9247. var capturedValue = parseInt(matches[matches.length - 1]);
  9248. if (capturedValue >= constraint) {
  9249. continue;
  9250. }
  9251. }
  9252. }
  9253. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9254. var target = targets_1[_b];
  9255. switch (target) {
  9256. case "uniformBuffer":
  9257. this.disableUniformBuffers = true;
  9258. break;
  9259. case "textureBindingOptimization":
  9260. this.disableTextureBindingOptimization = true;
  9261. break;
  9262. }
  9263. }
  9264. break;
  9265. }
  9266. }
  9267. }
  9268. // GL
  9269. if (!options.disableWebGL2Support) {
  9270. try {
  9271. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9272. if (this._gl) {
  9273. this._webGLVersion = 2.0;
  9274. }
  9275. }
  9276. catch (e) {
  9277. // Do nothing
  9278. }
  9279. }
  9280. if (!this._gl) {
  9281. if (!canvas) {
  9282. throw new Error("The provided canvas is null or undefined.");
  9283. }
  9284. try {
  9285. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9286. }
  9287. catch (e) {
  9288. throw new Error("WebGL not supported");
  9289. }
  9290. }
  9291. if (!this._gl) {
  9292. throw new Error("WebGL not supported");
  9293. }
  9294. this._onCanvasFocus = function () {
  9295. _this.onCanvasFocusObservable.notifyObservers(_this);
  9296. };
  9297. this._onCanvasBlur = function () {
  9298. _this.onCanvasBlurObservable.notifyObservers(_this);
  9299. };
  9300. canvas.addEventListener("focus", this._onCanvasFocus);
  9301. canvas.addEventListener("blur", this._onCanvasBlur);
  9302. this._onBlur = function () {
  9303. if (_this.disablePerformanceMonitorInBackground) {
  9304. _this._performanceMonitor.disable();
  9305. }
  9306. _this._windowIsBackground = true;
  9307. };
  9308. this._onFocus = function () {
  9309. if (_this.disablePerformanceMonitorInBackground) {
  9310. _this._performanceMonitor.enable();
  9311. }
  9312. _this._windowIsBackground = false;
  9313. };
  9314. this._onCanvasPointerOut = function () {
  9315. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9316. };
  9317. window.addEventListener("blur", this._onBlur);
  9318. window.addEventListener("focus", this._onFocus);
  9319. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9320. // Context lost
  9321. if (!this._doNotHandleContextLost) {
  9322. this._onContextLost = function (evt) {
  9323. evt.preventDefault();
  9324. _this._contextWasLost = true;
  9325. BABYLON.Tools.Warn("WebGL context lost.");
  9326. _this.onContextLostObservable.notifyObservers(_this);
  9327. };
  9328. this._onContextRestored = function (evt) {
  9329. // Adding a timeout to avoid race condition at browser level
  9330. setTimeout(function () {
  9331. // Rebuild gl context
  9332. _this._initGLContext();
  9333. // Rebuild effects
  9334. _this._rebuildEffects();
  9335. // Rebuild textures
  9336. _this._rebuildInternalTextures();
  9337. // Rebuild buffers
  9338. _this._rebuildBuffers();
  9339. // Cache
  9340. _this.wipeCaches(true);
  9341. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9342. _this.onContextRestoredObservable.notifyObservers(_this);
  9343. _this._contextWasLost = false;
  9344. }, 0);
  9345. };
  9346. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9347. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9348. }
  9349. }
  9350. else {
  9351. this._gl = canvasOrContext;
  9352. this._renderingCanvas = this._gl.canvas;
  9353. if (this._gl.renderbufferStorageMultisample) {
  9354. this._webGLVersion = 2.0;
  9355. }
  9356. options.stencil = this._gl.getContextAttributes().stencil;
  9357. }
  9358. // Viewport
  9359. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9360. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9361. this.resize();
  9362. this._isStencilEnable = options.stencil ? true : false;
  9363. this._initGLContext();
  9364. if (canvas) {
  9365. // Fullscreen
  9366. this._onFullscreenChange = function () {
  9367. if (document.fullscreen !== undefined) {
  9368. _this.isFullscreen = document.fullscreen;
  9369. }
  9370. else if (document.mozFullScreen !== undefined) {
  9371. _this.isFullscreen = document.mozFullScreen;
  9372. }
  9373. else if (document.webkitIsFullScreen !== undefined) {
  9374. _this.isFullscreen = document.webkitIsFullScreen;
  9375. }
  9376. else if (document.msIsFullScreen !== undefined) {
  9377. _this.isFullscreen = document.msIsFullScreen;
  9378. }
  9379. // Pointer lock
  9380. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9381. canvas.requestPointerLock = canvas.requestPointerLock ||
  9382. canvas.msRequestPointerLock ||
  9383. canvas.mozRequestPointerLock ||
  9384. canvas.webkitRequestPointerLock;
  9385. if (canvas.requestPointerLock) {
  9386. canvas.requestPointerLock();
  9387. }
  9388. }
  9389. };
  9390. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9391. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9392. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9393. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9394. // Pointer lock
  9395. this._onPointerLockChange = function () {
  9396. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9397. document.webkitPointerLockElement === canvas ||
  9398. document.msPointerLockElement === canvas ||
  9399. document.pointerLockElement === canvas);
  9400. };
  9401. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9402. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9403. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9404. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9405. this._onVRDisplayPointerRestricted = function () {
  9406. if (canvas) {
  9407. canvas.requestPointerLock();
  9408. }
  9409. };
  9410. this._onVRDisplayPointerUnrestricted = function () {
  9411. document.exitPointerLock();
  9412. };
  9413. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9414. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9415. }
  9416. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9417. Engine.audioEngine = new BABYLON.AudioEngine();
  9418. }
  9419. // Prepare buffer pointers
  9420. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9421. this._currentBufferPointers[i] = new BufferPointer();
  9422. }
  9423. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9424. // Load WebVR Devices
  9425. if (options.autoEnableWebVR) {
  9426. this.initWebVR();
  9427. }
  9428. // Detect if we are running on a faulty buggy OS.
  9429. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9430. // Detect if we are running on a faulty buggy desktop OS.
  9431. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9432. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9433. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9434. }
  9435. Object.defineProperty(Engine, "LastCreatedEngine", {
  9436. get: function () {
  9437. if (Engine.Instances.length === 0) {
  9438. return null;
  9439. }
  9440. return Engine.Instances[Engine.Instances.length - 1];
  9441. },
  9442. enumerable: true,
  9443. configurable: true
  9444. });
  9445. Object.defineProperty(Engine, "LastCreatedScene", {
  9446. get: function () {
  9447. var lastCreatedEngine = Engine.LastCreatedEngine;
  9448. if (!lastCreatedEngine) {
  9449. return null;
  9450. }
  9451. if (lastCreatedEngine.scenes.length === 0) {
  9452. return null;
  9453. }
  9454. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9455. },
  9456. enumerable: true,
  9457. configurable: true
  9458. });
  9459. /**
  9460. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9461. */
  9462. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9463. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9464. var engine = Engine.Instances[engineIndex];
  9465. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9466. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9467. }
  9468. }
  9469. };
  9470. Object.defineProperty(Engine, "NEVER", {
  9471. get: function () {
  9472. return Engine._NEVER;
  9473. },
  9474. enumerable: true,
  9475. configurable: true
  9476. });
  9477. Object.defineProperty(Engine, "ALWAYS", {
  9478. get: function () {
  9479. return Engine._ALWAYS;
  9480. },
  9481. enumerable: true,
  9482. configurable: true
  9483. });
  9484. Object.defineProperty(Engine, "LESS", {
  9485. get: function () {
  9486. return Engine._LESS;
  9487. },
  9488. enumerable: true,
  9489. configurable: true
  9490. });
  9491. Object.defineProperty(Engine, "EQUAL", {
  9492. get: function () {
  9493. return Engine._EQUAL;
  9494. },
  9495. enumerable: true,
  9496. configurable: true
  9497. });
  9498. Object.defineProperty(Engine, "LEQUAL", {
  9499. get: function () {
  9500. return Engine._LEQUAL;
  9501. },
  9502. enumerable: true,
  9503. configurable: true
  9504. });
  9505. Object.defineProperty(Engine, "GREATER", {
  9506. get: function () {
  9507. return Engine._GREATER;
  9508. },
  9509. enumerable: true,
  9510. configurable: true
  9511. });
  9512. Object.defineProperty(Engine, "GEQUAL", {
  9513. get: function () {
  9514. return Engine._GEQUAL;
  9515. },
  9516. enumerable: true,
  9517. configurable: true
  9518. });
  9519. Object.defineProperty(Engine, "NOTEQUAL", {
  9520. get: function () {
  9521. return Engine._NOTEQUAL;
  9522. },
  9523. enumerable: true,
  9524. configurable: true
  9525. });
  9526. Object.defineProperty(Engine, "KEEP", {
  9527. get: function () {
  9528. return Engine._KEEP;
  9529. },
  9530. enumerable: true,
  9531. configurable: true
  9532. });
  9533. Object.defineProperty(Engine, "REPLACE", {
  9534. get: function () {
  9535. return Engine._REPLACE;
  9536. },
  9537. enumerable: true,
  9538. configurable: true
  9539. });
  9540. Object.defineProperty(Engine, "INCR", {
  9541. get: function () {
  9542. return Engine._INCR;
  9543. },
  9544. enumerable: true,
  9545. configurable: true
  9546. });
  9547. Object.defineProperty(Engine, "DECR", {
  9548. get: function () {
  9549. return Engine._DECR;
  9550. },
  9551. enumerable: true,
  9552. configurable: true
  9553. });
  9554. Object.defineProperty(Engine, "INVERT", {
  9555. get: function () {
  9556. return Engine._INVERT;
  9557. },
  9558. enumerable: true,
  9559. configurable: true
  9560. });
  9561. Object.defineProperty(Engine, "INCR_WRAP", {
  9562. get: function () {
  9563. return Engine._INCR_WRAP;
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. Object.defineProperty(Engine, "DECR_WRAP", {
  9569. get: function () {
  9570. return Engine._DECR_WRAP;
  9571. },
  9572. enumerable: true,
  9573. configurable: true
  9574. });
  9575. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9576. get: function () {
  9577. return Engine._ALPHA_DISABLE;
  9578. },
  9579. enumerable: true,
  9580. configurable: true
  9581. });
  9582. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9583. get: function () {
  9584. return Engine._ALPHA_ONEONE;
  9585. },
  9586. enumerable: true,
  9587. configurable: true
  9588. });
  9589. Object.defineProperty(Engine, "ALPHA_ADD", {
  9590. get: function () {
  9591. return Engine._ALPHA_ADD;
  9592. },
  9593. enumerable: true,
  9594. configurable: true
  9595. });
  9596. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9597. get: function () {
  9598. return Engine._ALPHA_COMBINE;
  9599. },
  9600. enumerable: true,
  9601. configurable: true
  9602. });
  9603. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9604. get: function () {
  9605. return Engine._ALPHA_SUBTRACT;
  9606. },
  9607. enumerable: true,
  9608. configurable: true
  9609. });
  9610. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9611. get: function () {
  9612. return Engine._ALPHA_MULTIPLY;
  9613. },
  9614. enumerable: true,
  9615. configurable: true
  9616. });
  9617. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9618. get: function () {
  9619. return Engine._ALPHA_MAXIMIZED;
  9620. },
  9621. enumerable: true,
  9622. configurable: true
  9623. });
  9624. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9625. get: function () {
  9626. return Engine._ALPHA_PREMULTIPLIED;
  9627. },
  9628. enumerable: true,
  9629. configurable: true
  9630. });
  9631. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9632. get: function () {
  9633. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9639. get: function () {
  9640. return Engine._ALPHA_INTERPOLATE;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9646. get: function () {
  9647. return Engine._ALPHA_SCREENMODE;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9653. get: function () {
  9654. return Engine._DELAYLOADSTATE_NONE;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9660. get: function () {
  9661. return Engine._DELAYLOADSTATE_LOADED;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9667. get: function () {
  9668. return Engine._DELAYLOADSTATE_LOADING;
  9669. },
  9670. enumerable: true,
  9671. configurable: true
  9672. });
  9673. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9674. get: function () {
  9675. return Engine._DELAYLOADSTATE_NOTLOADED;
  9676. },
  9677. enumerable: true,
  9678. configurable: true
  9679. });
  9680. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9681. get: function () {
  9682. return Engine._TEXTUREFORMAT_ALPHA;
  9683. },
  9684. enumerable: true,
  9685. configurable: true
  9686. });
  9687. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9688. get: function () {
  9689. return Engine._TEXTUREFORMAT_LUMINANCE;
  9690. },
  9691. enumerable: true,
  9692. configurable: true
  9693. });
  9694. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9695. get: function () {
  9696. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9697. },
  9698. enumerable: true,
  9699. configurable: true
  9700. });
  9701. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9702. get: function () {
  9703. return Engine._TEXTUREFORMAT_RGB;
  9704. },
  9705. enumerable: true,
  9706. configurable: true
  9707. });
  9708. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9709. get: function () {
  9710. return Engine._TEXTUREFORMAT_RGBA;
  9711. },
  9712. enumerable: true,
  9713. configurable: true
  9714. });
  9715. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9716. get: function () {
  9717. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9718. },
  9719. enumerable: true,
  9720. configurable: true
  9721. });
  9722. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9723. get: function () {
  9724. return Engine._TEXTURETYPE_FLOAT;
  9725. },
  9726. enumerable: true,
  9727. configurable: true
  9728. });
  9729. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9730. get: function () {
  9731. return Engine._TEXTURETYPE_HALF_FLOAT;
  9732. },
  9733. enumerable: true,
  9734. configurable: true
  9735. });
  9736. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9737. get: function () {
  9738. return Engine._SCALEMODE_FLOOR;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9744. get: function () {
  9745. return Engine._SCALEMODE_NEAREST;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9751. get: function () {
  9752. return Engine._SCALEMODE_CEILING;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Engine, "Version", {
  9758. get: function () {
  9759. return "3.2.0-alpha5";
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9765. get: function () {
  9766. return this._vrExclusivePointerMode;
  9767. },
  9768. enumerable: true,
  9769. configurable: true
  9770. });
  9771. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9772. get: function () {
  9773. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9774. },
  9775. enumerable: true,
  9776. configurable: true
  9777. });
  9778. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9779. get: function () {
  9780. return this._webGLVersion < 2 || this.forcePOTTextures;
  9781. },
  9782. enumerable: true,
  9783. configurable: true
  9784. });
  9785. Object.defineProperty(Engine.prototype, "badOS", {
  9786. get: function () {
  9787. return this._badOS;
  9788. },
  9789. enumerable: true,
  9790. configurable: true
  9791. });
  9792. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9793. get: function () {
  9794. return this._badDesktopOS;
  9795. },
  9796. enumerable: true,
  9797. configurable: true
  9798. });
  9799. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9800. get: function () {
  9801. return this._performanceMonitor;
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9807. get: function () {
  9808. return this._texturesSupported;
  9809. },
  9810. enumerable: true,
  9811. configurable: true
  9812. });
  9813. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9814. get: function () {
  9815. return this._textureFormatInUse;
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(Engine.prototype, "currentViewport", {
  9821. get: function () {
  9822. return this._cachedViewport;
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9828. // Empty texture
  9829. get: function () {
  9830. if (!this._emptyTexture) {
  9831. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9832. }
  9833. return this._emptyTexture;
  9834. },
  9835. enumerable: true,
  9836. configurable: true
  9837. });
  9838. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9839. get: function () {
  9840. if (!this._emptyTexture3D) {
  9841. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9842. }
  9843. return this._emptyTexture3D;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9849. get: function () {
  9850. if (!this._emptyCubeTexture) {
  9851. var faceData = new Uint8Array(4);
  9852. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9853. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9854. }
  9855. return this._emptyCubeTexture;
  9856. },
  9857. enumerable: true,
  9858. configurable: true
  9859. });
  9860. Engine.prototype._rebuildInternalTextures = function () {
  9861. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9862. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9863. var internalTexture = currentState_1[_i];
  9864. internalTexture._rebuild();
  9865. }
  9866. };
  9867. Engine.prototype._rebuildEffects = function () {
  9868. for (var key in this._compiledEffects) {
  9869. var effect = this._compiledEffects[key];
  9870. effect._prepareEffect();
  9871. }
  9872. BABYLON.Effect.ResetCache();
  9873. };
  9874. Engine.prototype._rebuildBuffers = function () {
  9875. // Index / Vertex
  9876. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9877. var scene = _a[_i];
  9878. scene.resetCachedMaterial();
  9879. scene._rebuildGeometries();
  9880. scene._rebuildTextures();
  9881. }
  9882. // Uniforms
  9883. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9884. var uniformBuffer = _c[_b];
  9885. uniformBuffer._rebuild();
  9886. }
  9887. };
  9888. Engine.prototype._initGLContext = function () {
  9889. // Caps
  9890. this._caps = new EngineCapabilities();
  9891. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9892. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9893. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9894. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9895. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9896. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9897. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9898. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9899. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9900. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9901. // Infos
  9902. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9903. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9904. if (rendererInfo != null) {
  9905. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9906. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9907. }
  9908. if (!this._glVendor) {
  9909. this._glVendor = "Unknown vendor";
  9910. }
  9911. if (!this._glRenderer) {
  9912. this._glRenderer = "Unknown renderer";
  9913. }
  9914. // Constants
  9915. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9916. if (this._gl.RGBA16F !== 0x881A) {
  9917. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9918. }
  9919. if (this._gl.RGBA32F !== 0x8814) {
  9920. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9921. }
  9922. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9923. this._gl.DEPTH24_STENCIL8 = 35056;
  9924. }
  9925. // Extensions
  9926. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9927. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9928. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9929. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9930. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9931. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9932. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9933. 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');
  9934. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9935. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9936. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9937. this._caps.highPrecisionShaderSupported = true;
  9938. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9939. if (this._caps.timerQuery) {
  9940. if (this._webGLVersion === 1) {
  9941. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9942. }
  9943. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9944. }
  9945. // Checks if some of the format renders first to allow the use of webgl inspector.
  9946. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9947. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9948. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9949. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9950. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9951. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9952. if (this._webGLVersion > 1) {
  9953. this._gl.HALF_FLOAT_OES = 0x140B;
  9954. }
  9955. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9956. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9957. // Draw buffers
  9958. if (this._webGLVersion > 1) {
  9959. this._caps.drawBuffersExtension = true;
  9960. }
  9961. else {
  9962. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9963. if (drawBuffersExtension !== null) {
  9964. this._caps.drawBuffersExtension = true;
  9965. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9966. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9967. for (var i = 0; i < 16; i++) {
  9968. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9969. }
  9970. }
  9971. else {
  9972. this._caps.drawBuffersExtension = false;
  9973. }
  9974. }
  9975. // Depth Texture
  9976. if (this._webGLVersion > 1) {
  9977. this._caps.depthTextureExtension = true;
  9978. }
  9979. else {
  9980. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9981. if (depthTextureExtension != null) {
  9982. this._caps.depthTextureExtension = true;
  9983. }
  9984. }
  9985. // Vertex array object
  9986. if (this._webGLVersion > 1) {
  9987. this._caps.vertexArrayObject = true;
  9988. }
  9989. else {
  9990. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9991. if (vertexArrayObjectExtension != null) {
  9992. this._caps.vertexArrayObject = true;
  9993. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9994. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9995. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9996. }
  9997. else {
  9998. this._caps.vertexArrayObject = false;
  9999. }
  10000. }
  10001. // Instances count
  10002. if (this._webGLVersion > 1) {
  10003. this._caps.instancedArrays = true;
  10004. }
  10005. else {
  10006. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10007. if (instanceExtension != null) {
  10008. this._caps.instancedArrays = true;
  10009. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10010. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10011. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10012. }
  10013. else {
  10014. this._caps.instancedArrays = false;
  10015. }
  10016. }
  10017. // Intelligently add supported compressed formats in order to check for.
  10018. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10019. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10020. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10021. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10022. if (this._caps.astc)
  10023. this.texturesSupported.push('-astc.ktx');
  10024. if (this._caps.s3tc)
  10025. this.texturesSupported.push('-dxt.ktx');
  10026. if (this._caps.pvrtc)
  10027. this.texturesSupported.push('-pvrtc.ktx');
  10028. if (this._caps.etc2)
  10029. this.texturesSupported.push('-etc2.ktx');
  10030. if (this._caps.etc1)
  10031. this.texturesSupported.push('-etc1.ktx');
  10032. if (this._gl.getShaderPrecisionFormat) {
  10033. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10034. if (highp) {
  10035. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10036. }
  10037. }
  10038. // Depth buffer
  10039. this.setDepthBuffer(true);
  10040. this.setDepthFunctionToLessOrEqual();
  10041. this.setDepthWrite(true);
  10042. // Texture maps
  10043. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10044. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10045. this._nextFreeTextureSlots.push(slot);
  10046. }
  10047. };
  10048. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10049. get: function () {
  10050. return this._webGLVersion;
  10051. },
  10052. enumerable: true,
  10053. configurable: true
  10054. });
  10055. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10056. /**
  10057. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10058. */
  10059. get: function () {
  10060. return this._isStencilEnable;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Engine.prototype._prepareWorkingCanvas = function () {
  10066. if (this._workingCanvas) {
  10067. return;
  10068. }
  10069. this._workingCanvas = document.createElement("canvas");
  10070. var context = this._workingCanvas.getContext("2d");
  10071. if (context) {
  10072. this._workingContext = context;
  10073. }
  10074. };
  10075. Engine.prototype.resetTextureCache = function () {
  10076. for (var key in this._boundTexturesCache) {
  10077. var boundTexture = this._boundTexturesCache[key];
  10078. if (boundTexture) {
  10079. this._removeDesignatedSlot(boundTexture);
  10080. }
  10081. this._boundTexturesCache[key] = null;
  10082. }
  10083. this._nextFreeTextureSlots = [];
  10084. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10085. this._nextFreeTextureSlots.push(slot);
  10086. }
  10087. this._currentTextureChannel = -1;
  10088. };
  10089. Engine.prototype.isDeterministicLockStep = function () {
  10090. return this._deterministicLockstep;
  10091. };
  10092. Engine.prototype.getLockstepMaxSteps = function () {
  10093. return this._lockstepMaxSteps;
  10094. };
  10095. Engine.prototype.getGlInfo = function () {
  10096. return {
  10097. vendor: this._glVendor,
  10098. renderer: this._glRenderer,
  10099. version: this._glVersion
  10100. };
  10101. };
  10102. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10103. if (useScreen === void 0) { useScreen = false; }
  10104. var viewport = camera.viewport;
  10105. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10106. };
  10107. Engine.prototype.getRenderWidth = function (useScreen) {
  10108. if (useScreen === void 0) { useScreen = false; }
  10109. if (!useScreen && this._currentRenderTarget) {
  10110. return this._currentRenderTarget.width;
  10111. }
  10112. return this._gl.drawingBufferWidth;
  10113. };
  10114. Engine.prototype.getRenderHeight = function (useScreen) {
  10115. if (useScreen === void 0) { useScreen = false; }
  10116. if (!useScreen && this._currentRenderTarget) {
  10117. return this._currentRenderTarget.height;
  10118. }
  10119. return this._gl.drawingBufferHeight;
  10120. };
  10121. Engine.prototype.getRenderingCanvas = function () {
  10122. return this._renderingCanvas;
  10123. };
  10124. Engine.prototype.getRenderingCanvasClientRect = function () {
  10125. if (!this._renderingCanvas) {
  10126. return null;
  10127. }
  10128. return this._renderingCanvas.getBoundingClientRect();
  10129. };
  10130. Engine.prototype.setHardwareScalingLevel = function (level) {
  10131. this._hardwareScalingLevel = level;
  10132. this.resize();
  10133. };
  10134. Engine.prototype.getHardwareScalingLevel = function () {
  10135. return this._hardwareScalingLevel;
  10136. };
  10137. Engine.prototype.getLoadedTexturesCache = function () {
  10138. return this._internalTexturesCache;
  10139. };
  10140. Engine.prototype.getCaps = function () {
  10141. return this._caps;
  10142. };
  10143. Object.defineProperty(Engine.prototype, "drawCalls", {
  10144. /** The number of draw calls submitted last frame */
  10145. get: function () {
  10146. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10147. return 0;
  10148. },
  10149. enumerable: true,
  10150. configurable: true
  10151. });
  10152. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10153. get: function () {
  10154. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10155. return null;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Engine.prototype.getDepthFunction = function () {
  10161. return this._depthCullingState.depthFunc;
  10162. };
  10163. Engine.prototype.setDepthFunction = function (depthFunc) {
  10164. this._depthCullingState.depthFunc = depthFunc;
  10165. };
  10166. Engine.prototype.setDepthFunctionToGreater = function () {
  10167. this._depthCullingState.depthFunc = this._gl.GREATER;
  10168. };
  10169. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10170. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10171. };
  10172. Engine.prototype.setDepthFunctionToLess = function () {
  10173. this._depthCullingState.depthFunc = this._gl.LESS;
  10174. };
  10175. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10176. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10177. };
  10178. Engine.prototype.getStencilBuffer = function () {
  10179. return this._stencilState.stencilTest;
  10180. };
  10181. Engine.prototype.setStencilBuffer = function (enable) {
  10182. this._stencilState.stencilTest = enable;
  10183. };
  10184. Engine.prototype.getStencilMask = function () {
  10185. return this._stencilState.stencilMask;
  10186. };
  10187. Engine.prototype.setStencilMask = function (mask) {
  10188. this._stencilState.stencilMask = mask;
  10189. };
  10190. Engine.prototype.getStencilFunction = function () {
  10191. return this._stencilState.stencilFunc;
  10192. };
  10193. Engine.prototype.getStencilFunctionReference = function () {
  10194. return this._stencilState.stencilFuncRef;
  10195. };
  10196. Engine.prototype.getStencilFunctionMask = function () {
  10197. return this._stencilState.stencilFuncMask;
  10198. };
  10199. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10200. this._stencilState.stencilFunc = stencilFunc;
  10201. };
  10202. Engine.prototype.setStencilFunctionReference = function (reference) {
  10203. this._stencilState.stencilFuncRef = reference;
  10204. };
  10205. Engine.prototype.setStencilFunctionMask = function (mask) {
  10206. this._stencilState.stencilFuncMask = mask;
  10207. };
  10208. Engine.prototype.getStencilOperationFail = function () {
  10209. return this._stencilState.stencilOpStencilFail;
  10210. };
  10211. Engine.prototype.getStencilOperationDepthFail = function () {
  10212. return this._stencilState.stencilOpDepthFail;
  10213. };
  10214. Engine.prototype.getStencilOperationPass = function () {
  10215. return this._stencilState.stencilOpStencilDepthPass;
  10216. };
  10217. Engine.prototype.setStencilOperationFail = function (operation) {
  10218. this._stencilState.stencilOpStencilFail = operation;
  10219. };
  10220. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10221. this._stencilState.stencilOpDepthFail = operation;
  10222. };
  10223. Engine.prototype.setStencilOperationPass = function (operation) {
  10224. this._stencilState.stencilOpStencilDepthPass = operation;
  10225. };
  10226. Engine.prototype.setDitheringState = function (value) {
  10227. if (value) {
  10228. this._gl.enable(this._gl.DITHER);
  10229. }
  10230. else {
  10231. this._gl.disable(this._gl.DITHER);
  10232. }
  10233. };
  10234. Engine.prototype.setRasterizerState = function (value) {
  10235. if (value) {
  10236. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10237. }
  10238. else {
  10239. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10240. }
  10241. };
  10242. /**
  10243. * stop executing a render loop function and remove it from the execution array
  10244. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10245. */
  10246. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10247. if (!renderFunction) {
  10248. this._activeRenderLoops = [];
  10249. return;
  10250. }
  10251. var index = this._activeRenderLoops.indexOf(renderFunction);
  10252. if (index >= 0) {
  10253. this._activeRenderLoops.splice(index, 1);
  10254. }
  10255. };
  10256. Engine.prototype._renderLoop = function () {
  10257. if (!this._contextWasLost) {
  10258. var shouldRender = true;
  10259. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10260. shouldRender = false;
  10261. }
  10262. if (shouldRender) {
  10263. // Start new frame
  10264. this.beginFrame();
  10265. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10266. var renderFunction = this._activeRenderLoops[index];
  10267. renderFunction();
  10268. }
  10269. // Present
  10270. this.endFrame();
  10271. }
  10272. }
  10273. if (this._activeRenderLoops.length > 0) {
  10274. // Register new frame
  10275. var requester = null;
  10276. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10277. requester = this._vrDisplay;
  10278. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10279. }
  10280. else {
  10281. this._renderingQueueLaunched = false;
  10282. }
  10283. };
  10284. /**
  10285. * Register and execute a render loop. The engine can have more than one render function.
  10286. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10287. * @example
  10288. * engine.runRenderLoop(function () {
  10289. * scene.render()
  10290. * })
  10291. */
  10292. Engine.prototype.runRenderLoop = function (renderFunction) {
  10293. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10294. return;
  10295. }
  10296. this._activeRenderLoops.push(renderFunction);
  10297. if (!this._renderingQueueLaunched) {
  10298. this._renderingQueueLaunched = true;
  10299. this._bindedRenderFunction = this._renderLoop.bind(this);
  10300. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10301. }
  10302. };
  10303. /**
  10304. * Toggle full screen mode.
  10305. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10306. * @param {any} options - an options object to be sent to the requestFullscreen function
  10307. */
  10308. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10309. if (this.isFullscreen) {
  10310. BABYLON.Tools.ExitFullscreen();
  10311. }
  10312. else {
  10313. this._pointerLockRequested = requestPointerLock;
  10314. if (this._renderingCanvas) {
  10315. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10316. }
  10317. }
  10318. };
  10319. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10320. if (stencil === void 0) { stencil = false; }
  10321. this.applyStates();
  10322. var mode = 0;
  10323. if (backBuffer && color) {
  10324. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10325. mode |= this._gl.COLOR_BUFFER_BIT;
  10326. }
  10327. if (depth) {
  10328. this._gl.clearDepth(1.0);
  10329. mode |= this._gl.DEPTH_BUFFER_BIT;
  10330. }
  10331. if (stencil) {
  10332. this._gl.clearStencil(0);
  10333. mode |= this._gl.STENCIL_BUFFER_BIT;
  10334. }
  10335. this._gl.clear(mode);
  10336. };
  10337. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10338. var gl = this._gl;
  10339. // Save state
  10340. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10341. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10342. // Change state
  10343. gl.enable(gl.SCISSOR_TEST);
  10344. gl.scissor(x, y, width, height);
  10345. // Clear
  10346. this.clear(clearColor, true, true, true);
  10347. // Restore state
  10348. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10349. if (curScissor === true) {
  10350. gl.enable(gl.SCISSOR_TEST);
  10351. }
  10352. else {
  10353. gl.disable(gl.SCISSOR_TEST);
  10354. }
  10355. };
  10356. /**
  10357. * Set the WebGL's viewport
  10358. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10359. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10360. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10361. */
  10362. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10363. var width = requiredWidth || this.getRenderWidth();
  10364. var height = requiredHeight || this.getRenderHeight();
  10365. var x = viewport.x || 0;
  10366. var y = viewport.y || 0;
  10367. this._cachedViewport = viewport;
  10368. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10369. };
  10370. /**
  10371. * Directly set the WebGL Viewport
  10372. * The x, y, width & height are directly passed to the WebGL call
  10373. * @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.
  10374. */
  10375. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10376. var currentViewport = this._cachedViewport;
  10377. this._cachedViewport = null;
  10378. this._gl.viewport(x, y, width, height);
  10379. return currentViewport;
  10380. };
  10381. Engine.prototype.beginFrame = function () {
  10382. this.onBeginFrameObservable.notifyObservers(this);
  10383. this._measureFps();
  10384. };
  10385. Engine.prototype.endFrame = function () {
  10386. //force a flush in case we are using a bad OS.
  10387. if (this._badOS) {
  10388. this.flushFramebuffer();
  10389. }
  10390. //submit frame to the vr device, if enabled
  10391. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10392. // TODO: We should only submit the frame if we read frameData successfully.
  10393. this._vrDisplay.submitFrame();
  10394. }
  10395. this.onEndFrameObservable.notifyObservers(this);
  10396. };
  10397. /**
  10398. * resize the view according to the canvas' size.
  10399. * @example
  10400. * window.addEventListener("resize", function () {
  10401. * engine.resize();
  10402. * });
  10403. */
  10404. Engine.prototype.resize = function () {
  10405. // We're not resizing the size of the canvas while in VR mode & presenting
  10406. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10407. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10408. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10409. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10410. }
  10411. };
  10412. /**
  10413. * force a specific size of the canvas
  10414. * @param {number} width - the new canvas' width
  10415. * @param {number} height - the new canvas' height
  10416. */
  10417. Engine.prototype.setSize = function (width, height) {
  10418. if (!this._renderingCanvas) {
  10419. return;
  10420. }
  10421. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10422. return;
  10423. }
  10424. this._renderingCanvas.width = width;
  10425. this._renderingCanvas.height = height;
  10426. for (var index = 0; index < this.scenes.length; index++) {
  10427. var scene = this.scenes[index];
  10428. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10429. var cam = scene.cameras[camIndex];
  10430. cam._currentRenderId = 0;
  10431. }
  10432. }
  10433. if (this.onResizeObservable.hasObservers) {
  10434. this.onResizeObservable.notifyObservers(this);
  10435. }
  10436. };
  10437. // WebVR functions
  10438. Engine.prototype.isVRDevicePresent = function () {
  10439. return !!this._vrDisplay;
  10440. };
  10441. Engine.prototype.getVRDevice = function () {
  10442. return this._vrDisplay;
  10443. };
  10444. Engine.prototype.initWebVR = function () {
  10445. var _this = this;
  10446. var notifyObservers = function () {
  10447. var eventArgs = {
  10448. vrDisplay: _this._vrDisplay,
  10449. vrSupported: _this._vrSupported
  10450. };
  10451. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10452. };
  10453. if (!this._onVrDisplayConnect) {
  10454. this._onVrDisplayConnect = function (event) {
  10455. _this._vrDisplay = event.display;
  10456. notifyObservers();
  10457. };
  10458. this._onVrDisplayDisconnect = function () {
  10459. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10460. _this._vrDisplay = undefined;
  10461. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10462. notifyObservers();
  10463. };
  10464. this._onVrDisplayPresentChange = function () {
  10465. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10466. };
  10467. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10468. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10469. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10470. }
  10471. this._getVRDisplays(notifyObservers);
  10472. return this.onVRDisplayChangedObservable;
  10473. };
  10474. Engine.prototype.enableVR = function () {
  10475. var _this = this;
  10476. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10477. var onResolved = function () {
  10478. _this.onVRRequestPresentComplete.notifyObservers(true);
  10479. _this._onVRFullScreenTriggered();
  10480. };
  10481. var onRejected = function () {
  10482. _this.onVRRequestPresentComplete.notifyObservers(false);
  10483. };
  10484. this.onVRRequestPresentStart.notifyObservers(this);
  10485. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10486. }
  10487. };
  10488. Engine.prototype.disableVR = function () {
  10489. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10490. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10491. }
  10492. };
  10493. Engine.prototype._getVRDisplays = function (callback) {
  10494. var _this = this;
  10495. var getWebVRDevices = function (devices) {
  10496. _this._vrSupported = true;
  10497. // note that devices may actually be an empty array. This is fine;
  10498. // we expect this._vrDisplay to be undefined in this case.
  10499. return _this._vrDisplay = devices[0];
  10500. };
  10501. if (navigator.getVRDisplays) {
  10502. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10503. // TODO: System CANNOT support WebVR, despite API presence.
  10504. _this._vrSupported = false;
  10505. callback();
  10506. });
  10507. }
  10508. else {
  10509. // TODO: Browser does not support WebVR
  10510. this._vrDisplay = undefined;
  10511. this._vrSupported = false;
  10512. callback();
  10513. }
  10514. };
  10515. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10516. if (this._currentRenderTarget) {
  10517. this.unBindFramebuffer(this._currentRenderTarget);
  10518. }
  10519. this._currentRenderTarget = texture;
  10520. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10521. var gl = this._gl;
  10522. if (texture.isCube) {
  10523. if (faceIndex === undefined) {
  10524. faceIndex = 0;
  10525. }
  10526. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10527. }
  10528. if (this._cachedViewport && !forceFullscreenViewport) {
  10529. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10530. }
  10531. else {
  10532. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10533. }
  10534. this.wipeCaches();
  10535. };
  10536. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10537. if (this._currentFramebuffer !== framebuffer) {
  10538. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10539. this._currentFramebuffer = framebuffer;
  10540. }
  10541. };
  10542. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10543. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10544. this._currentRenderTarget = null;
  10545. // If MSAA, we need to bitblt back to main texture
  10546. var gl = this._gl;
  10547. if (texture._MSAAFramebuffer) {
  10548. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10549. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10550. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10551. }
  10552. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10553. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10554. gl.generateMipmap(gl.TEXTURE_2D);
  10555. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10556. }
  10557. if (onBeforeUnbind) {
  10558. if (texture._MSAAFramebuffer) {
  10559. // Bind the correct framebuffer
  10560. this.bindUnboundFramebuffer(texture._framebuffer);
  10561. }
  10562. onBeforeUnbind();
  10563. }
  10564. this.bindUnboundFramebuffer(null);
  10565. };
  10566. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10567. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10568. this._currentRenderTarget = null;
  10569. // If MSAA, we need to bitblt back to main texture
  10570. var gl = this._gl;
  10571. if (textures[0]._MSAAFramebuffer) {
  10572. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10573. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10574. var attachments = textures[0]._attachments;
  10575. if (!attachments) {
  10576. attachments = new Array(textures.length);
  10577. textures[0]._attachments = attachments;
  10578. }
  10579. for (var i = 0; i < textures.length; i++) {
  10580. var texture = textures[i];
  10581. for (var j = 0; j < attachments.length; j++) {
  10582. attachments[j] = gl.NONE;
  10583. }
  10584. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10585. gl.readBuffer(attachments[i]);
  10586. gl.drawBuffers(attachments);
  10587. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10588. }
  10589. for (var i = 0; i < attachments.length; i++) {
  10590. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10591. }
  10592. gl.drawBuffers(attachments);
  10593. }
  10594. for (var i = 0; i < textures.length; i++) {
  10595. var texture = textures[i];
  10596. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10597. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10598. gl.generateMipmap(gl.TEXTURE_2D);
  10599. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10600. }
  10601. }
  10602. if (onBeforeUnbind) {
  10603. if (textures[0]._MSAAFramebuffer) {
  10604. // Bind the correct framebuffer
  10605. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10606. }
  10607. onBeforeUnbind();
  10608. }
  10609. this.bindUnboundFramebuffer(null);
  10610. };
  10611. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10612. if (texture.generateMipMaps) {
  10613. var gl = this._gl;
  10614. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10615. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10616. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10617. }
  10618. };
  10619. Engine.prototype.flushFramebuffer = function () {
  10620. this._gl.flush();
  10621. };
  10622. Engine.prototype.restoreDefaultFramebuffer = function () {
  10623. if (this._currentRenderTarget) {
  10624. this.unBindFramebuffer(this._currentRenderTarget);
  10625. }
  10626. else {
  10627. this.bindUnboundFramebuffer(null);
  10628. }
  10629. if (this._cachedViewport) {
  10630. this.setViewport(this._cachedViewport);
  10631. }
  10632. this.wipeCaches();
  10633. };
  10634. // UBOs
  10635. Engine.prototype.createUniformBuffer = function (elements) {
  10636. var ubo = this._gl.createBuffer();
  10637. if (!ubo) {
  10638. throw new Error("Unable to create uniform buffer");
  10639. }
  10640. this.bindUniformBuffer(ubo);
  10641. if (elements instanceof Float32Array) {
  10642. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10643. }
  10644. else {
  10645. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10646. }
  10647. this.bindUniformBuffer(null);
  10648. ubo.references = 1;
  10649. return ubo;
  10650. };
  10651. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10652. var ubo = this._gl.createBuffer();
  10653. if (!ubo) {
  10654. throw new Error("Unable to create dynamic uniform buffer");
  10655. }
  10656. this.bindUniformBuffer(ubo);
  10657. if (elements instanceof Float32Array) {
  10658. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10659. }
  10660. else {
  10661. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10662. }
  10663. this.bindUniformBuffer(null);
  10664. ubo.references = 1;
  10665. return ubo;
  10666. };
  10667. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10668. this.bindUniformBuffer(uniformBuffer);
  10669. if (offset === undefined) {
  10670. offset = 0;
  10671. }
  10672. if (count === undefined) {
  10673. if (elements instanceof Float32Array) {
  10674. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10675. }
  10676. else {
  10677. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10678. }
  10679. }
  10680. else {
  10681. if (elements instanceof Float32Array) {
  10682. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10683. }
  10684. else {
  10685. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10686. }
  10687. }
  10688. this.bindUniformBuffer(null);
  10689. };
  10690. // VBOs
  10691. Engine.prototype._resetVertexBufferBinding = function () {
  10692. this.bindArrayBuffer(null);
  10693. this._cachedVertexBuffers = null;
  10694. };
  10695. Engine.prototype.createVertexBuffer = function (vertices) {
  10696. var vbo = this._gl.createBuffer();
  10697. if (!vbo) {
  10698. throw new Error("Unable to create vertex buffer");
  10699. }
  10700. this.bindArrayBuffer(vbo);
  10701. if (vertices instanceof Float32Array) {
  10702. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10703. }
  10704. else {
  10705. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10706. }
  10707. this._resetVertexBufferBinding();
  10708. vbo.references = 1;
  10709. return vbo;
  10710. };
  10711. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10712. var vbo = this._gl.createBuffer();
  10713. if (!vbo) {
  10714. throw new Error("Unable to create dynamic vertex buffer");
  10715. }
  10716. this.bindArrayBuffer(vbo);
  10717. if (vertices instanceof Float32Array) {
  10718. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10719. }
  10720. else {
  10721. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10722. }
  10723. this._resetVertexBufferBinding();
  10724. vbo.references = 1;
  10725. return vbo;
  10726. };
  10727. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10728. if (offset === void 0) { offset = 0; }
  10729. // Force cache update
  10730. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10731. this.bindIndexBuffer(indexBuffer);
  10732. var arrayBuffer;
  10733. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10734. arrayBuffer = indices;
  10735. }
  10736. else {
  10737. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10738. }
  10739. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10740. this._resetIndexBufferBinding();
  10741. };
  10742. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10743. this.bindArrayBuffer(vertexBuffer);
  10744. if (offset === undefined) {
  10745. offset = 0;
  10746. }
  10747. if (count === undefined) {
  10748. if (vertices instanceof Float32Array) {
  10749. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10750. }
  10751. else {
  10752. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10753. }
  10754. }
  10755. else {
  10756. if (vertices instanceof Float32Array) {
  10757. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10758. }
  10759. else {
  10760. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10761. }
  10762. }
  10763. this._resetVertexBufferBinding();
  10764. };
  10765. Engine.prototype._resetIndexBufferBinding = function () {
  10766. this.bindIndexBuffer(null);
  10767. this._cachedIndexBuffer = null;
  10768. };
  10769. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10770. var vbo = this._gl.createBuffer();
  10771. if (!vbo) {
  10772. throw new Error("Unable to create index buffer");
  10773. }
  10774. this.bindIndexBuffer(vbo);
  10775. // Check for 32 bits indices
  10776. var arrayBuffer;
  10777. var need32Bits = false;
  10778. if (indices instanceof Uint16Array) {
  10779. arrayBuffer = indices;
  10780. }
  10781. else {
  10782. //check 32 bit support
  10783. if (this._caps.uintIndices) {
  10784. if (indices instanceof Uint32Array) {
  10785. arrayBuffer = indices;
  10786. need32Bits = true;
  10787. }
  10788. else {
  10789. //number[] or Int32Array, check if 32 bit is necessary
  10790. for (var index = 0; index < indices.length; index++) {
  10791. if (indices[index] > 65535) {
  10792. need32Bits = true;
  10793. break;
  10794. }
  10795. }
  10796. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10797. }
  10798. }
  10799. else {
  10800. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10801. arrayBuffer = new Uint16Array(indices);
  10802. }
  10803. }
  10804. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10805. this._resetIndexBufferBinding();
  10806. vbo.references = 1;
  10807. vbo.is32Bits = need32Bits;
  10808. return vbo;
  10809. };
  10810. Engine.prototype.bindArrayBuffer = function (buffer) {
  10811. if (!this._vaoRecordInProgress) {
  10812. this._unbindVertexArrayObject();
  10813. }
  10814. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10815. };
  10816. Engine.prototype.bindUniformBuffer = function (buffer) {
  10817. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10818. };
  10819. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10820. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10821. };
  10822. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10823. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10824. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10825. };
  10826. ;
  10827. Engine.prototype.bindIndexBuffer = function (buffer) {
  10828. if (!this._vaoRecordInProgress) {
  10829. this._unbindVertexArrayObject();
  10830. }
  10831. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10832. };
  10833. Engine.prototype.bindBuffer = function (buffer, target) {
  10834. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10835. this._gl.bindBuffer(target, buffer);
  10836. this._currentBoundBuffer[target] = buffer;
  10837. }
  10838. };
  10839. Engine.prototype.updateArrayBuffer = function (data) {
  10840. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10841. };
  10842. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10843. var pointer = this._currentBufferPointers[indx];
  10844. var changed = false;
  10845. if (!pointer.active) {
  10846. changed = true;
  10847. pointer.active = true;
  10848. pointer.index = indx;
  10849. pointer.size = size;
  10850. pointer.type = type;
  10851. pointer.normalized = normalized;
  10852. pointer.stride = stride;
  10853. pointer.offset = offset;
  10854. pointer.buffer = buffer;
  10855. }
  10856. else {
  10857. if (pointer.buffer !== buffer) {
  10858. pointer.buffer = buffer;
  10859. changed = true;
  10860. }
  10861. if (pointer.size !== size) {
  10862. pointer.size = size;
  10863. changed = true;
  10864. }
  10865. if (pointer.type !== type) {
  10866. pointer.type = type;
  10867. changed = true;
  10868. }
  10869. if (pointer.normalized !== normalized) {
  10870. pointer.normalized = normalized;
  10871. changed = true;
  10872. }
  10873. if (pointer.stride !== stride) {
  10874. pointer.stride = stride;
  10875. changed = true;
  10876. }
  10877. if (pointer.offset !== offset) {
  10878. pointer.offset = offset;
  10879. changed = true;
  10880. }
  10881. }
  10882. if (changed || this._vaoRecordInProgress) {
  10883. this.bindArrayBuffer(buffer);
  10884. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10885. }
  10886. };
  10887. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10888. if (indexBuffer == null) {
  10889. return;
  10890. }
  10891. if (this._cachedIndexBuffer !== indexBuffer) {
  10892. this._cachedIndexBuffer = indexBuffer;
  10893. this.bindIndexBuffer(indexBuffer);
  10894. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10895. }
  10896. };
  10897. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10898. var attributes = effect.getAttributesNames();
  10899. if (!this._vaoRecordInProgress) {
  10900. this._unbindVertexArrayObject();
  10901. }
  10902. this.unbindAllAttributes();
  10903. for (var index = 0; index < attributes.length; index++) {
  10904. var order = effect.getAttributeLocation(index);
  10905. if (order >= 0) {
  10906. var vertexBuffer = vertexBuffers[attributes[index]];
  10907. if (!vertexBuffer) {
  10908. continue;
  10909. }
  10910. this._gl.enableVertexAttribArray(order);
  10911. if (!this._vaoRecordInProgress) {
  10912. this._vertexAttribArraysEnabled[order] = true;
  10913. }
  10914. var buffer = vertexBuffer.getBuffer();
  10915. if (buffer) {
  10916. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10917. if (vertexBuffer.getIsInstanced()) {
  10918. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10919. if (!this._vaoRecordInProgress) {
  10920. this._currentInstanceLocations.push(order);
  10921. this._currentInstanceBuffers.push(buffer);
  10922. }
  10923. }
  10924. }
  10925. }
  10926. }
  10927. };
  10928. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10929. var vao = this._gl.createVertexArray();
  10930. this._vaoRecordInProgress = true;
  10931. this._gl.bindVertexArray(vao);
  10932. this._mustWipeVertexAttributes = true;
  10933. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10934. this.bindIndexBuffer(indexBuffer);
  10935. this._vaoRecordInProgress = false;
  10936. this._gl.bindVertexArray(null);
  10937. return vao;
  10938. };
  10939. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10940. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10941. this._cachedVertexArrayObject = vertexArrayObject;
  10942. this._gl.bindVertexArray(vertexArrayObject);
  10943. this._cachedVertexBuffers = null;
  10944. this._cachedIndexBuffer = null;
  10945. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10946. this._mustWipeVertexAttributes = true;
  10947. }
  10948. };
  10949. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10950. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10951. this._cachedVertexBuffers = vertexBuffer;
  10952. this._cachedEffectForVertexBuffers = effect;
  10953. var attributesCount = effect.getAttributesCount();
  10954. this._unbindVertexArrayObject();
  10955. this.unbindAllAttributes();
  10956. var offset = 0;
  10957. for (var index = 0; index < attributesCount; index++) {
  10958. if (index < vertexDeclaration.length) {
  10959. var order = effect.getAttributeLocation(index);
  10960. if (order >= 0) {
  10961. this._gl.enableVertexAttribArray(order);
  10962. this._vertexAttribArraysEnabled[order] = true;
  10963. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10964. }
  10965. offset += vertexDeclaration[index] * 4;
  10966. }
  10967. }
  10968. }
  10969. this._bindIndexBufferWithCache(indexBuffer);
  10970. };
  10971. Engine.prototype._unbindVertexArrayObject = function () {
  10972. if (!this._cachedVertexArrayObject) {
  10973. return;
  10974. }
  10975. this._cachedVertexArrayObject = null;
  10976. this._gl.bindVertexArray(null);
  10977. };
  10978. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10979. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10980. this._cachedVertexBuffers = vertexBuffers;
  10981. this._cachedEffectForVertexBuffers = effect;
  10982. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10983. }
  10984. this._bindIndexBufferWithCache(indexBuffer);
  10985. };
  10986. Engine.prototype.unbindInstanceAttributes = function () {
  10987. var boundBuffer;
  10988. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10989. var instancesBuffer = this._currentInstanceBuffers[i];
  10990. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10991. boundBuffer = instancesBuffer;
  10992. this.bindArrayBuffer(instancesBuffer);
  10993. }
  10994. var offsetLocation = this._currentInstanceLocations[i];
  10995. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10996. }
  10997. this._currentInstanceBuffers.length = 0;
  10998. this._currentInstanceLocations.length = 0;
  10999. };
  11000. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11001. this._gl.deleteVertexArray(vao);
  11002. };
  11003. Engine.prototype._releaseBuffer = function (buffer) {
  11004. buffer.references--;
  11005. if (buffer.references === 0) {
  11006. this._gl.deleteBuffer(buffer);
  11007. return true;
  11008. }
  11009. return false;
  11010. };
  11011. Engine.prototype.createInstancesBuffer = function (capacity) {
  11012. var buffer = this._gl.createBuffer();
  11013. if (!buffer) {
  11014. throw new Error("Unable to create instance buffer");
  11015. }
  11016. buffer.capacity = capacity;
  11017. this.bindArrayBuffer(buffer);
  11018. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11019. return buffer;
  11020. };
  11021. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11022. this._gl.deleteBuffer(buffer);
  11023. };
  11024. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11025. this.bindArrayBuffer(instancesBuffer);
  11026. if (data) {
  11027. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11028. }
  11029. if (offsetLocations[0].index !== undefined) {
  11030. var stride = 0;
  11031. for (var i = 0; i < offsetLocations.length; i++) {
  11032. var ai = offsetLocations[i];
  11033. stride += ai.attributeSize * 4;
  11034. }
  11035. for (var i = 0; i < offsetLocations.length; i++) {
  11036. var ai = offsetLocations[i];
  11037. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11038. this._gl.enableVertexAttribArray(ai.index);
  11039. this._vertexAttribArraysEnabled[ai.index] = true;
  11040. }
  11041. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11042. this._gl.vertexAttribDivisor(ai.index, 1);
  11043. this._currentInstanceLocations.push(ai.index);
  11044. this._currentInstanceBuffers.push(instancesBuffer);
  11045. }
  11046. }
  11047. else {
  11048. for (var index = 0; index < 4; index++) {
  11049. var offsetLocation = offsetLocations[index];
  11050. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11051. this._gl.enableVertexAttribArray(offsetLocation);
  11052. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11053. }
  11054. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11055. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11056. this._currentInstanceLocations.push(offsetLocation);
  11057. this._currentInstanceBuffers.push(instancesBuffer);
  11058. }
  11059. }
  11060. };
  11061. Engine.prototype.applyStates = function () {
  11062. this._depthCullingState.apply(this._gl);
  11063. this._stencilState.apply(this._gl);
  11064. this._alphaState.apply(this._gl);
  11065. };
  11066. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11067. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11068. };
  11069. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11070. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11071. };
  11072. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11073. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11074. };
  11075. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11076. // Apply states
  11077. this.applyStates();
  11078. this._drawCalls.addCount(1, false);
  11079. // Render
  11080. var drawMode = this.DrawMode(fillMode);
  11081. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11082. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11083. if (instancesCount) {
  11084. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11085. }
  11086. else {
  11087. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11088. }
  11089. };
  11090. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11091. // Apply states
  11092. this.applyStates();
  11093. this._drawCalls.addCount(1, false);
  11094. var drawMode = this.DrawMode(fillMode);
  11095. if (instancesCount) {
  11096. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11097. }
  11098. else {
  11099. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11100. }
  11101. };
  11102. Engine.prototype.DrawMode = function (fillMode) {
  11103. switch (fillMode) {
  11104. // Triangle views
  11105. case BABYLON.Material.TriangleFillMode:
  11106. return this._gl.TRIANGLES;
  11107. case BABYLON.Material.PointFillMode:
  11108. return this._gl.POINTS;
  11109. case BABYLON.Material.WireFrameFillMode:
  11110. return this._gl.LINES;
  11111. // Draw modes
  11112. case BABYLON.Material.PointListDrawMode:
  11113. return this._gl.POINTS;
  11114. case BABYLON.Material.LineListDrawMode:
  11115. return this._gl.LINES;
  11116. case BABYLON.Material.LineLoopDrawMode:
  11117. return this._gl.LINE_LOOP;
  11118. case BABYLON.Material.LineStripDrawMode:
  11119. return this._gl.LINE_STRIP;
  11120. case BABYLON.Material.TriangleStripDrawMode:
  11121. return this._gl.TRIANGLE_STRIP;
  11122. case BABYLON.Material.TriangleFanDrawMode:
  11123. return this._gl.TRIANGLE_FAN;
  11124. default:
  11125. return this._gl.TRIANGLES;
  11126. }
  11127. };
  11128. // Shaders
  11129. Engine.prototype._releaseEffect = function (effect) {
  11130. if (this._compiledEffects[effect._key]) {
  11131. delete this._compiledEffects[effect._key];
  11132. this._deleteProgram(effect.getProgram());
  11133. }
  11134. };
  11135. Engine.prototype._deleteProgram = function (program) {
  11136. if (program) {
  11137. program.__SPECTOR_rebuildProgram = null;
  11138. if (program.transformFeedback) {
  11139. this.deleteTransformFeedback(program.transformFeedback);
  11140. program.transformFeedback = null;
  11141. }
  11142. this._gl.deleteProgram(program);
  11143. }
  11144. };
  11145. /**
  11146. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11147. * @param samplers An array of string used to represent textures
  11148. */
  11149. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11150. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11151. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11152. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11153. if (this._compiledEffects[name]) {
  11154. var compiledEffect = this._compiledEffects[name];
  11155. if (onCompiled && compiledEffect.isReady()) {
  11156. onCompiled(compiledEffect);
  11157. }
  11158. return compiledEffect;
  11159. }
  11160. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11161. effect._key = name;
  11162. this._compiledEffects[name] = effect;
  11163. return effect;
  11164. };
  11165. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11166. if (uniformsNames === void 0) { uniformsNames = []; }
  11167. if (samplers === void 0) { samplers = []; }
  11168. if (defines === void 0) { defines = ""; }
  11169. return this.createEffect({
  11170. vertex: "particles",
  11171. fragmentElement: fragmentName
  11172. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11173. };
  11174. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11175. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11176. context = context || this._gl;
  11177. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11178. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11179. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11180. };
  11181. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11182. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11183. context = context || this._gl;
  11184. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11185. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11186. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11187. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11188. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11189. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11190. return program;
  11191. };
  11192. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11193. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11194. var shaderProgram = context.createProgram();
  11195. if (!shaderProgram) {
  11196. throw new Error("Unable to create program");
  11197. }
  11198. context.attachShader(shaderProgram, vertexShader);
  11199. context.attachShader(shaderProgram, fragmentShader);
  11200. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11201. var transformFeedback = this.createTransformFeedback();
  11202. this.bindTransformFeedback(transformFeedback);
  11203. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11204. shaderProgram.transformFeedback = transformFeedback;
  11205. }
  11206. context.linkProgram(shaderProgram);
  11207. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11208. this.bindTransformFeedback(null);
  11209. }
  11210. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11211. if (!linked) {
  11212. context.validateProgram(shaderProgram);
  11213. var error = context.getProgramInfoLog(shaderProgram);
  11214. if (error) {
  11215. throw new Error(error);
  11216. }
  11217. }
  11218. context.deleteShader(vertexShader);
  11219. context.deleteShader(fragmentShader);
  11220. return shaderProgram;
  11221. };
  11222. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11223. var results = new Array();
  11224. for (var index = 0; index < uniformsNames.length; index++) {
  11225. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11226. }
  11227. return results;
  11228. };
  11229. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11230. var results = [];
  11231. for (var index = 0; index < attributesNames.length; index++) {
  11232. try {
  11233. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11234. }
  11235. catch (e) {
  11236. results.push(-1);
  11237. }
  11238. }
  11239. return results;
  11240. };
  11241. Engine.prototype.enableEffect = function (effect) {
  11242. if (!effect) {
  11243. return;
  11244. }
  11245. // Use program
  11246. this.bindSamplers(effect);
  11247. this._currentEffect = effect;
  11248. if (effect.onBind) {
  11249. effect.onBind(effect);
  11250. }
  11251. effect.onBindObservable.notifyObservers(effect);
  11252. };
  11253. Engine.prototype.setIntArray = function (uniform, array) {
  11254. if (!uniform)
  11255. return;
  11256. this._gl.uniform1iv(uniform, array);
  11257. };
  11258. Engine.prototype.setIntArray2 = function (uniform, array) {
  11259. if (!uniform || array.length % 2 !== 0)
  11260. return;
  11261. this._gl.uniform2iv(uniform, array);
  11262. };
  11263. Engine.prototype.setIntArray3 = function (uniform, array) {
  11264. if (!uniform || array.length % 3 !== 0)
  11265. return;
  11266. this._gl.uniform3iv(uniform, array);
  11267. };
  11268. Engine.prototype.setIntArray4 = function (uniform, array) {
  11269. if (!uniform || array.length % 4 !== 0)
  11270. return;
  11271. this._gl.uniform4iv(uniform, array);
  11272. };
  11273. Engine.prototype.setFloatArray = function (uniform, array) {
  11274. if (!uniform)
  11275. return;
  11276. this._gl.uniform1fv(uniform, array);
  11277. };
  11278. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11279. if (!uniform || array.length % 2 !== 0)
  11280. return;
  11281. this._gl.uniform2fv(uniform, array);
  11282. };
  11283. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11284. if (!uniform || array.length % 3 !== 0)
  11285. return;
  11286. this._gl.uniform3fv(uniform, array);
  11287. };
  11288. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11289. if (!uniform || array.length % 4 !== 0)
  11290. return;
  11291. this._gl.uniform4fv(uniform, array);
  11292. };
  11293. Engine.prototype.setArray = function (uniform, array) {
  11294. if (!uniform)
  11295. return;
  11296. this._gl.uniform1fv(uniform, array);
  11297. };
  11298. Engine.prototype.setArray2 = function (uniform, array) {
  11299. if (!uniform || array.length % 2 !== 0)
  11300. return;
  11301. this._gl.uniform2fv(uniform, array);
  11302. };
  11303. Engine.prototype.setArray3 = function (uniform, array) {
  11304. if (!uniform || array.length % 3 !== 0)
  11305. return;
  11306. this._gl.uniform3fv(uniform, array);
  11307. };
  11308. Engine.prototype.setArray4 = function (uniform, array) {
  11309. if (!uniform || array.length % 4 !== 0)
  11310. return;
  11311. this._gl.uniform4fv(uniform, array);
  11312. };
  11313. Engine.prototype.setMatrices = function (uniform, matrices) {
  11314. if (!uniform)
  11315. return;
  11316. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11317. };
  11318. Engine.prototype.setMatrix = function (uniform, matrix) {
  11319. if (!uniform)
  11320. return;
  11321. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11322. };
  11323. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11324. if (!uniform)
  11325. return;
  11326. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11327. };
  11328. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11329. if (!uniform)
  11330. return;
  11331. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11332. };
  11333. Engine.prototype.setInt = function (uniform, value) {
  11334. if (!uniform)
  11335. return;
  11336. this._gl.uniform1i(uniform, value);
  11337. };
  11338. Engine.prototype.setFloat = function (uniform, value) {
  11339. if (!uniform)
  11340. return;
  11341. this._gl.uniform1f(uniform, value);
  11342. };
  11343. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11344. if (!uniform)
  11345. return;
  11346. this._gl.uniform2f(uniform, x, y);
  11347. };
  11348. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11349. if (!uniform)
  11350. return;
  11351. this._gl.uniform3f(uniform, x, y, z);
  11352. };
  11353. Engine.prototype.setBool = function (uniform, bool) {
  11354. if (!uniform)
  11355. return;
  11356. this._gl.uniform1i(uniform, bool);
  11357. };
  11358. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11359. if (!uniform)
  11360. return;
  11361. this._gl.uniform4f(uniform, x, y, z, w);
  11362. };
  11363. Engine.prototype.setColor3 = function (uniform, color3) {
  11364. if (!uniform)
  11365. return;
  11366. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11367. };
  11368. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11369. if (!uniform)
  11370. return;
  11371. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11372. };
  11373. // States
  11374. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11375. if (zOffset === void 0) { zOffset = 0; }
  11376. if (reverseSide === void 0) { reverseSide = false; }
  11377. // Culling
  11378. if (this._depthCullingState.cull !== culling || force) {
  11379. this._depthCullingState.cull = culling;
  11380. }
  11381. // Cull face
  11382. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11383. if (this._depthCullingState.cullFace !== cullFace || force) {
  11384. this._depthCullingState.cullFace = cullFace;
  11385. }
  11386. // Z offset
  11387. this.setZOffset(zOffset);
  11388. // Front face
  11389. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11390. if (this._depthCullingState.frontFace !== frontFace || force) {
  11391. this._depthCullingState.frontFace = frontFace;
  11392. }
  11393. };
  11394. Engine.prototype.setZOffset = function (value) {
  11395. this._depthCullingState.zOffset = value;
  11396. };
  11397. Engine.prototype.getZOffset = function () {
  11398. return this._depthCullingState.zOffset;
  11399. };
  11400. Engine.prototype.setDepthBuffer = function (enable) {
  11401. this._depthCullingState.depthTest = enable;
  11402. };
  11403. Engine.prototype.getDepthWrite = function () {
  11404. return this._depthCullingState.depthMask;
  11405. };
  11406. Engine.prototype.setDepthWrite = function (enable) {
  11407. this._depthCullingState.depthMask = enable;
  11408. };
  11409. Engine.prototype.setColorWrite = function (enable) {
  11410. this._gl.colorMask(enable, enable, enable, enable);
  11411. this._colorWrite = enable;
  11412. };
  11413. Engine.prototype.getColorWrite = function () {
  11414. return this._colorWrite;
  11415. };
  11416. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11417. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11418. };
  11419. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11420. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11421. if (this._alphaMode === mode) {
  11422. return;
  11423. }
  11424. switch (mode) {
  11425. case Engine.ALPHA_DISABLE:
  11426. this._alphaState.alphaBlend = false;
  11427. break;
  11428. case Engine.ALPHA_PREMULTIPLIED:
  11429. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11430. this._alphaState.alphaBlend = true;
  11431. break;
  11432. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11433. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11434. this._alphaState.alphaBlend = true;
  11435. break;
  11436. case Engine.ALPHA_COMBINE:
  11437. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11438. this._alphaState.alphaBlend = true;
  11439. break;
  11440. case Engine.ALPHA_ONEONE:
  11441. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11442. this._alphaState.alphaBlend = true;
  11443. break;
  11444. case Engine.ALPHA_ADD:
  11445. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11446. this._alphaState.alphaBlend = true;
  11447. break;
  11448. case Engine.ALPHA_SUBTRACT:
  11449. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11450. this._alphaState.alphaBlend = true;
  11451. break;
  11452. case Engine.ALPHA_MULTIPLY:
  11453. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11454. this._alphaState.alphaBlend = true;
  11455. break;
  11456. case Engine.ALPHA_MAXIMIZED:
  11457. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11458. this._alphaState.alphaBlend = true;
  11459. break;
  11460. case Engine.ALPHA_INTERPOLATE:
  11461. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11462. this._alphaState.alphaBlend = true;
  11463. break;
  11464. case Engine.ALPHA_SCREENMODE:
  11465. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11466. this._alphaState.alphaBlend = true;
  11467. break;
  11468. }
  11469. if (!noDepthWriteChange) {
  11470. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11471. }
  11472. this._alphaMode = mode;
  11473. };
  11474. Engine.prototype.getAlphaMode = function () {
  11475. return this._alphaMode;
  11476. };
  11477. // Textures
  11478. Engine.prototype.wipeCaches = function (bruteForce) {
  11479. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11480. return;
  11481. }
  11482. this._currentEffect = null;
  11483. // 6/8/2017: deltakosh: Should not be required anymore.
  11484. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11485. if (bruteForce) {
  11486. this.resetTextureCache();
  11487. this._currentProgram = null;
  11488. this._stencilState.reset();
  11489. this._depthCullingState.reset();
  11490. this.setDepthFunctionToLessOrEqual();
  11491. this._alphaState.reset();
  11492. }
  11493. this._resetVertexBufferBinding();
  11494. this._cachedIndexBuffer = null;
  11495. this._cachedEffectForVertexBuffers = null;
  11496. this._unbindVertexArrayObject();
  11497. this.bindIndexBuffer(null);
  11498. };
  11499. /**
  11500. * Set the compressed texture format to use, based on the formats you have, and the formats
  11501. * supported by the hardware / browser.
  11502. *
  11503. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11504. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11505. * to API arguments needed to compressed textures. This puts the burden on the container
  11506. * generator to house the arcane code for determining these for current & future formats.
  11507. *
  11508. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11509. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11510. *
  11511. * Note: The result of this call is not taken into account when a texture is base64.
  11512. *
  11513. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11514. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11515. *
  11516. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11517. * @returns The extension selected.
  11518. */
  11519. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11520. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11521. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11522. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11523. return this._textureFormatInUse = this._texturesSupported[i];
  11524. }
  11525. }
  11526. }
  11527. // actively set format to nothing, to allow this to be called more than once
  11528. // and possibly fail the 2nd time
  11529. this._textureFormatInUse = null;
  11530. return null;
  11531. };
  11532. Engine.prototype._createTexture = function () {
  11533. var texture = this._gl.createTexture();
  11534. if (!texture) {
  11535. throw new Error("Unable to create texture");
  11536. }
  11537. return texture;
  11538. };
  11539. /**
  11540. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11541. * @param {string} urlArg- This contains one of the following:
  11542. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11543. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11544. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11545. *
  11546. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11547. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11548. * @param {Scene} scene- Needed for loading to the correct scene.
  11549. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11550. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11551. * @param {callback} onError- Optional callback to be called upon failure.
  11552. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11553. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11554. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11555. *
  11556. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11557. */
  11558. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11559. var _this = this;
  11560. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11561. if (onLoad === void 0) { onLoad = null; }
  11562. if (onError === void 0) { onError = null; }
  11563. if (buffer === void 0) { buffer = null; }
  11564. if (fallBack === void 0) { fallBack = null; }
  11565. if (format === void 0) { format = null; }
  11566. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11567. var fromData = url.substr(0, 5) === "data:";
  11568. var fromBlob = url.substr(0, 5) === "blob:";
  11569. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11570. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11571. // establish the file extension, if possible
  11572. var lastDot = url.lastIndexOf('.');
  11573. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11574. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11575. var isTGA = (extension === ".tga");
  11576. // determine if a ktx file should be substituted
  11577. var isKTX = false;
  11578. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11579. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11580. isKTX = true;
  11581. }
  11582. if (scene) {
  11583. scene._addPendingData(texture);
  11584. }
  11585. texture.url = url;
  11586. texture.generateMipMaps = !noMipmap;
  11587. texture.samplingMode = samplingMode;
  11588. texture.invertY = invertY;
  11589. if (!this._doNotHandleContextLost) {
  11590. // Keep a link to the buffer only if we plan to handle context lost
  11591. texture._buffer = buffer;
  11592. }
  11593. var onLoadObserver = null;
  11594. if (onLoad && !fallBack) {
  11595. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11596. }
  11597. if (!fallBack)
  11598. this._internalTexturesCache.push(texture);
  11599. var onerror = function (message, exception) {
  11600. if (scene) {
  11601. scene._removePendingData(texture);
  11602. }
  11603. if (onLoadObserver) {
  11604. texture.onLoadedObservable.remove(onLoadObserver);
  11605. }
  11606. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11607. if (isKTX) {
  11608. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11609. }
  11610. else if (BABYLON.Tools.UseFallbackTexture) {
  11611. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11612. }
  11613. if (onError) {
  11614. onError(message || "Unknown error", exception);
  11615. }
  11616. };
  11617. var callback = null;
  11618. // processing for non-image formats
  11619. if (isKTX || isTGA || isDDS) {
  11620. if (isKTX) {
  11621. callback = function (data) {
  11622. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11623. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11624. ktx.uploadLevels(_this._gl, !noMipmap);
  11625. return false;
  11626. }, samplingMode);
  11627. };
  11628. }
  11629. else if (isTGA) {
  11630. callback = function (arrayBuffer) {
  11631. var data = new Uint8Array(arrayBuffer);
  11632. var header = BABYLON.TGATools.GetTGAHeader(data);
  11633. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11634. BABYLON.TGATools.UploadContent(_this._gl, data);
  11635. return false;
  11636. }, samplingMode);
  11637. };
  11638. }
  11639. else if (isDDS) {
  11640. callback = function (data) {
  11641. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11642. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11643. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11644. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11645. return false;
  11646. }, samplingMode);
  11647. };
  11648. }
  11649. if (!buffer) {
  11650. this._loadFile(url, function (data) {
  11651. if (callback) {
  11652. callback(data);
  11653. }
  11654. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11655. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11656. });
  11657. }
  11658. else {
  11659. if (callback) {
  11660. callback(buffer);
  11661. }
  11662. }
  11663. // image format processing
  11664. }
  11665. else {
  11666. var onload = function (img) {
  11667. if (fromBlob && !_this._doNotHandleContextLost) {
  11668. // We need to store the image if we need to rebuild the texture
  11669. // in case of a webgl context lost
  11670. texture._buffer = img;
  11671. }
  11672. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11673. var gl = _this._gl;
  11674. var isPot = (img.width === potWidth && img.height === potHeight);
  11675. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11676. if (isPot) {
  11677. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11678. return false;
  11679. }
  11680. // Using shaders to rescale because canvas.drawImage is lossy
  11681. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11682. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11683. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11684. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11685. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11686. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11687. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11688. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11689. _this._releaseTexture(source);
  11690. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11691. continuationCallback();
  11692. });
  11693. return true;
  11694. }, samplingMode);
  11695. };
  11696. if (!fromData || isBase64)
  11697. if (buffer instanceof HTMLImageElement) {
  11698. onload(buffer);
  11699. }
  11700. else {
  11701. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11702. }
  11703. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11704. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11705. else
  11706. onload(buffer);
  11707. }
  11708. return texture;
  11709. };
  11710. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11711. var _this = this;
  11712. var rtt = this.createRenderTargetTexture({
  11713. width: destination.width,
  11714. height: destination.height,
  11715. }, {
  11716. generateMipMaps: false,
  11717. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11718. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11719. generateDepthBuffer: false,
  11720. generateStencilBuffer: false
  11721. });
  11722. if (!this._rescalePostProcess) {
  11723. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11724. }
  11725. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11726. _this._rescalePostProcess.onApply = function (effect) {
  11727. effect._bindTexture("textureSampler", source);
  11728. };
  11729. var hostingScene = scene;
  11730. if (!hostingScene) {
  11731. hostingScene = _this.scenes[_this.scenes.length - 1];
  11732. }
  11733. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11734. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11735. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11736. _this.unBindFramebuffer(rtt);
  11737. _this._releaseTexture(rtt);
  11738. if (onComplete) {
  11739. onComplete();
  11740. }
  11741. });
  11742. };
  11743. Engine.prototype._getInternalFormat = function (format) {
  11744. var internalFormat = this._gl.RGBA;
  11745. switch (format) {
  11746. case Engine.TEXTUREFORMAT_ALPHA:
  11747. internalFormat = this._gl.ALPHA;
  11748. break;
  11749. case Engine.TEXTUREFORMAT_LUMINANCE:
  11750. internalFormat = this._gl.LUMINANCE;
  11751. break;
  11752. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11753. internalFormat = this._gl.LUMINANCE_ALPHA;
  11754. break;
  11755. case Engine.TEXTUREFORMAT_RGB:
  11756. internalFormat = this._gl.RGB;
  11757. break;
  11758. case Engine.TEXTUREFORMAT_RGBA:
  11759. internalFormat = this._gl.RGBA;
  11760. break;
  11761. }
  11762. return internalFormat;
  11763. };
  11764. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11765. if (compression === void 0) { compression = null; }
  11766. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11767. if (!texture) {
  11768. return;
  11769. }
  11770. var internalFormat = this._getInternalFormat(format);
  11771. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11772. var textureType = this._getWebGLTextureType(type);
  11773. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11774. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11775. if (!this._doNotHandleContextLost) {
  11776. texture._bufferView = data;
  11777. texture.format = format;
  11778. texture.type = type;
  11779. texture.invertY = invertY;
  11780. texture._compression = compression;
  11781. }
  11782. if (texture.width % 4 !== 0) {
  11783. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11784. }
  11785. if (compression && data) {
  11786. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11787. }
  11788. else {
  11789. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11790. }
  11791. if (texture.generateMipMaps) {
  11792. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11793. }
  11794. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11795. // this.resetTextureCache();
  11796. texture.isReady = true;
  11797. };
  11798. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11799. if (compression === void 0) { compression = null; }
  11800. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11801. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11802. texture.baseWidth = width;
  11803. texture.baseHeight = height;
  11804. texture.width = width;
  11805. texture.height = height;
  11806. texture.format = format;
  11807. texture.generateMipMaps = generateMipMaps;
  11808. texture.samplingMode = samplingMode;
  11809. texture.invertY = invertY;
  11810. texture._compression = compression;
  11811. texture.type = type;
  11812. if (!this._doNotHandleContextLost) {
  11813. texture._bufferView = data;
  11814. }
  11815. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11816. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11817. // Filters
  11818. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11819. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11820. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11821. if (generateMipMaps) {
  11822. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11823. }
  11824. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11825. this._internalTexturesCache.push(texture);
  11826. return texture;
  11827. };
  11828. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11829. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11830. texture.baseWidth = width;
  11831. texture.baseHeight = height;
  11832. if (generateMipMaps) {
  11833. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11834. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11835. }
  11836. // this.resetTextureCache();
  11837. texture.width = width;
  11838. texture.height = height;
  11839. texture.isReady = false;
  11840. texture.generateMipMaps = generateMipMaps;
  11841. texture.samplingMode = samplingMode;
  11842. this.updateTextureSamplingMode(samplingMode, texture);
  11843. this._internalTexturesCache.push(texture);
  11844. return texture;
  11845. };
  11846. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11847. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11848. if (texture.isCube) {
  11849. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11850. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11851. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11852. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11853. }
  11854. else if (texture.is3D) {
  11855. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11856. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11857. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11858. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11859. }
  11860. else {
  11861. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11862. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11863. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11864. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11865. }
  11866. texture.samplingMode = samplingMode;
  11867. };
  11868. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11869. if (premulAlpha === void 0) { premulAlpha = false; }
  11870. if (!texture) {
  11871. return;
  11872. }
  11873. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11874. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11875. if (premulAlpha) {
  11876. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11877. }
  11878. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11879. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11880. if (texture.generateMipMaps) {
  11881. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11882. }
  11883. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11884. if (premulAlpha) {
  11885. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11886. }
  11887. texture.isReady = true;
  11888. };
  11889. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11890. if (!texture || texture._isDisabled) {
  11891. return;
  11892. }
  11893. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11894. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11895. try {
  11896. // Testing video texture support
  11897. if (this._videoTextureSupported === undefined) {
  11898. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11899. if (this._gl.getError() !== 0) {
  11900. this._videoTextureSupported = false;
  11901. }
  11902. else {
  11903. this._videoTextureSupported = true;
  11904. }
  11905. }
  11906. // Copy video through the current working canvas if video texture is not supported
  11907. if (!this._videoTextureSupported) {
  11908. if (!texture._workingCanvas) {
  11909. texture._workingCanvas = document.createElement("canvas");
  11910. var context = texture._workingCanvas.getContext("2d");
  11911. if (!context) {
  11912. throw new Error("Unable to get 2d context");
  11913. }
  11914. texture._workingContext = context;
  11915. texture._workingCanvas.width = texture.width;
  11916. texture._workingCanvas.height = texture.height;
  11917. }
  11918. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11919. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11920. }
  11921. else {
  11922. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11923. }
  11924. if (texture.generateMipMaps) {
  11925. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11926. }
  11927. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11928. // this.resetTextureCache();
  11929. texture.isReady = true;
  11930. }
  11931. catch (ex) {
  11932. // Something unexpected
  11933. // Let's disable the texture
  11934. texture._isDisabled = true;
  11935. }
  11936. };
  11937. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11938. var fullOptions = new RenderTargetCreationOptions();
  11939. if (options !== undefined && typeof options === "object") {
  11940. fullOptions.generateMipMaps = options.generateMipMaps;
  11941. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11942. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11943. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11944. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11945. }
  11946. else {
  11947. fullOptions.generateMipMaps = options;
  11948. fullOptions.generateDepthBuffer = true;
  11949. fullOptions.generateStencilBuffer = false;
  11950. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11951. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11952. }
  11953. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11954. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11955. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11956. }
  11957. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11958. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11959. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11960. }
  11961. var gl = this._gl;
  11962. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11963. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11964. var width = size.width || size;
  11965. var height = size.height || size;
  11966. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11967. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11968. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11969. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11970. }
  11971. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11972. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11973. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11974. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11975. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11976. // Create the framebuffer
  11977. var framebuffer = gl.createFramebuffer();
  11978. this.bindUnboundFramebuffer(framebuffer);
  11979. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11980. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11981. if (fullOptions.generateMipMaps) {
  11982. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11983. }
  11984. // Unbind
  11985. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11986. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11987. this.bindUnboundFramebuffer(null);
  11988. texture._framebuffer = framebuffer;
  11989. texture.baseWidth = width;
  11990. texture.baseHeight = height;
  11991. texture.width = width;
  11992. texture.height = height;
  11993. texture.isReady = true;
  11994. texture.samples = 1;
  11995. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11996. texture.samplingMode = fullOptions.samplingMode;
  11997. texture.type = fullOptions.type;
  11998. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11999. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12000. // this.resetTextureCache();
  12001. this._internalTexturesCache.push(texture);
  12002. return texture;
  12003. };
  12004. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12005. var generateMipMaps = false;
  12006. var generateDepthBuffer = true;
  12007. var generateStencilBuffer = false;
  12008. var generateDepthTexture = false;
  12009. var textureCount = 1;
  12010. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12011. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12012. var types = [], samplingModes = [];
  12013. if (options !== undefined) {
  12014. generateMipMaps = options.generateMipMaps;
  12015. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12016. generateStencilBuffer = options.generateStencilBuffer;
  12017. generateDepthTexture = options.generateDepthTexture;
  12018. textureCount = options.textureCount || 1;
  12019. if (options.types) {
  12020. types = options.types;
  12021. }
  12022. if (options.samplingModes) {
  12023. samplingModes = options.samplingModes;
  12024. }
  12025. }
  12026. var gl = this._gl;
  12027. // Create the framebuffer
  12028. var framebuffer = gl.createFramebuffer();
  12029. this.bindUnboundFramebuffer(framebuffer);
  12030. var width = size.width || size;
  12031. var height = size.height || size;
  12032. var textures = [];
  12033. var attachments = [];
  12034. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12035. for (var i = 0; i < textureCount; i++) {
  12036. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12037. var type = types[i] || defaultType;
  12038. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12039. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12040. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12041. }
  12042. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12043. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12044. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12045. }
  12046. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12047. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12048. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12049. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12050. }
  12051. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12052. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12053. textures.push(texture);
  12054. attachments.push(attachment);
  12055. gl.activeTexture(gl["TEXTURE" + i]);
  12056. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12057. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12058. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12059. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12060. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12061. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12062. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12063. if (generateMipMaps) {
  12064. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12065. }
  12066. // Unbind
  12067. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12068. texture._framebuffer = framebuffer;
  12069. texture._depthStencilBuffer = depthStencilBuffer;
  12070. texture.baseWidth = width;
  12071. texture.baseHeight = height;
  12072. texture.width = width;
  12073. texture.height = height;
  12074. texture.isReady = true;
  12075. texture.samples = 1;
  12076. texture.generateMipMaps = generateMipMaps;
  12077. texture.samplingMode = samplingMode;
  12078. texture.type = type;
  12079. texture._generateDepthBuffer = generateDepthBuffer;
  12080. texture._generateStencilBuffer = generateStencilBuffer;
  12081. texture._attachments = attachments;
  12082. this._internalTexturesCache.push(texture);
  12083. }
  12084. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12085. // Depth texture
  12086. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12087. gl.activeTexture(gl.TEXTURE0);
  12088. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12093. 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);
  12094. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12095. depthTexture._framebuffer = framebuffer;
  12096. depthTexture.baseWidth = width;
  12097. depthTexture.baseHeight = height;
  12098. depthTexture.width = width;
  12099. depthTexture.height = height;
  12100. depthTexture.isReady = true;
  12101. depthTexture.samples = 1;
  12102. depthTexture.generateMipMaps = generateMipMaps;
  12103. depthTexture.samplingMode = gl.NEAREST;
  12104. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12105. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12106. textures.push(depthTexture);
  12107. this._internalTexturesCache.push(depthTexture);
  12108. }
  12109. gl.drawBuffers(attachments);
  12110. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12111. this.bindUnboundFramebuffer(null);
  12112. this.resetTextureCache();
  12113. return textures;
  12114. };
  12115. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12116. if (samples === void 0) { samples = 1; }
  12117. var depthStencilBuffer = null;
  12118. var gl = this._gl;
  12119. // Create the depth/stencil buffer
  12120. if (generateStencilBuffer) {
  12121. depthStencilBuffer = gl.createRenderbuffer();
  12122. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12123. if (samples > 1) {
  12124. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12125. }
  12126. else {
  12127. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12128. }
  12129. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12130. }
  12131. else if (generateDepthBuffer) {
  12132. depthStencilBuffer = gl.createRenderbuffer();
  12133. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12134. if (samples > 1) {
  12135. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12136. }
  12137. else {
  12138. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12139. }
  12140. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12141. }
  12142. return depthStencilBuffer;
  12143. };
  12144. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12145. if (this.webGLVersion < 2 || !texture) {
  12146. return 1;
  12147. }
  12148. if (texture.samples === samples) {
  12149. return samples;
  12150. }
  12151. var gl = this._gl;
  12152. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12153. // Dispose previous render buffers
  12154. if (texture._depthStencilBuffer) {
  12155. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12156. texture._depthStencilBuffer = null;
  12157. }
  12158. if (texture._MSAAFramebuffer) {
  12159. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12160. texture._MSAAFramebuffer = null;
  12161. }
  12162. if (texture._MSAARenderBuffer) {
  12163. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12164. texture._MSAARenderBuffer = null;
  12165. }
  12166. if (samples > 1) {
  12167. var framebuffer = gl.createFramebuffer();
  12168. if (!framebuffer) {
  12169. throw new Error("Unable to create multi sampled framebuffer");
  12170. }
  12171. texture._MSAAFramebuffer = framebuffer;
  12172. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12173. var colorRenderbuffer = gl.createRenderbuffer();
  12174. if (!colorRenderbuffer) {
  12175. throw new Error("Unable to create multi sampled framebuffer");
  12176. }
  12177. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12178. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12179. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12180. texture._MSAARenderBuffer = colorRenderbuffer;
  12181. }
  12182. else {
  12183. this.bindUnboundFramebuffer(texture._framebuffer);
  12184. }
  12185. texture.samples = samples;
  12186. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12187. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12188. this.bindUnboundFramebuffer(null);
  12189. return samples;
  12190. };
  12191. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12192. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12193. return 1;
  12194. }
  12195. if (textures[0].samples === samples) {
  12196. return samples;
  12197. }
  12198. var gl = this._gl;
  12199. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12200. // Dispose previous render buffers
  12201. if (textures[0]._depthStencilBuffer) {
  12202. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12203. textures[0]._depthStencilBuffer = null;
  12204. }
  12205. if (textures[0]._MSAAFramebuffer) {
  12206. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12207. textures[0]._MSAAFramebuffer = null;
  12208. }
  12209. for (var i = 0; i < textures.length; i++) {
  12210. if (textures[i]._MSAARenderBuffer) {
  12211. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12212. textures[i]._MSAARenderBuffer = null;
  12213. }
  12214. }
  12215. if (samples > 1) {
  12216. var framebuffer = gl.createFramebuffer();
  12217. if (!framebuffer) {
  12218. throw new Error("Unable to create multi sampled framebuffer");
  12219. }
  12220. this.bindUnboundFramebuffer(framebuffer);
  12221. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12222. var attachments = [];
  12223. for (var i = 0; i < textures.length; i++) {
  12224. var texture = textures[i];
  12225. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12226. var colorRenderbuffer = gl.createRenderbuffer();
  12227. if (!colorRenderbuffer) {
  12228. throw new Error("Unable to create multi sampled framebuffer");
  12229. }
  12230. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12231. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12232. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12233. texture._MSAAFramebuffer = framebuffer;
  12234. texture._MSAARenderBuffer = colorRenderbuffer;
  12235. texture.samples = samples;
  12236. texture._depthStencilBuffer = depthStencilBuffer;
  12237. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12238. attachments.push(attachment);
  12239. }
  12240. gl.drawBuffers(attachments);
  12241. }
  12242. else {
  12243. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12244. }
  12245. this.bindUnboundFramebuffer(null);
  12246. return samples;
  12247. };
  12248. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12249. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12250. };
  12251. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12252. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12253. };
  12254. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12255. var gl = this._gl;
  12256. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12257. var generateMipMaps = true;
  12258. var generateDepthBuffer = true;
  12259. var generateStencilBuffer = false;
  12260. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12261. if (options !== undefined) {
  12262. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12263. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12264. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12265. if (options.samplingMode !== undefined) {
  12266. samplingMode = options.samplingMode;
  12267. }
  12268. }
  12269. texture.isCube = true;
  12270. texture.generateMipMaps = generateMipMaps;
  12271. texture.samples = 1;
  12272. texture.samplingMode = samplingMode;
  12273. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12274. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12275. for (var face = 0; face < 6; face++) {
  12276. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12277. }
  12278. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12279. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12280. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12281. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12282. // Create the framebuffer
  12283. var framebuffer = gl.createFramebuffer();
  12284. this.bindUnboundFramebuffer(framebuffer);
  12285. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12286. // Mipmaps
  12287. if (texture.generateMipMaps) {
  12288. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12289. }
  12290. // Unbind
  12291. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12292. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12293. this.bindUnboundFramebuffer(null);
  12294. texture._framebuffer = framebuffer;
  12295. texture.width = size;
  12296. texture.height = size;
  12297. texture.isReady = true;
  12298. //this.resetTextureCache();
  12299. this._internalTexturesCache.push(texture);
  12300. return texture;
  12301. };
  12302. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12303. var _this = this;
  12304. if (onLoad === void 0) { onLoad = null; }
  12305. if (onError === void 0) { onError = null; }
  12306. if (forcedExtension === void 0) { forcedExtension = null; }
  12307. var callback = function (loadData) {
  12308. if (!loadData) {
  12309. if (onLoad) {
  12310. onLoad(null);
  12311. }
  12312. return;
  12313. }
  12314. var texture = loadData.texture;
  12315. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12316. texture._lodGenerationScale = scale;
  12317. texture._lodGenerationOffset = offset;
  12318. if (_this._caps.textureLOD) {
  12319. // Do not add extra process if texture lod is supported.
  12320. if (onLoad) {
  12321. onLoad(texture);
  12322. }
  12323. return;
  12324. }
  12325. var mipSlices = 3;
  12326. var gl = _this._gl;
  12327. var width = loadData.width;
  12328. if (!width) {
  12329. return;
  12330. }
  12331. var textures = [];
  12332. for (var i = 0; i < mipSlices; i++) {
  12333. //compute LOD from even spacing in smoothness (matching shader calculation)
  12334. var smoothness = i / (mipSlices - 1);
  12335. var roughness = 1 - smoothness;
  12336. var minLODIndex = offset; // roughness = 0
  12337. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12338. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12339. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12340. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12341. glTextureFromLod.isCube = true;
  12342. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12343. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12344. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12345. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12346. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12347. if (loadData.isDDS) {
  12348. var info = loadData.info;
  12349. var data = loadData.data;
  12350. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12351. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12352. }
  12353. else {
  12354. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12355. }
  12356. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12357. // Wrap in a base texture for easy binding.
  12358. var lodTexture = new BABYLON.BaseTexture(scene);
  12359. lodTexture.isCube = true;
  12360. lodTexture._texture = glTextureFromLod;
  12361. glTextureFromLod.isReady = true;
  12362. textures.push(lodTexture);
  12363. }
  12364. texture._lodTextureHigh = textures[2];
  12365. texture._lodTextureMid = textures[1];
  12366. texture._lodTextureLow = textures[0];
  12367. if (onLoad) {
  12368. onLoad(texture);
  12369. }
  12370. };
  12371. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12372. };
  12373. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12374. var _this = this;
  12375. if (onLoad === void 0) { onLoad = null; }
  12376. if (onError === void 0) { onError = null; }
  12377. if (forcedExtension === void 0) { forcedExtension = null; }
  12378. var gl = this._gl;
  12379. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12380. texture.isCube = true;
  12381. texture.url = rootUrl;
  12382. texture.generateMipMaps = !noMipmap;
  12383. if (!this._doNotHandleContextLost) {
  12384. texture._extension = forcedExtension;
  12385. texture._files = files;
  12386. }
  12387. var isKTX = false;
  12388. var isDDS = false;
  12389. var lastDot = rootUrl.lastIndexOf('.');
  12390. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12391. if (this._textureFormatInUse) {
  12392. extension = this._textureFormatInUse;
  12393. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12394. isKTX = true;
  12395. }
  12396. else {
  12397. isDDS = (extension === ".dds");
  12398. }
  12399. var onerror = function (request, exception) {
  12400. if (onError && request) {
  12401. onError(request.status + " " + request.statusText, exception);
  12402. }
  12403. };
  12404. if (isKTX) {
  12405. this._loadFile(rootUrl, function (data) {
  12406. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12407. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12408. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12409. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12410. ktx.uploadLevels(_this._gl, !noMipmap);
  12411. _this.setCubeMapTextureParams(gl, loadMipmap);
  12412. texture.width = ktx.pixelWidth;
  12413. texture.height = ktx.pixelHeight;
  12414. texture.isReady = true;
  12415. }, undefined, undefined, true, onerror);
  12416. }
  12417. else if (isDDS) {
  12418. if (files && files.length === 6) {
  12419. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12420. var info;
  12421. var loadMipmap = false;
  12422. var width = 0;
  12423. for (var index = 0; index < imgs.length; index++) {
  12424. var data = imgs[index];
  12425. info = BABYLON.DDSTools.GetDDSInfo(data);
  12426. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12427. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12428. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12429. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12430. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12431. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12432. }
  12433. texture.width = info.width;
  12434. texture.height = info.height;
  12435. texture.type = info.textureType;
  12436. width = info.width;
  12437. }
  12438. _this.setCubeMapTextureParams(gl, loadMipmap);
  12439. texture.isReady = true;
  12440. if (onLoad) {
  12441. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12442. }
  12443. }, files, onError);
  12444. }
  12445. else {
  12446. this._loadFile(rootUrl, function (data) {
  12447. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12448. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12449. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12450. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12451. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12452. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12453. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12454. }
  12455. _this.setCubeMapTextureParams(gl, loadMipmap);
  12456. texture.width = info.width;
  12457. texture.height = info.height;
  12458. texture.isReady = true;
  12459. texture.type = info.textureType;
  12460. if (onLoad) {
  12461. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12462. }
  12463. }, undefined, undefined, true, onerror);
  12464. }
  12465. }
  12466. else {
  12467. if (!files) {
  12468. throw new Error("Cannot load cubemap because files were not defined");
  12469. }
  12470. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12471. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12472. var height = width;
  12473. _this._prepareWorkingCanvas();
  12474. if (!_this._workingCanvas || !_this._workingContext) {
  12475. return;
  12476. }
  12477. _this._workingCanvas.width = width;
  12478. _this._workingCanvas.height = height;
  12479. var faces = [
  12480. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12481. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12482. ];
  12483. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12484. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12485. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12486. for (var index = 0; index < faces.length; index++) {
  12487. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12488. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12489. }
  12490. if (!noMipmap) {
  12491. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12492. }
  12493. _this.setCubeMapTextureParams(gl, !noMipmap);
  12494. texture.width = width;
  12495. texture.height = height;
  12496. texture.isReady = true;
  12497. if (format) {
  12498. texture.format = format;
  12499. }
  12500. texture.onLoadedObservable.notifyObservers(texture);
  12501. texture.onLoadedObservable.clear();
  12502. if (onLoad) {
  12503. onLoad();
  12504. }
  12505. }, files, onError);
  12506. }
  12507. this._internalTexturesCache.push(texture);
  12508. return texture;
  12509. };
  12510. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12511. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12512. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12515. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12516. // this.resetTextureCache();
  12517. };
  12518. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12519. if (compression === void 0) { compression = null; }
  12520. if (level === void 0) { level = 0; }
  12521. texture._bufferViewArray = data;
  12522. texture.format = format;
  12523. texture.type = type;
  12524. texture.invertY = invertY;
  12525. texture._compression = compression;
  12526. var gl = this._gl;
  12527. var textureType = this._getWebGLTextureType(type);
  12528. var internalFormat = this._getInternalFormat(format);
  12529. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12530. var needConversion = false;
  12531. if (internalFormat === gl.RGB) {
  12532. internalFormat = gl.RGBA;
  12533. needConversion = true;
  12534. }
  12535. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12536. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12537. if (texture.width % 4 !== 0) {
  12538. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12539. }
  12540. // Data are known to be in +X +Y +Z -X -Y -Z
  12541. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12542. var faceData = data[faceIndex];
  12543. if (compression) {
  12544. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12545. }
  12546. else {
  12547. if (needConversion) {
  12548. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12549. }
  12550. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12551. }
  12552. }
  12553. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12554. if (isPot && texture.generateMipMaps && level === 0) {
  12555. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12556. }
  12557. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12558. // this.resetTextureCache();
  12559. texture.isReady = true;
  12560. };
  12561. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12562. if (compression === void 0) { compression = null; }
  12563. var gl = this._gl;
  12564. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12565. texture.isCube = true;
  12566. texture.generateMipMaps = generateMipMaps;
  12567. texture.format = format;
  12568. texture.type = type;
  12569. if (!this._doNotHandleContextLost) {
  12570. texture._bufferViewArray = data;
  12571. }
  12572. var textureType = this._getWebGLTextureType(type);
  12573. var internalFormat = this._getInternalFormat(format);
  12574. if (internalFormat === gl.RGB) {
  12575. internalFormat = gl.RGBA;
  12576. }
  12577. var width = size;
  12578. var height = width;
  12579. texture.width = width;
  12580. texture.height = height;
  12581. // Double check on POT to generate Mips.
  12582. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12583. if (!isPot) {
  12584. generateMipMaps = false;
  12585. }
  12586. // Upload data if needed. The texture won't be ready until then.
  12587. if (data) {
  12588. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12589. }
  12590. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12591. // Filters
  12592. if (data && generateMipMaps) {
  12593. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12594. }
  12595. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12596. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12597. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12598. }
  12599. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12602. }
  12603. else {
  12604. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12605. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12606. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12607. }
  12608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12610. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12611. return texture;
  12612. };
  12613. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12614. var _this = this;
  12615. if (onLoad === void 0) { onLoad = null; }
  12616. if (onError === void 0) { onError = null; }
  12617. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12618. if (invertY === void 0) { invertY = false; }
  12619. var gl = this._gl;
  12620. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12621. scene._addPendingData(texture);
  12622. texture.url = url;
  12623. this._internalTexturesCache.push(texture);
  12624. var onerror = function (request, exception) {
  12625. scene._removePendingData(texture);
  12626. if (onError && request) {
  12627. onError(request.status + " " + request.statusText, exception);
  12628. }
  12629. };
  12630. var internalCallback = function (data) {
  12631. var width = texture.width;
  12632. var faceDataArrays = callback(data);
  12633. if (!faceDataArrays) {
  12634. return;
  12635. }
  12636. if (mipmmapGenerator) {
  12637. var textureType = _this._getWebGLTextureType(type);
  12638. var internalFormat = _this._getInternalFormat(format);
  12639. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12640. var needConversion = false;
  12641. if (internalFormat === gl.RGB) {
  12642. internalFormat = gl.RGBA;
  12643. needConversion = true;
  12644. }
  12645. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12646. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12647. var mipData = mipmmapGenerator(faceDataArrays);
  12648. for (var level = 0; level < mipData.length; level++) {
  12649. var mipSize = width >> level;
  12650. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12651. var mipFaceData = mipData[level][faceIndex];
  12652. if (needConversion) {
  12653. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12654. }
  12655. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12656. }
  12657. }
  12658. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12659. }
  12660. else {
  12661. texture.generateMipMaps = !noMipmap;
  12662. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12663. }
  12664. texture.isReady = true;
  12665. // this.resetTextureCache();
  12666. scene._removePendingData(texture);
  12667. if (onLoad) {
  12668. onLoad();
  12669. }
  12670. };
  12671. this._loadFile(url, function (data) {
  12672. internalCallback(data);
  12673. }, undefined, scene.database, true, onerror);
  12674. return texture;
  12675. };
  12676. ;
  12677. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12678. if (compression === void 0) { compression = null; }
  12679. var internalFormat = this._getInternalFormat(format);
  12680. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12681. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12682. if (!this._doNotHandleContextLost) {
  12683. texture._bufferView = data;
  12684. texture.format = format;
  12685. texture.invertY = invertY;
  12686. texture._compression = compression;
  12687. }
  12688. if (texture.width % 4 !== 0) {
  12689. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12690. }
  12691. if (compression && data) {
  12692. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12693. }
  12694. else {
  12695. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12696. }
  12697. if (texture.generateMipMaps) {
  12698. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12699. }
  12700. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12701. // this.resetTextureCache();
  12702. texture.isReady = true;
  12703. };
  12704. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12705. if (compression === void 0) { compression = null; }
  12706. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12707. texture.baseWidth = width;
  12708. texture.baseHeight = height;
  12709. texture.baseDepth = depth;
  12710. texture.width = width;
  12711. texture.height = height;
  12712. texture.depth = depth;
  12713. texture.format = format;
  12714. texture.generateMipMaps = generateMipMaps;
  12715. texture.samplingMode = samplingMode;
  12716. texture.is3D = true;
  12717. if (!this._doNotHandleContextLost) {
  12718. texture._bufferView = data;
  12719. }
  12720. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12721. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12722. // Filters
  12723. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12724. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12725. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12726. if (generateMipMaps) {
  12727. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12728. }
  12729. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12730. this._internalTexturesCache.push(texture);
  12731. return texture;
  12732. };
  12733. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12734. var gl = this._gl;
  12735. if (!gl) {
  12736. return;
  12737. }
  12738. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12739. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12740. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12741. if (!noMipmap && !isCompressed) {
  12742. gl.generateMipmap(gl.TEXTURE_2D);
  12743. }
  12744. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12745. // this.resetTextureCache();
  12746. if (scene) {
  12747. scene._removePendingData(texture);
  12748. }
  12749. texture.onLoadedObservable.notifyObservers(texture);
  12750. texture.onLoadedObservable.clear();
  12751. };
  12752. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12753. var _this = this;
  12754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12755. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12756. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12757. var gl = this._gl;
  12758. if (!gl) {
  12759. return;
  12760. }
  12761. if (!texture._webGLTexture) {
  12762. // this.resetTextureCache();
  12763. if (scene) {
  12764. scene._removePendingData(texture);
  12765. }
  12766. return;
  12767. }
  12768. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12769. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12770. texture.baseWidth = width;
  12771. texture.baseHeight = height;
  12772. texture.width = potWidth;
  12773. texture.height = potHeight;
  12774. texture.isReady = true;
  12775. if (processFunction(potWidth, potHeight, function () {
  12776. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12777. })) {
  12778. // Returning as texture needs extra async steps
  12779. return;
  12780. }
  12781. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12782. };
  12783. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12784. // Create new RGBA data container.
  12785. var rgbaData;
  12786. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12787. rgbaData = new Float32Array(width * height * 4);
  12788. }
  12789. else {
  12790. rgbaData = new Uint32Array(width * height * 4);
  12791. }
  12792. // Convert each pixel.
  12793. for (var x = 0; x < width; x++) {
  12794. for (var y = 0; y < height; y++) {
  12795. var index = (y * width + x) * 3;
  12796. var newIndex = (y * width + x) * 4;
  12797. // Map Old Value to new value.
  12798. rgbaData[newIndex + 0] = rgbData[index + 0];
  12799. rgbaData[newIndex + 1] = rgbData[index + 1];
  12800. rgbaData[newIndex + 2] = rgbData[index + 2];
  12801. // Add fully opaque alpha channel.
  12802. rgbaData[newIndex + 3] = 1;
  12803. }
  12804. }
  12805. return rgbaData;
  12806. };
  12807. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12808. var gl = this._gl;
  12809. if (texture._framebuffer) {
  12810. gl.deleteFramebuffer(texture._framebuffer);
  12811. texture._framebuffer = null;
  12812. }
  12813. if (texture._depthStencilBuffer) {
  12814. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12815. texture._depthStencilBuffer = null;
  12816. }
  12817. if (texture._MSAAFramebuffer) {
  12818. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12819. texture._MSAAFramebuffer = null;
  12820. }
  12821. if (texture._MSAARenderBuffer) {
  12822. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12823. texture._MSAARenderBuffer = null;
  12824. }
  12825. };
  12826. Engine.prototype._releaseTexture = function (texture) {
  12827. var gl = this._gl;
  12828. this._releaseFramebufferObjects(texture);
  12829. gl.deleteTexture(texture._webGLTexture);
  12830. // Unbind channels
  12831. this.unbindAllTextures();
  12832. var index = this._internalTexturesCache.indexOf(texture);
  12833. if (index !== -1) {
  12834. this._internalTexturesCache.splice(index, 1);
  12835. }
  12836. // Integrated fixed lod samplers.
  12837. if (texture._lodTextureHigh) {
  12838. texture._lodTextureHigh.dispose();
  12839. }
  12840. if (texture._lodTextureMid) {
  12841. texture._lodTextureMid.dispose();
  12842. }
  12843. if (texture._lodTextureLow) {
  12844. texture._lodTextureLow.dispose();
  12845. }
  12846. };
  12847. Engine.prototype.setProgram = function (program) {
  12848. if (this._currentProgram !== program) {
  12849. this._gl.useProgram(program);
  12850. this._currentProgram = program;
  12851. }
  12852. };
  12853. Engine.prototype.bindSamplers = function (effect) {
  12854. this.setProgram(effect.getProgram());
  12855. var samplers = effect.getSamplers();
  12856. for (var index = 0; index < samplers.length; index++) {
  12857. var uniform = effect.getUniform(samplers[index]);
  12858. if (uniform) {
  12859. this._boundUniforms[index] = uniform;
  12860. }
  12861. }
  12862. this._currentEffect = null;
  12863. };
  12864. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12865. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  12866. return;
  12867. }
  12868. // Remove
  12869. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12870. // Bind last to it
  12871. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  12872. // Bind to dummy
  12873. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  12874. };
  12875. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12876. if (!internalTexture) {
  12877. return -1;
  12878. }
  12879. internalTexture._initialSlot = channel;
  12880. if (this.disableTextureBindingOptimization) {
  12881. if (channel !== internalTexture._designatedSlot) {
  12882. this._textureCollisions.addCount(1, false);
  12883. }
  12884. }
  12885. else {
  12886. if (channel !== internalTexture._designatedSlot) {
  12887. if (internalTexture._designatedSlot > -1) {
  12888. return internalTexture._designatedSlot;
  12889. }
  12890. else {
  12891. // No slot for this texture, let's pick a new one (if we find a free slot)
  12892. if (this._nextFreeTextureSlots.length) {
  12893. return this._nextFreeTextureSlots[0];
  12894. }
  12895. // We need to recycle the oldest bound texture, sorry.
  12896. this._textureCollisions.addCount(1, false);
  12897. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  12898. }
  12899. }
  12900. }
  12901. return channel;
  12902. };
  12903. Engine.prototype._linkTrackers = function (previous, next) {
  12904. previous.next = next;
  12905. next.previous = previous;
  12906. };
  12907. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12908. var currentSlot = internalTexture._designatedSlot;
  12909. if (currentSlot === -1) {
  12910. return -1;
  12911. }
  12912. internalTexture._designatedSlot = -1;
  12913. // Remove from bound list
  12914. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12915. // Free the slot
  12916. this._boundTexturesCache[currentSlot] = null;
  12917. this._nextFreeTextureSlots.push(currentSlot);
  12918. return currentSlot;
  12919. };
  12920. Engine.prototype._activateCurrentTexture = function () {
  12921. if (this._currentTextureChannel !== this._activeChannel) {
  12922. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  12923. this._currentTextureChannel = this._activeChannel;
  12924. }
  12925. };
  12926. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  12927. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  12928. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  12929. this._activeChannel = texture._designatedSlot;
  12930. }
  12931. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12932. var isTextureForRendering = texture && texture._initialSlot > -1;
  12933. if (currentTextureBound !== texture) {
  12934. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  12935. this._removeDesignatedSlot(currentTextureBound);
  12936. }
  12937. this._activateCurrentTexture();
  12938. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12939. this._boundTexturesCache[this._activeChannel] = texture;
  12940. if (texture) {
  12941. if (!this.disableTextureBindingOptimization) {
  12942. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12943. if (slotIndex > -1) {
  12944. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12945. }
  12946. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  12947. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  12948. }
  12949. texture._designatedSlot = this._activeChannel;
  12950. }
  12951. }
  12952. else if (forTextureDataUpdate) {
  12953. this._activateCurrentTexture();
  12954. }
  12955. if (isTextureForRendering && !forTextureDataUpdate) {
  12956. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12957. }
  12958. };
  12959. Engine.prototype._bindTexture = function (channel, texture) {
  12960. if (channel < 0) {
  12961. return;
  12962. }
  12963. if (texture) {
  12964. channel = this._getCorrectTextureChannel(channel, texture);
  12965. }
  12966. this._activeChannel = channel;
  12967. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12968. };
  12969. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12970. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12971. };
  12972. Engine.prototype.unbindAllTextures = function () {
  12973. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  12974. this._activeChannel = channel;
  12975. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12976. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12977. if (this.webGLVersion > 1) {
  12978. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12979. }
  12980. }
  12981. };
  12982. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12983. if (channel < 0) {
  12984. return;
  12985. }
  12986. if (uniform) {
  12987. this._boundUniforms[channel] = uniform;
  12988. }
  12989. this._setTexture(channel, texture);
  12990. };
  12991. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12992. var uniform = this._boundUniforms[sourceSlot];
  12993. if (uniform._currentState === destination) {
  12994. return;
  12995. }
  12996. this._gl.uniform1i(uniform, destination);
  12997. uniform._currentState = destination;
  12998. };
  12999. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13000. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13001. // Not ready?
  13002. if (!texture) {
  13003. if (this._boundTexturesCache[channel] != null) {
  13004. this._activeChannel = channel;
  13005. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13006. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13007. if (this.webGLVersion > 1) {
  13008. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13009. }
  13010. }
  13011. return false;
  13012. }
  13013. // Video
  13014. if (texture.video) {
  13015. this._activeChannel = channel;
  13016. texture.update();
  13017. }
  13018. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13019. texture.delayLoad();
  13020. return false;
  13021. }
  13022. var internalTexture;
  13023. if (texture.isReady()) {
  13024. internalTexture = texture.getInternalTexture();
  13025. }
  13026. else if (texture.isCube) {
  13027. internalTexture = this.emptyCubeTexture;
  13028. }
  13029. else if (texture.is3D) {
  13030. internalTexture = this.emptyTexture3D;
  13031. }
  13032. else {
  13033. internalTexture = this.emptyTexture;
  13034. }
  13035. if (!isPartOfTextureArray) {
  13036. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13037. }
  13038. if (this._boundTexturesCache[channel] === internalTexture) {
  13039. this._moveBoundTextureOnTop(internalTexture);
  13040. if (!isPartOfTextureArray) {
  13041. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13042. }
  13043. return false;
  13044. }
  13045. this._activeChannel = channel;
  13046. if (internalTexture && internalTexture.is3D) {
  13047. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13048. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13049. internalTexture._cachedWrapU = texture.wrapU;
  13050. switch (texture.wrapU) {
  13051. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13052. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13053. break;
  13054. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13055. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13056. break;
  13057. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13058. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13059. break;
  13060. }
  13061. }
  13062. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13063. internalTexture._cachedWrapV = texture.wrapV;
  13064. switch (texture.wrapV) {
  13065. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13066. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13067. break;
  13068. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13069. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13070. break;
  13071. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13072. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13073. break;
  13074. }
  13075. }
  13076. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13077. internalTexture._cachedWrapR = texture.wrapR;
  13078. switch (texture.wrapV) {
  13079. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13080. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13081. break;
  13082. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13083. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13084. break;
  13085. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13086. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13087. break;
  13088. }
  13089. }
  13090. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13091. }
  13092. else if (internalTexture && internalTexture.isCube) {
  13093. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13094. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13095. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13096. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13097. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13098. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13099. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13100. }
  13101. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13102. }
  13103. else {
  13104. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13105. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13106. internalTexture._cachedWrapU = texture.wrapU;
  13107. switch (texture.wrapU) {
  13108. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13109. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13110. break;
  13111. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13112. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13113. break;
  13114. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13115. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13116. break;
  13117. }
  13118. }
  13119. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13120. internalTexture._cachedWrapV = texture.wrapV;
  13121. switch (texture.wrapV) {
  13122. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13123. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13124. break;
  13125. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13126. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13127. break;
  13128. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13129. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13130. break;
  13131. }
  13132. }
  13133. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13134. }
  13135. return true;
  13136. };
  13137. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13138. if (channel < 0 || !uniform) {
  13139. return;
  13140. }
  13141. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13142. this._textureUnits = new Int32Array(textures.length);
  13143. }
  13144. for (var i = 0; i < textures.length; i++) {
  13145. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13146. }
  13147. this._gl.uniform1iv(uniform, this._textureUnits);
  13148. for (var index = 0; index < textures.length; index++) {
  13149. this._setTexture(this._textureUnits[index], textures[index], true);
  13150. }
  13151. };
  13152. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13153. var internalTexture = texture.getInternalTexture();
  13154. if (!internalTexture) {
  13155. return;
  13156. }
  13157. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13158. var value = texture.anisotropicFilteringLevel;
  13159. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13160. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13161. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13162. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13163. }
  13164. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13165. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13166. internalTexture._cachedAnisotropicFilteringLevel = value;
  13167. }
  13168. };
  13169. Engine.prototype.readPixels = function (x, y, width, height) {
  13170. var data = new Uint8Array(height * width * 4);
  13171. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13172. return data;
  13173. };
  13174. /**
  13175. * Add an externaly attached data from its key.
  13176. * This method call will fail and return false, if such key already exists.
  13177. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13178. * @param key the unique key that identifies the data
  13179. * @param data the data object to associate to the key for this Engine instance
  13180. * @return true if no such key were already present and the data was added successfully, false otherwise
  13181. */
  13182. Engine.prototype.addExternalData = function (key, data) {
  13183. if (!this._externalData) {
  13184. this._externalData = new BABYLON.StringDictionary();
  13185. }
  13186. return this._externalData.add(key, data);
  13187. };
  13188. /**
  13189. * Get an externaly attached data from its key
  13190. * @param key the unique key that identifies the data
  13191. * @return the associated data, if present (can be null), or undefined if not present
  13192. */
  13193. Engine.prototype.getExternalData = function (key) {
  13194. if (!this._externalData) {
  13195. this._externalData = new BABYLON.StringDictionary();
  13196. }
  13197. return this._externalData.get(key);
  13198. };
  13199. /**
  13200. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13201. * @param key the unique key that identifies the data
  13202. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13203. * @return the associated data, can be null if the factory returned null.
  13204. */
  13205. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13206. if (!this._externalData) {
  13207. this._externalData = new BABYLON.StringDictionary();
  13208. }
  13209. return this._externalData.getOrAddWithFactory(key, factory);
  13210. };
  13211. /**
  13212. * Remove an externaly attached data from the Engine instance
  13213. * @param key the unique key that identifies the data
  13214. * @return true if the data was successfully removed, false if it doesn't exist
  13215. */
  13216. Engine.prototype.removeExternalData = function (key) {
  13217. if (!this._externalData) {
  13218. this._externalData = new BABYLON.StringDictionary();
  13219. }
  13220. return this._externalData.remove(key);
  13221. };
  13222. Engine.prototype.unbindAllAttributes = function () {
  13223. if (this._mustWipeVertexAttributes) {
  13224. this._mustWipeVertexAttributes = false;
  13225. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13226. this._gl.disableVertexAttribArray(i);
  13227. this._vertexAttribArraysEnabled[i] = false;
  13228. this._currentBufferPointers[i].active = false;
  13229. }
  13230. return;
  13231. }
  13232. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13233. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13234. continue;
  13235. }
  13236. this._gl.disableVertexAttribArray(i);
  13237. this._vertexAttribArraysEnabled[i] = false;
  13238. this._currentBufferPointers[i].active = false;
  13239. }
  13240. };
  13241. Engine.prototype.releaseEffects = function () {
  13242. for (var name in this._compiledEffects) {
  13243. this._deleteProgram(this._compiledEffects[name]._program);
  13244. }
  13245. this._compiledEffects = {};
  13246. };
  13247. // Dispose
  13248. Engine.prototype.dispose = function () {
  13249. this.hideLoadingUI();
  13250. this.stopRenderLoop();
  13251. // Release postProcesses
  13252. while (this.postProcesses.length) {
  13253. this.postProcesses[0].dispose();
  13254. }
  13255. // Empty texture
  13256. if (this._emptyTexture) {
  13257. this._releaseTexture(this._emptyTexture);
  13258. this._emptyTexture = null;
  13259. }
  13260. if (this._emptyCubeTexture) {
  13261. this._releaseTexture(this._emptyCubeTexture);
  13262. this._emptyCubeTexture = null;
  13263. }
  13264. // Rescale PP
  13265. if (this._rescalePostProcess) {
  13266. this._rescalePostProcess.dispose();
  13267. }
  13268. // Release scenes
  13269. while (this.scenes.length) {
  13270. this.scenes[0].dispose();
  13271. }
  13272. // Release audio engine
  13273. if (Engine.audioEngine) {
  13274. Engine.audioEngine.dispose();
  13275. }
  13276. // Release effects
  13277. this.releaseEffects();
  13278. // Unbind
  13279. this.unbindAllAttributes();
  13280. if (this._dummyFramebuffer) {
  13281. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13282. }
  13283. //WebVR
  13284. this.disableVR();
  13285. // Events
  13286. if (BABYLON.Tools.IsWindowObjectExist()) {
  13287. window.removeEventListener("blur", this._onBlur);
  13288. window.removeEventListener("focus", this._onFocus);
  13289. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13290. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13291. if (this._renderingCanvas) {
  13292. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13293. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13294. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13295. if (!this._doNotHandleContextLost) {
  13296. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13297. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13298. }
  13299. }
  13300. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13301. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13302. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13303. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13304. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13305. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13306. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13307. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13308. if (this._onVrDisplayConnect) {
  13309. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13310. if (this._onVrDisplayDisconnect) {
  13311. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13312. }
  13313. if (this._onVrDisplayPresentChange) {
  13314. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13315. }
  13316. this._onVrDisplayConnect = null;
  13317. this._onVrDisplayDisconnect = null;
  13318. }
  13319. }
  13320. // Remove from Instances
  13321. var index = Engine.Instances.indexOf(this);
  13322. if (index >= 0) {
  13323. Engine.Instances.splice(index, 1);
  13324. }
  13325. this._workingCanvas = null;
  13326. this._workingContext = null;
  13327. this._currentBufferPointers = [];
  13328. this._renderingCanvas = null;
  13329. this._currentProgram = null;
  13330. this.onResizeObservable.clear();
  13331. this.onCanvasBlurObservable.clear();
  13332. this.onCanvasFocusObservable.clear();
  13333. this.onCanvasPointerOutObservable.clear();
  13334. this.onBeginFrameObservable.clear();
  13335. this.onEndFrameObservable.clear();
  13336. BABYLON.Effect.ResetCache();
  13337. // Abort active requests
  13338. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13339. var request = _a[_i];
  13340. request.abort();
  13341. }
  13342. };
  13343. // Loading screen
  13344. Engine.prototype.displayLoadingUI = function () {
  13345. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13346. return;
  13347. }
  13348. var loadingScreen = this.loadingScreen;
  13349. if (loadingScreen) {
  13350. loadingScreen.displayLoadingUI();
  13351. }
  13352. };
  13353. Engine.prototype.hideLoadingUI = function () {
  13354. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13355. return;
  13356. }
  13357. var loadingScreen = this.loadingScreen;
  13358. if (loadingScreen) {
  13359. loadingScreen.hideLoadingUI();
  13360. }
  13361. };
  13362. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13363. get: function () {
  13364. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13365. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13366. return this._loadingScreen;
  13367. },
  13368. set: function (loadingScreen) {
  13369. this._loadingScreen = loadingScreen;
  13370. },
  13371. enumerable: true,
  13372. configurable: true
  13373. });
  13374. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13375. set: function (text) {
  13376. this.loadingScreen.loadingUIText = text;
  13377. },
  13378. enumerable: true,
  13379. configurable: true
  13380. });
  13381. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13382. set: function (color) {
  13383. this.loadingScreen.loadingUIBackgroundColor = color;
  13384. },
  13385. enumerable: true,
  13386. configurable: true
  13387. });
  13388. Engine.prototype.attachContextLostEvent = function (callback) {
  13389. if (this._renderingCanvas) {
  13390. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13391. }
  13392. };
  13393. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13394. if (this._renderingCanvas) {
  13395. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13396. }
  13397. };
  13398. Engine.prototype.getVertexShaderSource = function (program) {
  13399. var shaders = this._gl.getAttachedShaders(program);
  13400. if (!shaders) {
  13401. return null;
  13402. }
  13403. return this._gl.getShaderSource(shaders[0]);
  13404. };
  13405. Engine.prototype.getFragmentShaderSource = function (program) {
  13406. var shaders = this._gl.getAttachedShaders(program);
  13407. if (!shaders) {
  13408. return null;
  13409. }
  13410. return this._gl.getShaderSource(shaders[1]);
  13411. };
  13412. Engine.prototype.getError = function () {
  13413. return this._gl.getError();
  13414. };
  13415. // FPS
  13416. Engine.prototype.getFps = function () {
  13417. return this._fps;
  13418. };
  13419. Engine.prototype.getDeltaTime = function () {
  13420. return this._deltaTime;
  13421. };
  13422. Engine.prototype._measureFps = function () {
  13423. this._performanceMonitor.sampleFrame();
  13424. this._fps = this._performanceMonitor.averageFPS;
  13425. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13426. };
  13427. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13428. if (faceIndex === void 0) { faceIndex = -1; }
  13429. var gl = this._gl;
  13430. if (!this._dummyFramebuffer) {
  13431. var dummy = gl.createFramebuffer();
  13432. if (!dummy) {
  13433. throw new Error("Unable to create dummy framebuffer");
  13434. }
  13435. this._dummyFramebuffer = dummy;
  13436. }
  13437. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13438. if (faceIndex > -1) {
  13439. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13440. }
  13441. else {
  13442. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13443. }
  13444. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13445. var buffer;
  13446. switch (readType) {
  13447. case gl.UNSIGNED_BYTE:
  13448. buffer = new Uint8Array(4 * width * height);
  13449. readType = gl.UNSIGNED_BYTE;
  13450. break;
  13451. default:
  13452. buffer = new Float32Array(4 * width * height);
  13453. readType = gl.FLOAT;
  13454. break;
  13455. }
  13456. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13457. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13458. return buffer;
  13459. };
  13460. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13461. if (this._webGLVersion > 1) {
  13462. return this._caps.colorBufferFloat;
  13463. }
  13464. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13465. };
  13466. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13467. if (this._webGLVersion > 1) {
  13468. return this._caps.colorBufferFloat;
  13469. }
  13470. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13471. };
  13472. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13473. Engine.prototype._canRenderToFramebuffer = function (type) {
  13474. var gl = this._gl;
  13475. //clear existing errors
  13476. while (gl.getError() !== gl.NO_ERROR) { }
  13477. var successful = true;
  13478. var texture = gl.createTexture();
  13479. gl.bindTexture(gl.TEXTURE_2D, texture);
  13480. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13481. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13483. var fb = gl.createFramebuffer();
  13484. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13485. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13486. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13487. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13488. successful = successful && (gl.getError() === gl.NO_ERROR);
  13489. //try render by clearing frame buffer's color buffer
  13490. if (successful) {
  13491. gl.clear(gl.COLOR_BUFFER_BIT);
  13492. successful = successful && (gl.getError() === gl.NO_ERROR);
  13493. }
  13494. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13495. if (successful) {
  13496. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13497. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13498. var readFormat = gl.RGBA;
  13499. var readType = gl.UNSIGNED_BYTE;
  13500. var buffer = new Uint8Array(4);
  13501. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13502. successful = successful && (gl.getError() === gl.NO_ERROR);
  13503. }
  13504. //clean up
  13505. gl.deleteTexture(texture);
  13506. gl.deleteFramebuffer(fb);
  13507. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13508. //clear accumulated errors
  13509. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13510. return successful;
  13511. };
  13512. Engine.prototype._getWebGLTextureType = function (type) {
  13513. if (type === Engine.TEXTURETYPE_FLOAT) {
  13514. return this._gl.FLOAT;
  13515. }
  13516. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13517. // Add Half Float Constant.
  13518. return this._gl.HALF_FLOAT_OES;
  13519. }
  13520. return this._gl.UNSIGNED_BYTE;
  13521. };
  13522. ;
  13523. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13524. if (this._webGLVersion === 1) {
  13525. return this._gl.RGBA;
  13526. }
  13527. if (type === Engine.TEXTURETYPE_FLOAT) {
  13528. return this._gl.RGBA32F;
  13529. }
  13530. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13531. return this._gl.RGBA16F;
  13532. }
  13533. return this._gl.RGBA;
  13534. };
  13535. ;
  13536. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13537. if (type === Engine.TEXTURETYPE_FLOAT) {
  13538. return this._gl.RGBA32F;
  13539. }
  13540. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13541. return this._gl.RGBA16F;
  13542. }
  13543. return this._gl.RGBA8;
  13544. };
  13545. ;
  13546. Engine.prototype.createQuery = function () {
  13547. return this._gl.createQuery();
  13548. };
  13549. Engine.prototype.deleteQuery = function (query) {
  13550. this._gl.deleteQuery(query);
  13551. return this;
  13552. };
  13553. Engine.prototype.isQueryResultAvailable = function (query) {
  13554. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13555. };
  13556. Engine.prototype.getQueryResult = function (query) {
  13557. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13558. };
  13559. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13560. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13561. this._gl.beginQuery(glAlgorithm, query);
  13562. return this;
  13563. };
  13564. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13565. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13566. this._gl.endQuery(glAlgorithm);
  13567. return this;
  13568. };
  13569. /* Time queries */
  13570. Engine.prototype._createTimeQuery = function () {
  13571. var timerQuery = this._caps.timerQuery;
  13572. if (timerQuery.createQueryEXT) {
  13573. return timerQuery.createQueryEXT();
  13574. }
  13575. return this.createQuery();
  13576. };
  13577. Engine.prototype._deleteTimeQuery = function (query) {
  13578. var timerQuery = this._caps.timerQuery;
  13579. if (timerQuery.deleteQueryEXT) {
  13580. timerQuery.deleteQueryEXT(query);
  13581. return;
  13582. }
  13583. this.deleteQuery(query);
  13584. };
  13585. Engine.prototype._getTimeQueryResult = function (query) {
  13586. var timerQuery = this._caps.timerQuery;
  13587. if (timerQuery.getQueryObjectEXT) {
  13588. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13589. }
  13590. return this.getQueryResult(query);
  13591. };
  13592. Engine.prototype._getTimeQueryAvailability = function (query) {
  13593. var timerQuery = this._caps.timerQuery;
  13594. if (timerQuery.getQueryObjectEXT) {
  13595. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13596. }
  13597. return this.isQueryResultAvailable(query);
  13598. };
  13599. Engine.prototype.startTimeQuery = function () {
  13600. var timerQuery = this._caps.timerQuery;
  13601. if (!timerQuery) {
  13602. return null;
  13603. }
  13604. var token = new BABYLON._TimeToken();
  13605. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13606. if (this._caps.canUseTimestampForTimerQuery) {
  13607. token._startTimeQuery = this._createTimeQuery();
  13608. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13609. }
  13610. else {
  13611. if (this._currentNonTimestampToken) {
  13612. return this._currentNonTimestampToken;
  13613. }
  13614. token._timeElapsedQuery = this._createTimeQuery();
  13615. if (timerQuery.beginQueryEXT) {
  13616. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13617. }
  13618. else {
  13619. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13620. }
  13621. this._currentNonTimestampToken = token;
  13622. }
  13623. return token;
  13624. };
  13625. Engine.prototype.endTimeQuery = function (token) {
  13626. var timerQuery = this._caps.timerQuery;
  13627. if (!timerQuery || !token) {
  13628. return -1;
  13629. }
  13630. if (this._caps.canUseTimestampForTimerQuery) {
  13631. if (!token._startTimeQuery) {
  13632. return -1;
  13633. }
  13634. if (!token._endTimeQuery) {
  13635. token._endTimeQuery = this._createTimeQuery();
  13636. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13637. }
  13638. }
  13639. else if (!token._timeElapsedQueryEnded) {
  13640. if (!token._timeElapsedQuery) {
  13641. return -1;
  13642. }
  13643. if (timerQuery.endQueryEXT) {
  13644. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13645. }
  13646. else {
  13647. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13648. }
  13649. token._timeElapsedQueryEnded = true;
  13650. }
  13651. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13652. var available = false;
  13653. if (token._endTimeQuery) {
  13654. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13655. }
  13656. else if (token._timeElapsedQuery) {
  13657. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13658. }
  13659. if (available && !disjoint) {
  13660. var result = 0;
  13661. if (this._caps.canUseTimestampForTimerQuery) {
  13662. if (!token._startTimeQuery || !token._endTimeQuery) {
  13663. return -1;
  13664. }
  13665. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13666. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13667. result = timeEnd - timeStart;
  13668. this._deleteTimeQuery(token._startTimeQuery);
  13669. this._deleteTimeQuery(token._endTimeQuery);
  13670. token._startTimeQuery = null;
  13671. token._endTimeQuery = null;
  13672. }
  13673. else {
  13674. if (!token._timeElapsedQuery) {
  13675. return -1;
  13676. }
  13677. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13678. this._deleteTimeQuery(token._timeElapsedQuery);
  13679. token._timeElapsedQuery = null;
  13680. token._timeElapsedQueryEnded = false;
  13681. this._currentNonTimestampToken = null;
  13682. }
  13683. return result;
  13684. }
  13685. return -1;
  13686. };
  13687. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13688. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13689. };
  13690. // Transform feedback
  13691. Engine.prototype.createTransformFeedback = function () {
  13692. return this._gl.createTransformFeedback();
  13693. };
  13694. Engine.prototype.deleteTransformFeedback = function (value) {
  13695. this._gl.deleteTransformFeedback(value);
  13696. };
  13697. Engine.prototype.bindTransformFeedback = function (value) {
  13698. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13699. };
  13700. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13701. if (usePoints === void 0) { usePoints = true; }
  13702. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13703. };
  13704. Engine.prototype.endTransformFeedback = function () {
  13705. this._gl.endTransformFeedback();
  13706. };
  13707. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13708. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13709. };
  13710. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13711. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13712. };
  13713. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13714. var _this = this;
  13715. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13716. this._activeRequests.push(request);
  13717. request.onCompleteObservable.add(function (request) {
  13718. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13719. });
  13720. return request;
  13721. };
  13722. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13723. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13724. var onload = function (data) {
  13725. loadedFiles[index] = data;
  13726. loadedFiles._internalCount++;
  13727. if (loadedFiles._internalCount === 6) {
  13728. onfinish(loadedFiles);
  13729. }
  13730. };
  13731. var onerror = function (request, exception) {
  13732. if (onErrorCallBack && request) {
  13733. onErrorCallBack(request.status + " " + request.statusText, exception);
  13734. }
  13735. };
  13736. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13737. };
  13738. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13739. if (onError === void 0) { onError = null; }
  13740. var loadedFiles = [];
  13741. loadedFiles._internalCount = 0;
  13742. for (var index = 0; index < 6; index++) {
  13743. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13744. }
  13745. };
  13746. // Statics
  13747. Engine.isSupported = function () {
  13748. try {
  13749. var tempcanvas = document.createElement("canvas");
  13750. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13751. return gl != null && !!window.WebGLRenderingContext;
  13752. }
  13753. catch (e) {
  13754. return false;
  13755. }
  13756. };
  13757. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13758. Engine.ExceptionList = [
  13759. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13760. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13761. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13762. ];
  13763. Engine.Instances = new Array();
  13764. // Const statics
  13765. Engine._ALPHA_DISABLE = 0;
  13766. Engine._ALPHA_ADD = 1;
  13767. Engine._ALPHA_COMBINE = 2;
  13768. Engine._ALPHA_SUBTRACT = 3;
  13769. Engine._ALPHA_MULTIPLY = 4;
  13770. Engine._ALPHA_MAXIMIZED = 5;
  13771. Engine._ALPHA_ONEONE = 6;
  13772. Engine._ALPHA_PREMULTIPLIED = 7;
  13773. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13774. Engine._ALPHA_INTERPOLATE = 9;
  13775. Engine._ALPHA_SCREENMODE = 10;
  13776. Engine._DELAYLOADSTATE_NONE = 0;
  13777. Engine._DELAYLOADSTATE_LOADED = 1;
  13778. Engine._DELAYLOADSTATE_LOADING = 2;
  13779. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13780. Engine._TEXTUREFORMAT_ALPHA = 0;
  13781. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13782. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13783. Engine._TEXTUREFORMAT_RGB = 4;
  13784. Engine._TEXTUREFORMAT_RGBA = 5;
  13785. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13786. Engine._TEXTURETYPE_FLOAT = 1;
  13787. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13788. // Depht or Stencil test Constants.
  13789. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13790. 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.
  13791. 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.
  13792. 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.
  13793. 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.
  13794. 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.
  13795. 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.
  13796. 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.
  13797. // Stencil Actions Constants.
  13798. Engine._KEEP = 0x1E00;
  13799. Engine._REPLACE = 0x1E01;
  13800. Engine._INCR = 0x1E02;
  13801. Engine._DECR = 0x1E03;
  13802. Engine._INVERT = 0x150A;
  13803. Engine._INCR_WRAP = 0x8507;
  13804. Engine._DECR_WRAP = 0x8508;
  13805. // Texture rescaling mode
  13806. Engine._SCALEMODE_FLOOR = 1;
  13807. Engine._SCALEMODE_NEAREST = 2;
  13808. Engine._SCALEMODE_CEILING = 3;
  13809. // Updatable statics so stick with vars here
  13810. Engine.CollisionsEpsilon = 0.001;
  13811. Engine.CodeRepository = "src/";
  13812. Engine.ShadersRepository = "src/Shaders/";
  13813. return Engine;
  13814. }());
  13815. BABYLON.Engine = Engine;
  13816. })(BABYLON || (BABYLON = {}));
  13817. //# sourceMappingURL=babylon.engine.js.map
  13818. var BABYLON;
  13819. (function (BABYLON) {
  13820. /**
  13821. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13822. */
  13823. var Node = /** @class */ (function () {
  13824. /**
  13825. * @constructor
  13826. * @param {string} name - the name and id to be given to this node
  13827. * @param {BABYLON.Scene} the scene this node will be added to
  13828. */
  13829. function Node(name, scene) {
  13830. if (scene === void 0) { scene = null; }
  13831. this.state = "";
  13832. this.metadata = null;
  13833. this.doNotSerialize = false;
  13834. this.animations = new Array();
  13835. this._ranges = {};
  13836. this._isEnabled = true;
  13837. this._isReady = true;
  13838. this._currentRenderId = -1;
  13839. this._parentRenderId = -1;
  13840. /**
  13841. * An event triggered when the mesh is disposed.
  13842. * @type {BABYLON.Observable}
  13843. */
  13844. this.onDisposeObservable = new BABYLON.Observable();
  13845. // Behaviors
  13846. this._behaviors = new Array();
  13847. this.name = name;
  13848. this.id = name;
  13849. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13850. this.uniqueId = this._scene.getUniqueId();
  13851. this._initCache();
  13852. }
  13853. Object.defineProperty(Node.prototype, "parent", {
  13854. get: function () {
  13855. return this._parentNode;
  13856. },
  13857. set: function (parent) {
  13858. if (this._parentNode === parent) {
  13859. return;
  13860. }
  13861. // Remove self from list of children of parent
  13862. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13863. var index = this._parentNode._children.indexOf(this);
  13864. if (index !== -1) {
  13865. this._parentNode._children.splice(index, 1);
  13866. }
  13867. }
  13868. // Store new parent
  13869. this._parentNode = parent;
  13870. // Add as child to new parent
  13871. if (this._parentNode) {
  13872. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13873. this._parentNode._children = new Array();
  13874. }
  13875. this._parentNode._children.push(this);
  13876. }
  13877. },
  13878. enumerable: true,
  13879. configurable: true
  13880. });
  13881. Node.prototype.getClassName = function () {
  13882. return "Node";
  13883. };
  13884. Object.defineProperty(Node.prototype, "onDispose", {
  13885. set: function (callback) {
  13886. if (this._onDisposeObserver) {
  13887. this.onDisposeObservable.remove(this._onDisposeObserver);
  13888. }
  13889. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13890. },
  13891. enumerable: true,
  13892. configurable: true
  13893. });
  13894. Node.prototype.getScene = function () {
  13895. return this._scene;
  13896. };
  13897. Node.prototype.getEngine = function () {
  13898. return this._scene.getEngine();
  13899. };
  13900. Node.prototype.addBehavior = function (behavior) {
  13901. var _this = this;
  13902. var index = this._behaviors.indexOf(behavior);
  13903. if (index !== -1) {
  13904. return this;
  13905. }
  13906. behavior.init();
  13907. if (this._scene.isLoading) {
  13908. // We defer the attach when the scene will be loaded
  13909. var observer = this._scene.onDataLoadedObservable.add(function () {
  13910. behavior.attach(_this);
  13911. setTimeout(function () {
  13912. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13913. _this._scene.onDataLoadedObservable.remove(observer);
  13914. }, 0);
  13915. });
  13916. }
  13917. else {
  13918. behavior.attach(this);
  13919. }
  13920. this._behaviors.push(behavior);
  13921. return this;
  13922. };
  13923. Node.prototype.removeBehavior = function (behavior) {
  13924. var index = this._behaviors.indexOf(behavior);
  13925. if (index === -1) {
  13926. return this;
  13927. }
  13928. this._behaviors[index].detach();
  13929. this._behaviors.splice(index, 1);
  13930. return this;
  13931. };
  13932. Object.defineProperty(Node.prototype, "behaviors", {
  13933. get: function () {
  13934. return this._behaviors;
  13935. },
  13936. enumerable: true,
  13937. configurable: true
  13938. });
  13939. Node.prototype.getBehaviorByName = function (name) {
  13940. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13941. var behavior = _a[_i];
  13942. if (behavior.name === name) {
  13943. return behavior;
  13944. }
  13945. }
  13946. return null;
  13947. };
  13948. // override it in derived class
  13949. Node.prototype.getWorldMatrix = function () {
  13950. return BABYLON.Matrix.Identity();
  13951. };
  13952. // override it in derived class if you add new variables to the cache
  13953. // and call the parent class method
  13954. Node.prototype._initCache = function () {
  13955. this._cache = {};
  13956. this._cache.parent = undefined;
  13957. };
  13958. Node.prototype.updateCache = function (force) {
  13959. if (!force && this.isSynchronized())
  13960. return;
  13961. this._cache.parent = this.parent;
  13962. this._updateCache();
  13963. };
  13964. // override it in derived class if you add new variables to the cache
  13965. // and call the parent class method if !ignoreParentClass
  13966. Node.prototype._updateCache = function (ignoreParentClass) {
  13967. };
  13968. // override it in derived class if you add new variables to the cache
  13969. Node.prototype._isSynchronized = function () {
  13970. return true;
  13971. };
  13972. Node.prototype._markSyncedWithParent = function () {
  13973. if (this.parent) {
  13974. this._parentRenderId = this.parent._currentRenderId;
  13975. }
  13976. };
  13977. Node.prototype.isSynchronizedWithParent = function () {
  13978. if (!this.parent) {
  13979. return true;
  13980. }
  13981. if (this._parentRenderId !== this.parent._currentRenderId) {
  13982. return false;
  13983. }
  13984. return this.parent.isSynchronized();
  13985. };
  13986. Node.prototype.isSynchronized = function (updateCache) {
  13987. var check = this.hasNewParent();
  13988. check = check || !this.isSynchronizedWithParent();
  13989. check = check || !this._isSynchronized();
  13990. if (updateCache)
  13991. this.updateCache(true);
  13992. return !check;
  13993. };
  13994. Node.prototype.hasNewParent = function (update) {
  13995. if (this._cache.parent === this.parent)
  13996. return false;
  13997. if (update)
  13998. this._cache.parent = this.parent;
  13999. return true;
  14000. };
  14001. /**
  14002. * Is this node ready to be used/rendered
  14003. * @return {boolean} is it ready
  14004. */
  14005. Node.prototype.isReady = function () {
  14006. return this._isReady;
  14007. };
  14008. /**
  14009. * Is this node enabled.
  14010. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true.
  14011. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  14012. * @return {boolean} whether this node (and its parent) is enabled.
  14013. * @see setEnabled
  14014. */
  14015. Node.prototype.isEnabled = function (checkAncestors) {
  14016. if (checkAncestors === void 0) { checkAncestors = true; }
  14017. if (checkAncestors === false) {
  14018. return this._isEnabled;
  14019. }
  14020. if (this._isEnabled === false) {
  14021. return false;
  14022. }
  14023. if (this.parent !== undefined && this.parent !== null) {
  14024. return this.parent.isEnabled(checkAncestors);
  14025. }
  14026. return true;
  14027. };
  14028. /**
  14029. * Set the enabled state of this node.
  14030. * @param {boolean} value - the new enabled state
  14031. * @see isEnabled
  14032. */
  14033. Node.prototype.setEnabled = function (value) {
  14034. this._isEnabled = value;
  14035. };
  14036. /**
  14037. * Is this node a descendant of the given node.
  14038. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14039. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14040. * @see parent
  14041. */
  14042. Node.prototype.isDescendantOf = function (ancestor) {
  14043. if (this.parent) {
  14044. if (this.parent === ancestor) {
  14045. return true;
  14046. }
  14047. return this.parent.isDescendantOf(ancestor);
  14048. }
  14049. return false;
  14050. };
  14051. /**
  14052. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14053. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14054. * @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.
  14055. * @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.
  14056. */
  14057. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14058. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14059. if (!this._children) {
  14060. return;
  14061. }
  14062. for (var index = 0; index < this._children.length; index++) {
  14063. var item = this._children[index];
  14064. if (!predicate || predicate(item)) {
  14065. results.push(item);
  14066. }
  14067. if (!directDescendantsOnly) {
  14068. item._getDescendants(results, false, predicate);
  14069. }
  14070. }
  14071. };
  14072. /**
  14073. * Will return all nodes that have this node as ascendant.
  14074. * @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.
  14075. * @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.
  14076. * @return {BABYLON.Node[]} all children nodes of all types.
  14077. */
  14078. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14079. var results = new Array();
  14080. this._getDescendants(results, directDescendantsOnly, predicate);
  14081. return results;
  14082. };
  14083. /**
  14084. * Get all child-meshes of this node.
  14085. */
  14086. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14087. var results = [];
  14088. this._getDescendants(results, directDescendantsOnly, function (node) {
  14089. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14090. });
  14091. return results;
  14092. };
  14093. /**
  14094. * Get all child-transformNodes of this node.
  14095. */
  14096. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14097. var results = [];
  14098. this._getDescendants(results, directDescendantsOnly, function (node) {
  14099. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14100. });
  14101. return results;
  14102. };
  14103. /**
  14104. * Get all direct children of this node.
  14105. */
  14106. Node.prototype.getChildren = function (predicate) {
  14107. return this.getDescendants(true, predicate);
  14108. };
  14109. Node.prototype._setReady = function (state) {
  14110. if (state === this._isReady) {
  14111. return;
  14112. }
  14113. if (!state) {
  14114. this._isReady = false;
  14115. return;
  14116. }
  14117. this._isReady = true;
  14118. if (this.onReady) {
  14119. this.onReady(this);
  14120. }
  14121. };
  14122. Node.prototype.getAnimationByName = function (name) {
  14123. for (var i = 0; i < this.animations.length; i++) {
  14124. var animation = this.animations[i];
  14125. if (animation.name === name) {
  14126. return animation;
  14127. }
  14128. }
  14129. return null;
  14130. };
  14131. Node.prototype.createAnimationRange = function (name, from, to) {
  14132. // check name not already in use
  14133. if (!this._ranges[name]) {
  14134. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14135. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14136. if (this.animations[i]) {
  14137. this.animations[i].createRange(name, from, to);
  14138. }
  14139. }
  14140. }
  14141. };
  14142. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14143. if (deleteFrames === void 0) { deleteFrames = true; }
  14144. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14145. if (this.animations[i]) {
  14146. this.animations[i].deleteRange(name, deleteFrames);
  14147. }
  14148. }
  14149. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14150. };
  14151. Node.prototype.getAnimationRange = function (name) {
  14152. return this._ranges[name];
  14153. };
  14154. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14155. var range = this.getAnimationRange(name);
  14156. if (!range) {
  14157. return;
  14158. }
  14159. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14160. };
  14161. Node.prototype.serializeAnimationRanges = function () {
  14162. var serializationRanges = [];
  14163. for (var name in this._ranges) {
  14164. var localRange = this._ranges[name];
  14165. if (!localRange) {
  14166. continue;
  14167. }
  14168. var range = {};
  14169. range.name = name;
  14170. range.from = localRange.from;
  14171. range.to = localRange.to;
  14172. serializationRanges.push(range);
  14173. }
  14174. return serializationRanges;
  14175. };
  14176. // override it in derived class
  14177. Node.prototype.computeWorldMatrix = function (force) {
  14178. return BABYLON.Matrix.Identity();
  14179. };
  14180. Node.prototype.dispose = function () {
  14181. this.parent = null;
  14182. // Callback
  14183. this.onDisposeObservable.notifyObservers(this);
  14184. this.onDisposeObservable.clear();
  14185. // Behaviors
  14186. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14187. var behavior = _a[_i];
  14188. behavior.detach();
  14189. }
  14190. this._behaviors = [];
  14191. };
  14192. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14193. if (parsedNode.ranges) {
  14194. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14195. var data = parsedNode.ranges[index];
  14196. node.createAnimationRange(data.name, data.from, data.to);
  14197. }
  14198. }
  14199. };
  14200. __decorate([
  14201. BABYLON.serialize()
  14202. ], Node.prototype, "name", void 0);
  14203. __decorate([
  14204. BABYLON.serialize()
  14205. ], Node.prototype, "id", void 0);
  14206. __decorate([
  14207. BABYLON.serialize()
  14208. ], Node.prototype, "uniqueId", void 0);
  14209. __decorate([
  14210. BABYLON.serialize()
  14211. ], Node.prototype, "state", void 0);
  14212. __decorate([
  14213. BABYLON.serialize()
  14214. ], Node.prototype, "metadata", void 0);
  14215. return Node;
  14216. }());
  14217. BABYLON.Node = Node;
  14218. })(BABYLON || (BABYLON = {}));
  14219. //# sourceMappingURL=babylon.node.js.map
  14220. var BABYLON;
  14221. (function (BABYLON) {
  14222. var BoundingSphere = /** @class */ (function () {
  14223. function BoundingSphere(minimum, maximum) {
  14224. this.minimum = minimum;
  14225. this.maximum = maximum;
  14226. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14227. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14228. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14229. this.radius = distance * 0.5;
  14230. this.centerWorld = BABYLON.Vector3.Zero();
  14231. this._update(BABYLON.Matrix.Identity());
  14232. }
  14233. // Methods
  14234. BoundingSphere.prototype._update = function (world) {
  14235. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14236. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14237. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14238. };
  14239. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14240. for (var i = 0; i < 6; i++) {
  14241. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14242. return false;
  14243. }
  14244. return true;
  14245. };
  14246. BoundingSphere.prototype.intersectsPoint = function (point) {
  14247. var x = this.centerWorld.x - point.x;
  14248. var y = this.centerWorld.y - point.y;
  14249. var z = this.centerWorld.z - point.z;
  14250. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14251. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14252. return false;
  14253. return true;
  14254. };
  14255. // Statics
  14256. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14257. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14258. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14259. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14260. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14261. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14262. return false;
  14263. return true;
  14264. };
  14265. return BoundingSphere;
  14266. }());
  14267. BABYLON.BoundingSphere = BoundingSphere;
  14268. })(BABYLON || (BABYLON = {}));
  14269. //# sourceMappingURL=babylon.boundingSphere.js.map
  14270. var BABYLON;
  14271. (function (BABYLON) {
  14272. var BoundingBox = /** @class */ (function () {
  14273. function BoundingBox(minimum, maximum) {
  14274. this.minimum = minimum;
  14275. this.maximum = maximum;
  14276. this.vectors = new Array();
  14277. this.vectorsWorld = new Array();
  14278. // Bounding vectors
  14279. this.vectors.push(this.minimum.clone());
  14280. this.vectors.push(this.maximum.clone());
  14281. this.vectors.push(this.minimum.clone());
  14282. this.vectors[2].x = this.maximum.x;
  14283. this.vectors.push(this.minimum.clone());
  14284. this.vectors[3].y = this.maximum.y;
  14285. this.vectors.push(this.minimum.clone());
  14286. this.vectors[4].z = this.maximum.z;
  14287. this.vectors.push(this.maximum.clone());
  14288. this.vectors[5].z = this.minimum.z;
  14289. this.vectors.push(this.maximum.clone());
  14290. this.vectors[6].x = this.minimum.x;
  14291. this.vectors.push(this.maximum.clone());
  14292. this.vectors[7].y = this.minimum.y;
  14293. // OBB
  14294. this.center = this.maximum.add(this.minimum).scale(0.5);
  14295. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14296. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14297. // World
  14298. for (var index = 0; index < this.vectors.length; index++) {
  14299. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14300. }
  14301. this.minimumWorld = BABYLON.Vector3.Zero();
  14302. this.maximumWorld = BABYLON.Vector3.Zero();
  14303. this.centerWorld = BABYLON.Vector3.Zero();
  14304. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14305. this._update(BABYLON.Matrix.Identity());
  14306. }
  14307. // Methods
  14308. BoundingBox.prototype.getWorldMatrix = function () {
  14309. return this._worldMatrix;
  14310. };
  14311. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14312. this._worldMatrix.copyFrom(matrix);
  14313. return this;
  14314. };
  14315. BoundingBox.prototype._update = function (world) {
  14316. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14317. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14318. for (var index = 0; index < this.vectors.length; index++) {
  14319. var v = this.vectorsWorld[index];
  14320. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14321. if (v.x < this.minimumWorld.x)
  14322. this.minimumWorld.x = v.x;
  14323. if (v.y < this.minimumWorld.y)
  14324. this.minimumWorld.y = v.y;
  14325. if (v.z < this.minimumWorld.z)
  14326. this.minimumWorld.z = v.z;
  14327. if (v.x > this.maximumWorld.x)
  14328. this.maximumWorld.x = v.x;
  14329. if (v.y > this.maximumWorld.y)
  14330. this.maximumWorld.y = v.y;
  14331. if (v.z > this.maximumWorld.z)
  14332. this.maximumWorld.z = v.z;
  14333. }
  14334. // Extend
  14335. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14336. this.extendSizeWorld.scaleInPlace(0.5);
  14337. // OBB
  14338. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14339. this.centerWorld.scaleInPlace(0.5);
  14340. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14341. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14342. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14343. this._worldMatrix = world;
  14344. };
  14345. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14346. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14347. };
  14348. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14349. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14350. };
  14351. BoundingBox.prototype.intersectsPoint = function (point) {
  14352. var delta = -BABYLON.Epsilon;
  14353. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14354. return false;
  14355. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14356. return false;
  14357. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14358. return false;
  14359. return true;
  14360. };
  14361. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14362. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14363. };
  14364. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14365. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14366. return false;
  14367. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14368. return false;
  14369. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14370. return false;
  14371. return true;
  14372. };
  14373. // Statics
  14374. BoundingBox.Intersects = function (box0, box1) {
  14375. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14376. return false;
  14377. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14378. return false;
  14379. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14380. return false;
  14381. return true;
  14382. };
  14383. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14384. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14385. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14386. return (num <= (sphereRadius * sphereRadius));
  14387. };
  14388. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14389. for (var p = 0; p < 6; p++) {
  14390. for (var i = 0; i < 8; i++) {
  14391. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14392. return false;
  14393. }
  14394. }
  14395. }
  14396. return true;
  14397. };
  14398. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14399. for (var p = 0; p < 6; p++) {
  14400. var inCount = 8;
  14401. for (var i = 0; i < 8; i++) {
  14402. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14403. --inCount;
  14404. }
  14405. else {
  14406. break;
  14407. }
  14408. }
  14409. if (inCount === 0)
  14410. return false;
  14411. }
  14412. return true;
  14413. };
  14414. return BoundingBox;
  14415. }());
  14416. BABYLON.BoundingBox = BoundingBox;
  14417. })(BABYLON || (BABYLON = {}));
  14418. //# sourceMappingURL=babylon.boundingBox.js.map
  14419. var BABYLON;
  14420. (function (BABYLON) {
  14421. var computeBoxExtents = function (axis, box) {
  14422. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14423. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14424. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14425. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14426. var r = r0 + r1 + r2;
  14427. return {
  14428. min: p - r,
  14429. max: p + r
  14430. };
  14431. };
  14432. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14433. var axisOverlap = function (axis, box0, box1) {
  14434. var result0 = computeBoxExtents(axis, box0);
  14435. var result1 = computeBoxExtents(axis, box1);
  14436. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14437. };
  14438. var BoundingInfo = /** @class */ (function () {
  14439. function BoundingInfo(minimum, maximum) {
  14440. this.minimum = minimum;
  14441. this.maximum = maximum;
  14442. this._isLocked = false;
  14443. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14444. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14445. }
  14446. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14447. get: function () {
  14448. return this._isLocked;
  14449. },
  14450. set: function (value) {
  14451. this._isLocked = value;
  14452. },
  14453. enumerable: true,
  14454. configurable: true
  14455. });
  14456. // Methods
  14457. BoundingInfo.prototype.update = function (world) {
  14458. if (this._isLocked) {
  14459. return;
  14460. }
  14461. this.boundingBox._update(world);
  14462. this.boundingSphere._update(world);
  14463. };
  14464. /**
  14465. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14466. * @param center New center of the bounding info
  14467. * @param extend New extend of the bounding info
  14468. */
  14469. BoundingInfo.prototype.centerOn = function (center, extend) {
  14470. this.minimum = center.subtract(extend);
  14471. this.maximum = center.add(extend);
  14472. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14473. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14474. return this;
  14475. };
  14476. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14477. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14478. return false;
  14479. return this.boundingBox.isInFrustum(frustumPlanes);
  14480. };
  14481. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14482. /**
  14483. * Gets the world distance between the min and max points of the bounding box
  14484. */
  14485. get: function () {
  14486. var boundingBox = this.boundingBox;
  14487. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14488. return size.length();
  14489. },
  14490. enumerable: true,
  14491. configurable: true
  14492. });
  14493. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14494. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14495. };
  14496. BoundingInfo.prototype._checkCollision = function (collider) {
  14497. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14498. };
  14499. BoundingInfo.prototype.intersectsPoint = function (point) {
  14500. if (!this.boundingSphere.centerWorld) {
  14501. return false;
  14502. }
  14503. if (!this.boundingSphere.intersectsPoint(point)) {
  14504. return false;
  14505. }
  14506. if (!this.boundingBox.intersectsPoint(point)) {
  14507. return false;
  14508. }
  14509. return true;
  14510. };
  14511. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14512. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14513. return false;
  14514. }
  14515. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14516. return false;
  14517. }
  14518. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14519. return false;
  14520. }
  14521. if (!precise) {
  14522. return true;
  14523. }
  14524. var box0 = this.boundingBox;
  14525. var box1 = boundingInfo.boundingBox;
  14526. if (!axisOverlap(box0.directions[0], box0, box1))
  14527. return false;
  14528. if (!axisOverlap(box0.directions[1], box0, box1))
  14529. return false;
  14530. if (!axisOverlap(box0.directions[2], box0, box1))
  14531. return false;
  14532. if (!axisOverlap(box1.directions[0], box0, box1))
  14533. return false;
  14534. if (!axisOverlap(box1.directions[1], box0, box1))
  14535. return false;
  14536. if (!axisOverlap(box1.directions[2], box0, box1))
  14537. return false;
  14538. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14539. return false;
  14540. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14541. return false;
  14542. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14543. return false;
  14544. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14545. return false;
  14546. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14547. return false;
  14548. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14549. return false;
  14550. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14551. return false;
  14552. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14553. return false;
  14554. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14555. return false;
  14556. return true;
  14557. };
  14558. return BoundingInfo;
  14559. }());
  14560. BABYLON.BoundingInfo = BoundingInfo;
  14561. })(BABYLON || (BABYLON = {}));
  14562. //# sourceMappingURL=babylon.boundingInfo.js.map
  14563. var BABYLON;
  14564. (function (BABYLON) {
  14565. var TransformNode = /** @class */ (function (_super) {
  14566. __extends(TransformNode, _super);
  14567. function TransformNode(name, scene, isPure) {
  14568. if (scene === void 0) { scene = null; }
  14569. if (isPure === void 0) { isPure = true; }
  14570. var _this = _super.call(this, name, scene) || this;
  14571. // Properties
  14572. _this._rotation = BABYLON.Vector3.Zero();
  14573. _this._scaling = BABYLON.Vector3.One();
  14574. _this._isDirty = false;
  14575. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14576. _this.scalingDeterminant = 1;
  14577. _this.infiniteDistance = false;
  14578. _this.position = BABYLON.Vector3.Zero();
  14579. _this._localWorld = BABYLON.Matrix.Zero();
  14580. _this._worldMatrix = BABYLON.Matrix.Zero();
  14581. _this._worldMatrixDeterminant = 0;
  14582. _this._absolutePosition = BABYLON.Vector3.Zero();
  14583. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14584. _this._postMultiplyPivotMatrix = false;
  14585. _this._isWorldMatrixFrozen = false;
  14586. /**
  14587. * An event triggered after the world matrix is updated
  14588. * @type {BABYLON.Observable}
  14589. */
  14590. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14591. _this._nonUniformScaling = false;
  14592. if (isPure) {
  14593. _this.getScene().addTransformNode(_this);
  14594. }
  14595. return _this;
  14596. }
  14597. Object.defineProperty(TransformNode.prototype, "rotation", {
  14598. /**
  14599. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14600. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14601. * Default : (0.0, 0.0, 0.0)
  14602. */
  14603. get: function () {
  14604. return this._rotation;
  14605. },
  14606. set: function (newRotation) {
  14607. this._rotation = newRotation;
  14608. },
  14609. enumerable: true,
  14610. configurable: true
  14611. });
  14612. Object.defineProperty(TransformNode.prototype, "scaling", {
  14613. /**
  14614. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14615. * Default : (1.0, 1.0, 1.0)
  14616. */
  14617. get: function () {
  14618. return this._scaling;
  14619. },
  14620. /**
  14621. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14622. * Default : (1.0, 1.0, 1.0)
  14623. */
  14624. set: function (newScaling) {
  14625. this._scaling = newScaling;
  14626. },
  14627. enumerable: true,
  14628. configurable: true
  14629. });
  14630. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14631. /**
  14632. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14633. * It's null by default.
  14634. * 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)
  14635. */
  14636. get: function () {
  14637. return this._rotationQuaternion;
  14638. },
  14639. set: function (quaternion) {
  14640. this._rotationQuaternion = quaternion;
  14641. //reset the rotation vector.
  14642. if (quaternion && this.rotation.length()) {
  14643. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14644. }
  14645. },
  14646. enumerable: true,
  14647. configurable: true
  14648. });
  14649. /**
  14650. * Returns the latest update of the World matrix
  14651. * Returns a Matrix.
  14652. */
  14653. TransformNode.prototype.getWorldMatrix = function () {
  14654. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14655. this.computeWorldMatrix();
  14656. }
  14657. return this._worldMatrix;
  14658. };
  14659. /**
  14660. * Returns the latest update of the World matrix determinant.
  14661. */
  14662. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14663. return this._worldMatrixDeterminant;
  14664. };
  14665. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14666. /**
  14667. * Returns directly the latest state of the mesh World matrix.
  14668. * A Matrix is returned.
  14669. */
  14670. get: function () {
  14671. return this._worldMatrix;
  14672. },
  14673. enumerable: true,
  14674. configurable: true
  14675. });
  14676. /**
  14677. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14678. * Returns the AbstractMesh.
  14679. */
  14680. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14681. this._poseMatrix.copyFrom(matrix);
  14682. return this;
  14683. };
  14684. /**
  14685. * Returns the mesh Pose matrix.
  14686. * Returned object : Matrix
  14687. */
  14688. TransformNode.prototype.getPoseMatrix = function () {
  14689. return this._poseMatrix;
  14690. };
  14691. TransformNode.prototype._isSynchronized = function () {
  14692. if (this._isDirty) {
  14693. return false;
  14694. }
  14695. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14696. return false;
  14697. if (this._cache.pivotMatrixUpdated) {
  14698. return false;
  14699. }
  14700. if (this.infiniteDistance) {
  14701. return false;
  14702. }
  14703. if (!this._cache.position.equals(this.position))
  14704. return false;
  14705. if (this.rotationQuaternion) {
  14706. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14707. return false;
  14708. }
  14709. if (!this._cache.rotation.equals(this.rotation))
  14710. return false;
  14711. if (!this._cache.scaling.equals(this.scaling))
  14712. return false;
  14713. return true;
  14714. };
  14715. TransformNode.prototype._initCache = function () {
  14716. _super.prototype._initCache.call(this);
  14717. this._cache.localMatrixUpdated = false;
  14718. this._cache.position = BABYLON.Vector3.Zero();
  14719. this._cache.scaling = BABYLON.Vector3.Zero();
  14720. this._cache.rotation = BABYLON.Vector3.Zero();
  14721. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14722. this._cache.billboardMode = -1;
  14723. };
  14724. TransformNode.prototype.markAsDirty = function (property) {
  14725. if (property === "rotation") {
  14726. this.rotationQuaternion = null;
  14727. }
  14728. this._currentRenderId = Number.MAX_VALUE;
  14729. this._isDirty = true;
  14730. return this;
  14731. };
  14732. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14733. /**
  14734. * Returns the current mesh absolute position.
  14735. * Retuns a Vector3.
  14736. */
  14737. get: function () {
  14738. return this._absolutePosition;
  14739. },
  14740. enumerable: true,
  14741. configurable: true
  14742. });
  14743. /**
  14744. * Sets a new pivot matrix to the mesh.
  14745. * Returns the AbstractMesh.
  14746. */
  14747. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14748. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14749. this._pivotMatrix = matrix.clone();
  14750. this._cache.pivotMatrixUpdated = true;
  14751. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14752. if (this._postMultiplyPivotMatrix) {
  14753. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14754. }
  14755. return this;
  14756. };
  14757. /**
  14758. * Returns the mesh pivot matrix.
  14759. * Default : Identity.
  14760. * A Matrix is returned.
  14761. */
  14762. TransformNode.prototype.getPivotMatrix = function () {
  14763. return this._pivotMatrix;
  14764. };
  14765. /**
  14766. * Prevents the World matrix to be computed any longer.
  14767. * Returns the AbstractMesh.
  14768. */
  14769. TransformNode.prototype.freezeWorldMatrix = function () {
  14770. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14771. this.computeWorldMatrix(true);
  14772. this._isWorldMatrixFrozen = true;
  14773. return this;
  14774. };
  14775. /**
  14776. * Allows back the World matrix computation.
  14777. * Returns the AbstractMesh.
  14778. */
  14779. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14780. this._isWorldMatrixFrozen = false;
  14781. this.computeWorldMatrix(true);
  14782. return this;
  14783. };
  14784. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14785. /**
  14786. * True if the World matrix has been frozen.
  14787. * Returns a boolean.
  14788. */
  14789. get: function () {
  14790. return this._isWorldMatrixFrozen;
  14791. },
  14792. enumerable: true,
  14793. configurable: true
  14794. });
  14795. /**
  14796. * Retuns the mesh absolute position in the World.
  14797. * Returns a Vector3.
  14798. */
  14799. TransformNode.prototype.getAbsolutePosition = function () {
  14800. this.computeWorldMatrix();
  14801. return this._absolutePosition;
  14802. };
  14803. /**
  14804. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14805. * Returns the AbstractMesh.
  14806. */
  14807. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14808. if (!absolutePosition) {
  14809. return this;
  14810. }
  14811. var absolutePositionX;
  14812. var absolutePositionY;
  14813. var absolutePositionZ;
  14814. if (absolutePosition.x === undefined) {
  14815. if (arguments.length < 3) {
  14816. return this;
  14817. }
  14818. absolutePositionX = arguments[0];
  14819. absolutePositionY = arguments[1];
  14820. absolutePositionZ = arguments[2];
  14821. }
  14822. else {
  14823. absolutePositionX = absolutePosition.x;
  14824. absolutePositionY = absolutePosition.y;
  14825. absolutePositionZ = absolutePosition.z;
  14826. }
  14827. if (this.parent) {
  14828. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14829. invertParentWorldMatrix.invert();
  14830. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14831. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14832. }
  14833. else {
  14834. this.position.x = absolutePositionX;
  14835. this.position.y = absolutePositionY;
  14836. this.position.z = absolutePositionZ;
  14837. }
  14838. return this;
  14839. };
  14840. /**
  14841. * Sets the mesh position in its local space.
  14842. * Returns the AbstractMesh.
  14843. */
  14844. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14845. this.computeWorldMatrix();
  14846. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14847. return this;
  14848. };
  14849. /**
  14850. * Returns the mesh position in the local space from the current World matrix values.
  14851. * Returns a new Vector3.
  14852. */
  14853. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14854. this.computeWorldMatrix();
  14855. var invLocalWorldMatrix = this._localWorld.clone();
  14856. invLocalWorldMatrix.invert();
  14857. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14858. };
  14859. /**
  14860. * Translates the mesh along the passed Vector3 in its local space.
  14861. * Returns the AbstractMesh.
  14862. */
  14863. TransformNode.prototype.locallyTranslate = function (vector3) {
  14864. this.computeWorldMatrix(true);
  14865. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14866. return this;
  14867. };
  14868. /**
  14869. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14870. * @param targetPoint the position (must be in same space as current mesh) to look at
  14871. * @param yawCor optional yaw (y-axis) correction in radians
  14872. * @param pitchCor optional pitch (x-axis) correction in radians
  14873. * @param rollCor optional roll (z-axis) correction in radians
  14874. * @param space the choosen space of the target
  14875. * @returns the TransformNode.
  14876. */
  14877. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14878. if (yawCor === void 0) { yawCor = 0; }
  14879. if (pitchCor === void 0) { pitchCor = 0; }
  14880. if (rollCor === void 0) { rollCor = 0; }
  14881. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14882. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14883. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14884. targetPoint.subtractToRef(pos, dv);
  14885. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14886. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14887. var pitch = Math.atan2(dv.y, len);
  14888. if (this.rotationQuaternion) {
  14889. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14890. }
  14891. else {
  14892. this.rotation.x = pitch + pitchCor;
  14893. this.rotation.y = yaw + yawCor;
  14894. this.rotation.z = rollCor;
  14895. }
  14896. return this;
  14897. };
  14898. /**
  14899. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14900. * This Vector3 is expressed in the World space.
  14901. */
  14902. TransformNode.prototype.getDirection = function (localAxis) {
  14903. var result = BABYLON.Vector3.Zero();
  14904. this.getDirectionToRef(localAxis, result);
  14905. return result;
  14906. };
  14907. /**
  14908. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14909. * localAxis is expressed in the mesh local space.
  14910. * result is computed in the Wordl space from the mesh World matrix.
  14911. * Returns the AbstractMesh.
  14912. */
  14913. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14914. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14915. return this;
  14916. };
  14917. TransformNode.prototype.setPivotPoint = function (point, space) {
  14918. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14919. if (this.getScene().getRenderId() == 0) {
  14920. this.computeWorldMatrix(true);
  14921. }
  14922. var wm = this.getWorldMatrix();
  14923. if (space == BABYLON.Space.WORLD) {
  14924. var tmat = BABYLON.Tmp.Matrix[0];
  14925. wm.invertToRef(tmat);
  14926. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14927. }
  14928. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14929. this._pivotMatrix.m[12] = -point.x;
  14930. this._pivotMatrix.m[13] = -point.y;
  14931. this._pivotMatrix.m[14] = -point.z;
  14932. this._cache.pivotMatrixUpdated = true;
  14933. return this;
  14934. };
  14935. /**
  14936. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14937. */
  14938. TransformNode.prototype.getPivotPoint = function () {
  14939. var point = BABYLON.Vector3.Zero();
  14940. this.getPivotPointToRef(point);
  14941. return point;
  14942. };
  14943. /**
  14944. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14945. * Returns the AbstractMesh.
  14946. */
  14947. TransformNode.prototype.getPivotPointToRef = function (result) {
  14948. result.x = -this._pivotMatrix.m[12];
  14949. result.y = -this._pivotMatrix.m[13];
  14950. result.z = -this._pivotMatrix.m[14];
  14951. return this;
  14952. };
  14953. /**
  14954. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14955. */
  14956. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14957. var point = BABYLON.Vector3.Zero();
  14958. this.getAbsolutePivotPointToRef(point);
  14959. return point;
  14960. };
  14961. /**
  14962. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14963. * Returns the AbstractMesh.
  14964. */
  14965. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14966. result.x = this._pivotMatrix.m[12];
  14967. result.y = this._pivotMatrix.m[13];
  14968. result.z = this._pivotMatrix.m[14];
  14969. this.getPivotPointToRef(result);
  14970. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14971. return this;
  14972. };
  14973. /**
  14974. * Defines the passed node as the parent of the current node.
  14975. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14976. * Returns the TransformNode.
  14977. */
  14978. TransformNode.prototype.setParent = function (node) {
  14979. if (node === null) {
  14980. var rotation = BABYLON.Tmp.Quaternion[0];
  14981. var position = BABYLON.Tmp.Vector3[0];
  14982. var scale = BABYLON.Tmp.Vector3[1];
  14983. if (this.parent && this.parent.computeWorldMatrix) {
  14984. this.parent.computeWorldMatrix(true);
  14985. }
  14986. this.computeWorldMatrix(true);
  14987. this.getWorldMatrix().decompose(scale, rotation, position);
  14988. if (this.rotationQuaternion) {
  14989. this.rotationQuaternion.copyFrom(rotation);
  14990. }
  14991. else {
  14992. rotation.toEulerAnglesToRef(this.rotation);
  14993. }
  14994. this.scaling.x = scale.x;
  14995. this.scaling.y = scale.y;
  14996. this.scaling.z = scale.z;
  14997. this.position.x = position.x;
  14998. this.position.y = position.y;
  14999. this.position.z = position.z;
  15000. }
  15001. else {
  15002. var rotation = BABYLON.Tmp.Quaternion[0];
  15003. var position = BABYLON.Tmp.Vector3[0];
  15004. var scale = BABYLON.Tmp.Vector3[1];
  15005. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15006. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15007. this.computeWorldMatrix(true);
  15008. node.computeWorldMatrix(true);
  15009. node.getWorldMatrix().invertToRef(invParentMatrix);
  15010. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15011. diffMatrix.decompose(scale, rotation, position);
  15012. if (this.rotationQuaternion) {
  15013. this.rotationQuaternion.copyFrom(rotation);
  15014. }
  15015. else {
  15016. rotation.toEulerAnglesToRef(this.rotation);
  15017. }
  15018. this.position.x = position.x;
  15019. this.position.y = position.y;
  15020. this.position.z = position.z;
  15021. this.scaling.x = scale.x;
  15022. this.scaling.y = scale.y;
  15023. this.scaling.z = scale.z;
  15024. }
  15025. this.parent = node;
  15026. return this;
  15027. };
  15028. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15029. get: function () {
  15030. return this._nonUniformScaling;
  15031. },
  15032. enumerable: true,
  15033. configurable: true
  15034. });
  15035. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15036. if (this._nonUniformScaling === value) {
  15037. return false;
  15038. }
  15039. this._nonUniformScaling = true;
  15040. return true;
  15041. };
  15042. /**
  15043. * Attach the current TransformNode to another TransformNode associated with a bone
  15044. * @param bone Bone affecting the TransformNode
  15045. * @param affectedTransformNode TransformNode associated with the bone
  15046. */
  15047. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15048. this._transformToBoneReferal = affectedTransformNode;
  15049. this.parent = bone;
  15050. if (bone.getWorldMatrix().determinant() < 0) {
  15051. this.scalingDeterminant *= -1;
  15052. }
  15053. return this;
  15054. };
  15055. TransformNode.prototype.detachFromBone = function () {
  15056. if (!this.parent) {
  15057. return this;
  15058. }
  15059. if (this.parent.getWorldMatrix().determinant() < 0) {
  15060. this.scalingDeterminant *= -1;
  15061. }
  15062. this._transformToBoneReferal = null;
  15063. this.parent = null;
  15064. return this;
  15065. };
  15066. /**
  15067. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15068. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15069. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15070. * The passed axis is also normalized.
  15071. * Returns the AbstractMesh.
  15072. */
  15073. TransformNode.prototype.rotate = function (axis, amount, space) {
  15074. axis.normalize();
  15075. if (!this.rotationQuaternion) {
  15076. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15077. this.rotation = BABYLON.Vector3.Zero();
  15078. }
  15079. var rotationQuaternion;
  15080. if (!space || space === BABYLON.Space.LOCAL) {
  15081. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15082. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15083. }
  15084. else {
  15085. if (this.parent) {
  15086. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15087. invertParentWorldMatrix.invert();
  15088. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15089. }
  15090. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15091. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15092. }
  15093. return this;
  15094. };
  15095. /**
  15096. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15097. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15098. * The passed axis is also normalized.
  15099. * Returns the AbstractMesh.
  15100. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15101. */
  15102. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15103. axis.normalize();
  15104. if (!this.rotationQuaternion) {
  15105. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15106. this.rotation.copyFromFloats(0, 0, 0);
  15107. }
  15108. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15109. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15110. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15111. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15112. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15113. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15114. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15115. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15116. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15117. return this;
  15118. };
  15119. /**
  15120. * Translates the mesh along the axis vector for the passed distance in the given space.
  15121. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15122. * Returns the AbstractMesh.
  15123. */
  15124. TransformNode.prototype.translate = function (axis, distance, space) {
  15125. var displacementVector = axis.scale(distance);
  15126. if (!space || space === BABYLON.Space.LOCAL) {
  15127. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15128. this.setPositionWithLocalVector(tempV3);
  15129. }
  15130. else {
  15131. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15132. }
  15133. return this;
  15134. };
  15135. /**
  15136. * Adds a rotation step to the mesh current rotation.
  15137. * x, y, z are Euler angles expressed in radians.
  15138. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15139. * This means this rotation is made in the mesh local space only.
  15140. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15141. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15142. * ```javascript
  15143. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15144. * ```
  15145. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15146. * 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.
  15147. * Returns the AbstractMesh.
  15148. */
  15149. TransformNode.prototype.addRotation = function (x, y, z) {
  15150. var rotationQuaternion;
  15151. if (this.rotationQuaternion) {
  15152. rotationQuaternion = this.rotationQuaternion;
  15153. }
  15154. else {
  15155. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15156. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15157. }
  15158. var accumulation = BABYLON.Tmp.Quaternion[0];
  15159. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15160. rotationQuaternion.multiplyInPlace(accumulation);
  15161. if (!this.rotationQuaternion) {
  15162. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15163. }
  15164. return this;
  15165. };
  15166. /**
  15167. * Computes the mesh World matrix and returns it.
  15168. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15169. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15170. * If the parameter `force`is set to `true`, the actual computation is done.
  15171. * Returns the mesh World Matrix.
  15172. */
  15173. TransformNode.prototype.computeWorldMatrix = function (force) {
  15174. if (this._isWorldMatrixFrozen) {
  15175. return this._worldMatrix;
  15176. }
  15177. if (!force && this.isSynchronized(true)) {
  15178. return this._worldMatrix;
  15179. }
  15180. this._cache.position.copyFrom(this.position);
  15181. this._cache.scaling.copyFrom(this.scaling);
  15182. this._cache.pivotMatrixUpdated = false;
  15183. this._cache.billboardMode = this.billboardMode;
  15184. this._currentRenderId = this.getScene().getRenderId();
  15185. this._isDirty = false;
  15186. // Scaling
  15187. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15188. // Rotation
  15189. //rotate, if quaternion is set and rotation was used
  15190. if (this.rotationQuaternion) {
  15191. var len = this.rotation.length();
  15192. if (len) {
  15193. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15194. this.rotation.copyFromFloats(0, 0, 0);
  15195. }
  15196. }
  15197. if (this.rotationQuaternion) {
  15198. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15199. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15200. }
  15201. else {
  15202. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15203. this._cache.rotation.copyFrom(this.rotation);
  15204. }
  15205. // Translation
  15206. var camera = this.getScene().activeCamera;
  15207. if (this.infiniteDistance && !this.parent && camera) {
  15208. var cameraWorldMatrix = camera.getWorldMatrix();
  15209. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15210. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15211. }
  15212. else {
  15213. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15214. }
  15215. // Composing transformations
  15216. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15217. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15218. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15219. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15220. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15221. // Need to decompose each rotation here
  15222. var currentPosition = BABYLON.Tmp.Vector3[3];
  15223. if (this.parent && this.parent.getWorldMatrix) {
  15224. if (this._transformToBoneReferal) {
  15225. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15226. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15227. }
  15228. else {
  15229. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15230. }
  15231. }
  15232. else {
  15233. currentPosition.copyFrom(this.position);
  15234. }
  15235. currentPosition.subtractInPlace(camera.globalPosition);
  15236. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15237. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15238. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15239. }
  15240. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15241. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15242. }
  15243. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15244. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15245. }
  15246. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15247. }
  15248. else {
  15249. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15250. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15251. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15252. }
  15253. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15254. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15255. }
  15256. // Local world
  15257. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15258. // Parent
  15259. if (this.parent && this.parent.getWorldMatrix) {
  15260. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15261. if (this._transformToBoneReferal) {
  15262. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15263. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15264. }
  15265. else {
  15266. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15267. }
  15268. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15269. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15270. this._worldMatrix.copyFrom(this._localWorld);
  15271. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15272. }
  15273. else {
  15274. if (this._transformToBoneReferal) {
  15275. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15276. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15277. }
  15278. else {
  15279. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15280. }
  15281. }
  15282. this._markSyncedWithParent();
  15283. }
  15284. else {
  15285. this._worldMatrix.copyFrom(this._localWorld);
  15286. }
  15287. // Post multiply inverse of pivotMatrix
  15288. if (this._postMultiplyPivotMatrix) {
  15289. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15290. }
  15291. // Normal matrix
  15292. if (this.scaling.isNonUniform) {
  15293. this._updateNonUniformScalingState(true);
  15294. }
  15295. else if (this.parent && this.parent._nonUniformScaling) {
  15296. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15297. }
  15298. else {
  15299. this._updateNonUniformScalingState(false);
  15300. }
  15301. this._afterComputeWorldMatrix();
  15302. // Absolute position
  15303. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15304. // Callbacks
  15305. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15306. if (!this._poseMatrix) {
  15307. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15308. }
  15309. // Cache the determinant
  15310. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15311. return this._worldMatrix;
  15312. };
  15313. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15314. };
  15315. /**
  15316. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15317. * @param func: callback function to add
  15318. *
  15319. * Returns the TransformNode.
  15320. */
  15321. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15322. this.onAfterWorldMatrixUpdateObservable.add(func);
  15323. return this;
  15324. };
  15325. /**
  15326. * Removes a registered callback function.
  15327. * Returns the TransformNode.
  15328. */
  15329. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15330. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15331. return this;
  15332. };
  15333. /**
  15334. * Clone the current transform node
  15335. * Returns the new transform node
  15336. * @param name Name of the new clone
  15337. * @param newParent New parent for the clone
  15338. * @param doNotCloneChildren Do not clone children hierarchy
  15339. */
  15340. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15341. var _this = this;
  15342. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15343. result.name = name;
  15344. result.id = name;
  15345. if (newParent) {
  15346. result.parent = newParent;
  15347. }
  15348. if (!doNotCloneChildren) {
  15349. // Children
  15350. var directDescendants = this.getDescendants(true);
  15351. for (var index = 0; index < directDescendants.length; index++) {
  15352. var child = directDescendants[index];
  15353. if (child.clone) {
  15354. child.clone(name + "." + child.name, result);
  15355. }
  15356. }
  15357. }
  15358. return result;
  15359. };
  15360. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15361. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15362. serializationObject.type = this.getClassName();
  15363. // Parent
  15364. if (this.parent) {
  15365. serializationObject.parentId = this.parent.id;
  15366. }
  15367. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15368. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15369. }
  15370. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15371. serializationObject.isEnabled = this.isEnabled();
  15372. // Parent
  15373. if (this.parent) {
  15374. serializationObject.parentId = this.parent.id;
  15375. }
  15376. return serializationObject;
  15377. };
  15378. // Statics
  15379. /**
  15380. * Returns a new TransformNode object parsed from the source provided.
  15381. * The parameter `parsedMesh` is the source.
  15382. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15383. */
  15384. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15385. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15386. if (BABYLON.Tags) {
  15387. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15388. }
  15389. if (parsedTransformNode.localMatrix) {
  15390. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15391. }
  15392. else if (parsedTransformNode.pivotMatrix) {
  15393. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15394. }
  15395. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15396. // Parent
  15397. if (parsedTransformNode.parentId) {
  15398. transformNode._waitingParentId = parsedTransformNode.parentId;
  15399. }
  15400. return transformNode;
  15401. };
  15402. /**
  15403. * Disposes the TransformNode.
  15404. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15405. * Returns nothing.
  15406. */
  15407. TransformNode.prototype.dispose = function (doNotRecurse) {
  15408. // Animations
  15409. this.getScene().stopAnimation(this);
  15410. // Remove from scene
  15411. this.getScene().removeTransformNode(this);
  15412. if (!doNotRecurse) {
  15413. // Children
  15414. var objects = this.getDescendants(true);
  15415. for (var index = 0; index < objects.length; index++) {
  15416. objects[index].dispose();
  15417. }
  15418. }
  15419. else {
  15420. var childMeshes = this.getChildMeshes(true);
  15421. for (index = 0; index < childMeshes.length; index++) {
  15422. var child = childMeshes[index];
  15423. child.parent = null;
  15424. child.computeWorldMatrix(true);
  15425. }
  15426. }
  15427. this.onAfterWorldMatrixUpdateObservable.clear();
  15428. _super.prototype.dispose.call(this);
  15429. };
  15430. // Statics
  15431. TransformNode.BILLBOARDMODE_NONE = 0;
  15432. TransformNode.BILLBOARDMODE_X = 1;
  15433. TransformNode.BILLBOARDMODE_Y = 2;
  15434. TransformNode.BILLBOARDMODE_Z = 4;
  15435. TransformNode.BILLBOARDMODE_ALL = 7;
  15436. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15437. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15438. __decorate([
  15439. BABYLON.serializeAsVector3()
  15440. ], TransformNode.prototype, "_rotation", void 0);
  15441. __decorate([
  15442. BABYLON.serializeAsQuaternion()
  15443. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15444. __decorate([
  15445. BABYLON.serializeAsVector3()
  15446. ], TransformNode.prototype, "_scaling", void 0);
  15447. __decorate([
  15448. BABYLON.serialize()
  15449. ], TransformNode.prototype, "billboardMode", void 0);
  15450. __decorate([
  15451. BABYLON.serialize()
  15452. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15453. __decorate([
  15454. BABYLON.serialize()
  15455. ], TransformNode.prototype, "infiniteDistance", void 0);
  15456. __decorate([
  15457. BABYLON.serializeAsVector3()
  15458. ], TransformNode.prototype, "position", void 0);
  15459. return TransformNode;
  15460. }(BABYLON.Node));
  15461. BABYLON.TransformNode = TransformNode;
  15462. })(BABYLON || (BABYLON = {}));
  15463. //# sourceMappingURL=babylon.transformNode.js.map
  15464. var BABYLON;
  15465. (function (BABYLON) {
  15466. var AbstractMesh = /** @class */ (function (_super) {
  15467. __extends(AbstractMesh, _super);
  15468. // Constructor
  15469. function AbstractMesh(name, scene) {
  15470. if (scene === void 0) { scene = null; }
  15471. var _this = _super.call(this, name, scene, false) || this;
  15472. _this._facetNb = 0; // facet number
  15473. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15474. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15475. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15476. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15477. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15478. _this._subDiv = {
  15479. max: 1,
  15480. X: 1,
  15481. Y: 1,
  15482. Z: 1
  15483. };
  15484. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15485. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15486. // Events
  15487. /**
  15488. * An event triggered when this mesh collides with another one
  15489. * @type {BABYLON.Observable}
  15490. */
  15491. _this.onCollideObservable = new BABYLON.Observable();
  15492. /**
  15493. * An event triggered when the collision's position changes
  15494. * @type {BABYLON.Observable}
  15495. */
  15496. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15497. /**
  15498. * An event triggered when material is changed
  15499. * @type {BABYLON.Observable}
  15500. */
  15501. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15502. // Properties
  15503. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15504. /**
  15505. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15506. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15507. * or
  15508. * 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.
  15509. * for more info check WebGl documentations
  15510. */
  15511. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15512. /**
  15513. * 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:
  15514. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15515. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15516. * 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.
  15517. */
  15518. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15519. /**
  15520. * 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.
  15521. * The default value is -1 which means don't break the query and wait till the result.
  15522. */
  15523. _this.occlusionRetryCount = -1;
  15524. _this._occlusionInternalRetryCounter = 0;
  15525. _this._isOccluded = false;
  15526. _this._isOcclusionQueryInProgress = false;
  15527. _this.visibility = 1.0;
  15528. _this.alphaIndex = Number.MAX_VALUE;
  15529. _this.isVisible = true;
  15530. _this.isPickable = true;
  15531. _this.showBoundingBox = false;
  15532. _this.showSubMeshesBoundingBox = false;
  15533. _this.isBlocker = false;
  15534. _this.enablePointerMoveEvents = false;
  15535. _this.renderingGroupId = 0;
  15536. _this._receiveShadows = false;
  15537. _this.renderOutline = false;
  15538. _this.outlineColor = BABYLON.Color3.Red();
  15539. _this.outlineWidth = 0.02;
  15540. _this.renderOverlay = false;
  15541. _this.overlayColor = BABYLON.Color3.Red();
  15542. _this.overlayAlpha = 0.5;
  15543. _this._hasVertexAlpha = false;
  15544. _this._useVertexColors = true;
  15545. _this._computeBonesUsingShaders = true;
  15546. _this._numBoneInfluencers = 4;
  15547. _this._applyFog = true;
  15548. _this.useOctreeForRenderingSelection = true;
  15549. _this.useOctreeForPicking = true;
  15550. _this.useOctreeForCollisions = true;
  15551. _this._layerMask = 0x0FFFFFFF;
  15552. /**
  15553. * True if the mesh must be rendered in any case.
  15554. */
  15555. _this.alwaysSelectAsActiveMesh = false;
  15556. /**
  15557. * This scene's action manager
  15558. * @type {BABYLON.ActionManager}
  15559. */
  15560. _this.actionManager = null;
  15561. // Physics
  15562. _this.physicsImpostor = null;
  15563. // Collisions
  15564. _this._checkCollisions = false;
  15565. _this._collisionMask = -1;
  15566. _this._collisionGroup = -1;
  15567. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15568. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15569. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15570. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15571. // Edges
  15572. _this.edgesWidth = 1;
  15573. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15574. // Cache
  15575. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15576. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15577. _this._isDisposed = false;
  15578. _this._renderId = 0;
  15579. _this._intersectionsInProgress = new Array();
  15580. _this._unIndexed = false;
  15581. _this._lightSources = new Array();
  15582. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15583. if (collidedMesh === void 0) { collidedMesh = null; }
  15584. //TODO move this to the collision coordinator!
  15585. if (_this.getScene().workerCollisions)
  15586. newPosition.multiplyInPlace(_this._collider._radius);
  15587. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15588. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15589. _this.position.addInPlace(_this._diffPositionForCollisions);
  15590. }
  15591. if (collidedMesh) {
  15592. _this.onCollideObservable.notifyObservers(collidedMesh);
  15593. }
  15594. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15595. };
  15596. _this.getScene().addMesh(_this);
  15597. _this._resyncLightSources();
  15598. return _this;
  15599. }
  15600. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15601. get: function () {
  15602. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15603. },
  15604. enumerable: true,
  15605. configurable: true
  15606. });
  15607. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15608. get: function () {
  15609. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15610. },
  15611. enumerable: true,
  15612. configurable: true
  15613. });
  15614. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15615. get: function () {
  15616. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15617. },
  15618. enumerable: true,
  15619. configurable: true
  15620. });
  15621. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15622. get: function () {
  15623. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15624. },
  15625. enumerable: true,
  15626. configurable: true
  15627. });
  15628. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15629. get: function () {
  15630. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15631. },
  15632. enumerable: true,
  15633. configurable: true
  15634. });
  15635. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15636. /**
  15637. * Read-only : the number of facets in the mesh
  15638. */
  15639. get: function () {
  15640. return this._facetNb;
  15641. },
  15642. enumerable: true,
  15643. configurable: true
  15644. });
  15645. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15646. /**
  15647. * The number (integer) of subdivisions per axis in the partioning space
  15648. */
  15649. get: function () {
  15650. return this._partitioningSubdivisions;
  15651. },
  15652. set: function (nb) {
  15653. this._partitioningSubdivisions = nb;
  15654. },
  15655. enumerable: true,
  15656. configurable: true
  15657. });
  15658. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15659. /**
  15660. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15661. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15662. */
  15663. get: function () {
  15664. return this._partitioningBBoxRatio;
  15665. },
  15666. set: function (ratio) {
  15667. this._partitioningBBoxRatio = ratio;
  15668. },
  15669. enumerable: true,
  15670. configurable: true
  15671. });
  15672. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15673. /**
  15674. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15675. * Works only for updatable meshes.
  15676. * Doesn't work with multi-materials.
  15677. */
  15678. get: function () {
  15679. return this._facetDepthSort;
  15680. },
  15681. set: function (sort) {
  15682. this._facetDepthSort = sort;
  15683. },
  15684. enumerable: true,
  15685. configurable: true
  15686. });
  15687. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15688. /**
  15689. * The location (Vector3) where the facet depth sort must be computed from.
  15690. * By default, the active camera position.
  15691. * Used only when facet depth sort is enabled.
  15692. */
  15693. get: function () {
  15694. return this._facetDepthSortFrom;
  15695. },
  15696. set: function (location) {
  15697. this._facetDepthSortFrom = location;
  15698. },
  15699. enumerable: true,
  15700. configurable: true
  15701. });
  15702. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15703. /**
  15704. * Read-only boolean : is the feature facetData enabled ?
  15705. */
  15706. get: function () {
  15707. return this._facetDataEnabled;
  15708. },
  15709. enumerable: true,
  15710. configurable: true
  15711. });
  15712. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15713. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15714. return false;
  15715. }
  15716. this._markSubMeshesAsMiscDirty();
  15717. return true;
  15718. };
  15719. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15720. set: function (callback) {
  15721. if (this._onCollideObserver) {
  15722. this.onCollideObservable.remove(this._onCollideObserver);
  15723. }
  15724. this._onCollideObserver = this.onCollideObservable.add(callback);
  15725. },
  15726. enumerable: true,
  15727. configurable: true
  15728. });
  15729. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15730. set: function (callback) {
  15731. if (this._onCollisionPositionChangeObserver) {
  15732. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15733. }
  15734. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15735. },
  15736. enumerable: true,
  15737. configurable: true
  15738. });
  15739. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15740. /**
  15741. * 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.
  15742. */
  15743. get: function () {
  15744. return this._isOccluded;
  15745. },
  15746. set: function (value) {
  15747. this._isOccluded = value;
  15748. },
  15749. enumerable: true,
  15750. configurable: true
  15751. });
  15752. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15753. /**
  15754. * Flag to check the progress status of the query
  15755. */
  15756. get: function () {
  15757. return this._isOcclusionQueryInProgress;
  15758. },
  15759. enumerable: true,
  15760. configurable: true
  15761. });
  15762. Object.defineProperty(AbstractMesh.prototype, "material", {
  15763. get: function () {
  15764. return this._material;
  15765. },
  15766. set: function (value) {
  15767. if (this._material === value) {
  15768. return;
  15769. }
  15770. this._material = value;
  15771. if (this.onMaterialChangedObservable.hasObservers) {
  15772. this.onMaterialChangedObservable.notifyObservers(this);
  15773. }
  15774. if (!this.subMeshes) {
  15775. return;
  15776. }
  15777. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15778. var subMesh = _a[_i];
  15779. subMesh.setEffect(null);
  15780. }
  15781. },
  15782. enumerable: true,
  15783. configurable: true
  15784. });
  15785. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15786. get: function () {
  15787. return this._receiveShadows;
  15788. },
  15789. set: function (value) {
  15790. if (this._receiveShadows === value) {
  15791. return;
  15792. }
  15793. this._receiveShadows = value;
  15794. this._markSubMeshesAsLightDirty();
  15795. },
  15796. enumerable: true,
  15797. configurable: true
  15798. });
  15799. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15800. get: function () {
  15801. return this._hasVertexAlpha;
  15802. },
  15803. set: function (value) {
  15804. if (this._hasVertexAlpha === value) {
  15805. return;
  15806. }
  15807. this._hasVertexAlpha = value;
  15808. this._markSubMeshesAsAttributesDirty();
  15809. },
  15810. enumerable: true,
  15811. configurable: true
  15812. });
  15813. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15814. get: function () {
  15815. return this._useVertexColors;
  15816. },
  15817. set: function (value) {
  15818. if (this._useVertexColors === value) {
  15819. return;
  15820. }
  15821. this._useVertexColors = value;
  15822. this._markSubMeshesAsAttributesDirty();
  15823. },
  15824. enumerable: true,
  15825. configurable: true
  15826. });
  15827. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15828. get: function () {
  15829. return this._computeBonesUsingShaders;
  15830. },
  15831. set: function (value) {
  15832. if (this._computeBonesUsingShaders === value) {
  15833. return;
  15834. }
  15835. this._computeBonesUsingShaders = value;
  15836. this._markSubMeshesAsAttributesDirty();
  15837. },
  15838. enumerable: true,
  15839. configurable: true
  15840. });
  15841. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15842. get: function () {
  15843. return this._numBoneInfluencers;
  15844. },
  15845. set: function (value) {
  15846. if (this._numBoneInfluencers === value) {
  15847. return;
  15848. }
  15849. this._numBoneInfluencers = value;
  15850. this._markSubMeshesAsAttributesDirty();
  15851. },
  15852. enumerable: true,
  15853. configurable: true
  15854. });
  15855. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15856. get: function () {
  15857. return this._applyFog;
  15858. },
  15859. set: function (value) {
  15860. if (this._applyFog === value) {
  15861. return;
  15862. }
  15863. this._applyFog = value;
  15864. this._markSubMeshesAsMiscDirty();
  15865. },
  15866. enumerable: true,
  15867. configurable: true
  15868. });
  15869. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15870. get: function () {
  15871. return this._layerMask;
  15872. },
  15873. set: function (value) {
  15874. if (value === this._layerMask) {
  15875. return;
  15876. }
  15877. this._layerMask = value;
  15878. this._resyncLightSources();
  15879. },
  15880. enumerable: true,
  15881. configurable: true
  15882. });
  15883. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15884. get: function () {
  15885. return this._collisionMask;
  15886. },
  15887. set: function (mask) {
  15888. this._collisionMask = !isNaN(mask) ? mask : -1;
  15889. },
  15890. enumerable: true,
  15891. configurable: true
  15892. });
  15893. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15894. get: function () {
  15895. return this._collisionGroup;
  15896. },
  15897. set: function (mask) {
  15898. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15899. },
  15900. enumerable: true,
  15901. configurable: true
  15902. });
  15903. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15904. get: function () {
  15905. return null;
  15906. },
  15907. enumerable: true,
  15908. configurable: true
  15909. });
  15910. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15911. get: function () {
  15912. return this._skeleton;
  15913. },
  15914. set: function (value) {
  15915. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15916. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15917. }
  15918. if (value && value.needInitialSkinMatrix) {
  15919. value._registerMeshWithPoseMatrix(this);
  15920. }
  15921. this._skeleton = value;
  15922. if (!this._skeleton) {
  15923. this._bonesTransformMatrices = null;
  15924. }
  15925. this._markSubMeshesAsAttributesDirty();
  15926. },
  15927. enumerable: true,
  15928. configurable: true
  15929. });
  15930. /**
  15931. * Boolean : true if the mesh has been disposed.
  15932. */
  15933. AbstractMesh.prototype.isDisposed = function () {
  15934. return this._isDisposed;
  15935. };
  15936. /**
  15937. * Returns the string "AbstractMesh"
  15938. */
  15939. AbstractMesh.prototype.getClassName = function () {
  15940. return "AbstractMesh";
  15941. };
  15942. /**
  15943. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15944. */
  15945. AbstractMesh.prototype.toString = function (fullDetails) {
  15946. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15947. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15948. if (this._skeleton) {
  15949. ret += ", skeleton: " + this._skeleton.name;
  15950. }
  15951. if (fullDetails) {
  15952. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15953. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15954. }
  15955. return ret;
  15956. };
  15957. AbstractMesh.prototype._rebuild = function () {
  15958. if (this._occlusionQuery) {
  15959. this._occlusionQuery = null;
  15960. }
  15961. if (this._edgesRenderer) {
  15962. this._edgesRenderer._rebuild();
  15963. }
  15964. if (!this.subMeshes) {
  15965. return;
  15966. }
  15967. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15968. var subMesh = _a[_i];
  15969. subMesh._rebuild();
  15970. }
  15971. };
  15972. AbstractMesh.prototype._resyncLightSources = function () {
  15973. this._lightSources.length = 0;
  15974. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15975. var light = _a[_i];
  15976. if (!light.isEnabled()) {
  15977. continue;
  15978. }
  15979. if (light.canAffectMesh(this)) {
  15980. this._lightSources.push(light);
  15981. }
  15982. }
  15983. this._markSubMeshesAsLightDirty();
  15984. };
  15985. AbstractMesh.prototype._resyncLighSource = function (light) {
  15986. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15987. var index = this._lightSources.indexOf(light);
  15988. if (index === -1) {
  15989. if (!isIn) {
  15990. return;
  15991. }
  15992. this._lightSources.push(light);
  15993. }
  15994. else {
  15995. if (isIn) {
  15996. return;
  15997. }
  15998. this._lightSources.splice(index, 1);
  15999. }
  16000. this._markSubMeshesAsLightDirty();
  16001. };
  16002. AbstractMesh.prototype._removeLightSource = function (light) {
  16003. var index = this._lightSources.indexOf(light);
  16004. if (index === -1) {
  16005. return;
  16006. }
  16007. this._lightSources.splice(index, 1);
  16008. this._markSubMeshesAsLightDirty();
  16009. };
  16010. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16011. if (!this.subMeshes) {
  16012. return;
  16013. }
  16014. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16015. var subMesh = _a[_i];
  16016. if (subMesh._materialDefines) {
  16017. func(subMesh._materialDefines);
  16018. }
  16019. }
  16020. };
  16021. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16022. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16023. };
  16024. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16025. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16026. };
  16027. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16028. if (!this.subMeshes) {
  16029. return;
  16030. }
  16031. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16032. var subMesh = _a[_i];
  16033. var material = subMesh.getMaterial();
  16034. if (material) {
  16035. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16036. }
  16037. }
  16038. };
  16039. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16040. /**
  16041. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16042. * Default : (1.0, 1.0, 1.0)
  16043. */
  16044. get: function () {
  16045. return this._scaling;
  16046. },
  16047. /**
  16048. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16049. * Default : (1.0, 1.0, 1.0)
  16050. */
  16051. set: function (newScaling) {
  16052. this._scaling = newScaling;
  16053. if (this.physicsImpostor) {
  16054. this.physicsImpostor.forceUpdate();
  16055. }
  16056. },
  16057. enumerable: true,
  16058. configurable: true
  16059. });
  16060. // Methods
  16061. /**
  16062. * Disables the mesh edger rendering mode.
  16063. * Returns the AbstractMesh.
  16064. */
  16065. AbstractMesh.prototype.disableEdgesRendering = function () {
  16066. if (this._edgesRenderer) {
  16067. this._edgesRenderer.dispose();
  16068. this._edgesRenderer = null;
  16069. }
  16070. return this;
  16071. };
  16072. /**
  16073. * Enables the edge rendering mode on the mesh.
  16074. * This mode makes the mesh edges visible.
  16075. * Returns the AbstractMesh.
  16076. */
  16077. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16078. if (epsilon === void 0) { epsilon = 0.95; }
  16079. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16080. this.disableEdgesRendering();
  16081. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16082. return this;
  16083. };
  16084. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16085. /**
  16086. * Returns true if the mesh is blocked. Used by the class Mesh.
  16087. * Returns the boolean `false` by default.
  16088. */
  16089. get: function () {
  16090. return false;
  16091. },
  16092. enumerable: true,
  16093. configurable: true
  16094. });
  16095. /**
  16096. * Returns the mesh itself by default, used by the class Mesh.
  16097. * Returned type : AbstractMesh
  16098. */
  16099. AbstractMesh.prototype.getLOD = function (camera) {
  16100. return this;
  16101. };
  16102. /**
  16103. * Returns 0 by default, used by the class Mesh.
  16104. * Returns an integer.
  16105. */
  16106. AbstractMesh.prototype.getTotalVertices = function () {
  16107. return 0;
  16108. };
  16109. /**
  16110. * Returns null by default, used by the class Mesh.
  16111. * Returned type : integer array
  16112. */
  16113. AbstractMesh.prototype.getIndices = function () {
  16114. return null;
  16115. };
  16116. /**
  16117. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16118. * Returned type : float array or Float32Array
  16119. */
  16120. AbstractMesh.prototype.getVerticesData = function (kind) {
  16121. return null;
  16122. };
  16123. /**
  16124. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16125. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16126. * The `data` are either a numeric array either a Float32Array.
  16127. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16128. * 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).
  16129. * Note that a new underlying VertexBuffer object is created each call.
  16130. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16131. *
  16132. * Possible `kind` values :
  16133. * - BABYLON.VertexBuffer.PositionKind
  16134. * - BABYLON.VertexBuffer.UVKind
  16135. * - BABYLON.VertexBuffer.UV2Kind
  16136. * - BABYLON.VertexBuffer.UV3Kind
  16137. * - BABYLON.VertexBuffer.UV4Kind
  16138. * - BABYLON.VertexBuffer.UV5Kind
  16139. * - BABYLON.VertexBuffer.UV6Kind
  16140. * - BABYLON.VertexBuffer.ColorKind
  16141. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16142. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16143. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16144. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16145. *
  16146. * Returns the Mesh.
  16147. */
  16148. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16149. return this;
  16150. };
  16151. /**
  16152. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16153. * If the mesh has no geometry, it is simply returned as it is.
  16154. * The `data` are either a numeric array either a Float32Array.
  16155. * No new underlying VertexBuffer object is created.
  16156. * 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.
  16157. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16158. *
  16159. * Possible `kind` values :
  16160. * - BABYLON.VertexBuffer.PositionKind
  16161. * - BABYLON.VertexBuffer.UVKind
  16162. * - BABYLON.VertexBuffer.UV2Kind
  16163. * - BABYLON.VertexBuffer.UV3Kind
  16164. * - BABYLON.VertexBuffer.UV4Kind
  16165. * - BABYLON.VertexBuffer.UV5Kind
  16166. * - BABYLON.VertexBuffer.UV6Kind
  16167. * - BABYLON.VertexBuffer.ColorKind
  16168. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16169. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16170. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16171. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16172. *
  16173. * Returns the Mesh.
  16174. */
  16175. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16176. return this;
  16177. };
  16178. /**
  16179. * Sets the mesh indices.
  16180. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16181. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16182. * This method creates a new index buffer each call.
  16183. * Returns the Mesh.
  16184. */
  16185. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16186. return this;
  16187. };
  16188. /** Returns false by default, used by the class Mesh.
  16189. * Returns a boolean
  16190. */
  16191. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16192. return false;
  16193. };
  16194. /**
  16195. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16196. * Returns a BoundingInfo
  16197. */
  16198. AbstractMesh.prototype.getBoundingInfo = function () {
  16199. if (this._masterMesh) {
  16200. return this._masterMesh.getBoundingInfo();
  16201. }
  16202. if (!this._boundingInfo) {
  16203. // this._boundingInfo is being created here
  16204. this._updateBoundingInfo();
  16205. }
  16206. // cannot be null.
  16207. return this._boundingInfo;
  16208. };
  16209. /**
  16210. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16211. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16212. */
  16213. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16214. if (includeDescendants === void 0) { includeDescendants = true; }
  16215. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16216. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16217. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16218. if (maxDimension === 0) {
  16219. return this;
  16220. }
  16221. var scale = 1 / maxDimension;
  16222. this.scaling.scaleInPlace(scale);
  16223. return this;
  16224. };
  16225. /**
  16226. * Sets a mesh new object BoundingInfo.
  16227. * Returns the AbstractMesh.
  16228. */
  16229. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16230. this._boundingInfo = boundingInfo;
  16231. return this;
  16232. };
  16233. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16234. get: function () {
  16235. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16236. },
  16237. enumerable: true,
  16238. configurable: true
  16239. });
  16240. AbstractMesh.prototype._preActivate = function () {
  16241. };
  16242. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16243. };
  16244. AbstractMesh.prototype._activate = function (renderId) {
  16245. this._renderId = renderId;
  16246. };
  16247. /**
  16248. * Returns the latest update of the World matrix
  16249. * Returns a Matrix.
  16250. */
  16251. AbstractMesh.prototype.getWorldMatrix = function () {
  16252. if (this._masterMesh) {
  16253. return this._masterMesh.getWorldMatrix();
  16254. }
  16255. return _super.prototype.getWorldMatrix.call(this);
  16256. };
  16257. /**
  16258. * Returns the latest update of the World matrix determinant.
  16259. */
  16260. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16261. if (this._masterMesh) {
  16262. return this._masterMesh._getWorldMatrixDeterminant();
  16263. }
  16264. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16265. };
  16266. // ================================== Point of View Movement =================================
  16267. /**
  16268. * Perform relative position change from the point of view of behind the front of the mesh.
  16269. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16270. * Supports definition of mesh facing forward or backward.
  16271. * @param {number} amountRight
  16272. * @param {number} amountUp
  16273. * @param {number} amountForward
  16274. *
  16275. * Returns the AbstractMesh.
  16276. */
  16277. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16278. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16279. return this;
  16280. };
  16281. /**
  16282. * Calculate relative position change from the point of view of behind the front of the mesh.
  16283. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16284. * Supports definition of mesh facing forward or backward.
  16285. * @param {number} amountRight
  16286. * @param {number} amountUp
  16287. * @param {number} amountForward
  16288. *
  16289. * Returns a new Vector3.
  16290. */
  16291. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16292. var rotMatrix = new BABYLON.Matrix();
  16293. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16294. rotQuaternion.toRotationMatrix(rotMatrix);
  16295. var translationDelta = BABYLON.Vector3.Zero();
  16296. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16297. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16298. return translationDelta;
  16299. };
  16300. // ================================== Point of View Rotation =================================
  16301. /**
  16302. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16303. * Supports definition of mesh facing forward or backward.
  16304. * @param {number} flipBack
  16305. * @param {number} twirlClockwise
  16306. * @param {number} tiltRight
  16307. *
  16308. * Returns the AbstractMesh.
  16309. */
  16310. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16311. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16312. return this;
  16313. };
  16314. /**
  16315. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16316. * Supports definition of mesh facing forward or backward.
  16317. * @param {number} flipBack
  16318. * @param {number} twirlClockwise
  16319. * @param {number} tiltRight
  16320. *
  16321. * Returns a new Vector3.
  16322. */
  16323. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16324. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16325. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16326. };
  16327. /**
  16328. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16329. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16330. */
  16331. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16332. if (includeDescendants === void 0) { includeDescendants = true; }
  16333. this.computeWorldMatrix(true);
  16334. var min;
  16335. var max;
  16336. var boundingInfo = this.getBoundingInfo();
  16337. if (!this.subMeshes) {
  16338. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16339. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16340. }
  16341. else {
  16342. min = boundingInfo.boundingBox.minimumWorld;
  16343. max = boundingInfo.boundingBox.maximumWorld;
  16344. }
  16345. if (includeDescendants) {
  16346. var descendants = this.getDescendants(false);
  16347. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16348. var descendant = descendants_1[_i];
  16349. var childMesh = descendant;
  16350. childMesh.computeWorldMatrix(true);
  16351. //make sure we have the needed params to get mix and max
  16352. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16353. continue;
  16354. }
  16355. var childBoundingInfo = childMesh.getBoundingInfo();
  16356. var boundingBox = childBoundingInfo.boundingBox;
  16357. var minBox = boundingBox.minimumWorld;
  16358. var maxBox = boundingBox.maximumWorld;
  16359. BABYLON.Tools.CheckExtends(minBox, min, max);
  16360. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16361. }
  16362. }
  16363. return {
  16364. min: min,
  16365. max: max
  16366. };
  16367. };
  16368. /**
  16369. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16370. * Returns the AbstractMesh.
  16371. */
  16372. AbstractMesh.prototype._updateBoundingInfo = function () {
  16373. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16374. this._boundingInfo.update(this.worldMatrixFromCache);
  16375. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16376. return this;
  16377. };
  16378. /**
  16379. * Update a mesh's children BoundingInfo objects only.
  16380. * Returns the AbstractMesh.
  16381. */
  16382. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16383. if (!this.subMeshes) {
  16384. return this;
  16385. }
  16386. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16387. var subMesh = this.subMeshes[subIndex];
  16388. if (!subMesh.IsGlobal) {
  16389. subMesh.updateBoundingInfo(matrix);
  16390. }
  16391. }
  16392. return this;
  16393. };
  16394. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16395. // Bounding info
  16396. this._updateBoundingInfo();
  16397. };
  16398. /**
  16399. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16400. * A mesh is in the frustum if its bounding box intersects the frustum.
  16401. * Boolean returned.
  16402. */
  16403. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16404. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16405. };
  16406. /**
  16407. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16408. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16409. * Boolean returned.
  16410. */
  16411. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16412. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16413. ;
  16414. };
  16415. /**
  16416. * True if the mesh intersects another mesh or a SolidParticle object.
  16417. * 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)
  16418. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16419. * Returns a boolean.
  16420. */
  16421. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16422. if (precise === void 0) { precise = false; }
  16423. if (!this._boundingInfo || !mesh._boundingInfo) {
  16424. return false;
  16425. }
  16426. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16427. return true;
  16428. }
  16429. if (includeDescendants) {
  16430. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16431. var child = _a[_i];
  16432. if (child.intersectsMesh(mesh, precise, true)) {
  16433. return true;
  16434. }
  16435. }
  16436. }
  16437. return false;
  16438. };
  16439. /**
  16440. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16441. * Returns a boolean.
  16442. */
  16443. AbstractMesh.prototype.intersectsPoint = function (point) {
  16444. if (!this._boundingInfo) {
  16445. return false;
  16446. }
  16447. return this._boundingInfo.intersectsPoint(point);
  16448. };
  16449. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16450. return this.physicsImpostor;
  16451. };
  16452. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16453. if (camera === void 0) { camera = null; }
  16454. if (!camera) {
  16455. camera = this.getScene().activeCamera;
  16456. }
  16457. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16458. };
  16459. /**
  16460. * Returns the distance from the mesh to the active camera.
  16461. * Returns a float.
  16462. */
  16463. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16464. if (camera === void 0) { camera = null; }
  16465. if (!camera) {
  16466. camera = this.getScene().activeCamera;
  16467. }
  16468. return this.absolutePosition.subtract(camera.position).length();
  16469. };
  16470. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16471. if (!this.physicsImpostor) {
  16472. return this;
  16473. }
  16474. this.physicsImpostor.applyImpulse(force, contactPoint);
  16475. return this;
  16476. };
  16477. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16478. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16479. return this;
  16480. }
  16481. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16482. mainPivot: pivot1,
  16483. connectedPivot: pivot2,
  16484. nativeParams: options
  16485. });
  16486. return this;
  16487. };
  16488. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16489. // Collisions
  16490. /**
  16491. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16492. * Default `false`.
  16493. */
  16494. get: function () {
  16495. return this._checkCollisions;
  16496. },
  16497. set: function (collisionEnabled) {
  16498. this._checkCollisions = collisionEnabled;
  16499. if (this.getScene().workerCollisions) {
  16500. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16501. }
  16502. },
  16503. enumerable: true,
  16504. configurable: true
  16505. });
  16506. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16507. /**
  16508. * Gets Collider object used to compute collisions (not physics)
  16509. */
  16510. get: function () {
  16511. return this._collider;
  16512. },
  16513. enumerable: true,
  16514. configurable: true
  16515. });
  16516. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16517. var globalPosition = this.getAbsolutePosition();
  16518. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16519. if (!this._collider) {
  16520. this._collider = new BABYLON.Collider();
  16521. }
  16522. this._collider._radius = this.ellipsoid;
  16523. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16524. return this;
  16525. };
  16526. // Submeshes octree
  16527. /**
  16528. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16529. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16530. * Returns an Octree of submeshes.
  16531. */
  16532. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16533. if (maxCapacity === void 0) { maxCapacity = 64; }
  16534. if (maxDepth === void 0) { maxDepth = 2; }
  16535. if (!this._submeshesOctree) {
  16536. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16537. }
  16538. this.computeWorldMatrix(true);
  16539. var boundingInfo = this.getBoundingInfo();
  16540. // Update octree
  16541. var bbox = boundingInfo.boundingBox;
  16542. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16543. return this._submeshesOctree;
  16544. };
  16545. // Collisions
  16546. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16547. this._generatePointsArray();
  16548. if (!this._positions) {
  16549. return this;
  16550. }
  16551. // Transformation
  16552. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16553. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16554. subMesh._lastColliderWorldVertices = [];
  16555. subMesh._trianglePlanes = [];
  16556. var start = subMesh.verticesStart;
  16557. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16558. for (var i = start; i < end; i++) {
  16559. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16560. }
  16561. }
  16562. // Collide
  16563. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16564. if (collider.collisionFound) {
  16565. collider.collidedMesh = this;
  16566. }
  16567. return this;
  16568. };
  16569. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16570. var subMeshes;
  16571. var len;
  16572. // Octrees
  16573. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16574. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16575. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16576. len = intersections.length;
  16577. subMeshes = intersections.data;
  16578. }
  16579. else {
  16580. subMeshes = this.subMeshes;
  16581. len = subMeshes.length;
  16582. }
  16583. for (var index = 0; index < len; index++) {
  16584. var subMesh = subMeshes[index];
  16585. // Bounding test
  16586. if (len > 1 && !subMesh._checkCollision(collider))
  16587. continue;
  16588. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16589. }
  16590. return this;
  16591. };
  16592. AbstractMesh.prototype._checkCollision = function (collider) {
  16593. // Bounding box test
  16594. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16595. return this;
  16596. // Transformation matrix
  16597. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16598. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16599. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16600. return this;
  16601. };
  16602. // Picking
  16603. AbstractMesh.prototype._generatePointsArray = function () {
  16604. return false;
  16605. };
  16606. /**
  16607. * Checks if the passed Ray intersects with the mesh.
  16608. * Returns an object PickingInfo.
  16609. */
  16610. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16611. var pickingInfo = new BABYLON.PickingInfo();
  16612. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16613. return pickingInfo;
  16614. }
  16615. if (!this._generatePointsArray()) {
  16616. return pickingInfo;
  16617. }
  16618. var intersectInfo = null;
  16619. // Octrees
  16620. var subMeshes;
  16621. var len;
  16622. if (this._submeshesOctree && this.useOctreeForPicking) {
  16623. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16624. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16625. len = intersections.length;
  16626. subMeshes = intersections.data;
  16627. }
  16628. else {
  16629. subMeshes = this.subMeshes;
  16630. len = subMeshes.length;
  16631. }
  16632. for (var index = 0; index < len; index++) {
  16633. var subMesh = subMeshes[index];
  16634. // Bounding test
  16635. if (len > 1 && !subMesh.canIntersects(ray))
  16636. continue;
  16637. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16638. if (currentIntersectInfo) {
  16639. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16640. intersectInfo = currentIntersectInfo;
  16641. intersectInfo.subMeshId = index;
  16642. if (fastCheck) {
  16643. break;
  16644. }
  16645. }
  16646. }
  16647. }
  16648. if (intersectInfo) {
  16649. // Get picked point
  16650. var world = this.getWorldMatrix();
  16651. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16652. var direction = ray.direction.clone();
  16653. direction = direction.scale(intersectInfo.distance);
  16654. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16655. var pickedPoint = worldOrigin.add(worldDirection);
  16656. // Return result
  16657. pickingInfo.hit = true;
  16658. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16659. pickingInfo.pickedPoint = pickedPoint;
  16660. pickingInfo.pickedMesh = this;
  16661. pickingInfo.bu = intersectInfo.bu || 0;
  16662. pickingInfo.bv = intersectInfo.bv || 0;
  16663. pickingInfo.faceId = intersectInfo.faceId;
  16664. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16665. return pickingInfo;
  16666. }
  16667. return pickingInfo;
  16668. };
  16669. /**
  16670. * Clones the mesh, used by the class Mesh.
  16671. * Just returns `null` for an AbstractMesh.
  16672. */
  16673. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16674. return null;
  16675. };
  16676. /**
  16677. * Disposes all the mesh submeshes.
  16678. * Returns the AbstractMesh.
  16679. */
  16680. AbstractMesh.prototype.releaseSubMeshes = function () {
  16681. if (this.subMeshes) {
  16682. while (this.subMeshes.length) {
  16683. this.subMeshes[0].dispose();
  16684. }
  16685. }
  16686. else {
  16687. this.subMeshes = new Array();
  16688. }
  16689. return this;
  16690. };
  16691. /**
  16692. * Disposes the AbstractMesh.
  16693. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16694. * Returns nothing.
  16695. */
  16696. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16697. var _this = this;
  16698. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16699. var index;
  16700. // Action manager
  16701. if (this.actionManager !== undefined && this.actionManager !== null) {
  16702. this.actionManager.dispose();
  16703. this.actionManager = null;
  16704. }
  16705. // Skeleton
  16706. this.skeleton = null;
  16707. // Physics
  16708. if (this.physicsImpostor) {
  16709. this.physicsImpostor.dispose();
  16710. }
  16711. // Intersections in progress
  16712. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16713. var other = this._intersectionsInProgress[index];
  16714. var pos = other._intersectionsInProgress.indexOf(this);
  16715. other._intersectionsInProgress.splice(pos, 1);
  16716. }
  16717. this._intersectionsInProgress = [];
  16718. // Lights
  16719. var lights = this.getScene().lights;
  16720. lights.forEach(function (light) {
  16721. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16722. if (meshIndex !== -1) {
  16723. light.includedOnlyMeshes.splice(meshIndex, 1);
  16724. }
  16725. meshIndex = light.excludedMeshes.indexOf(_this);
  16726. if (meshIndex !== -1) {
  16727. light.excludedMeshes.splice(meshIndex, 1);
  16728. }
  16729. // Shadow generators
  16730. var generator = light.getShadowGenerator();
  16731. if (generator) {
  16732. var shadowMap = generator.getShadowMap();
  16733. if (shadowMap && shadowMap.renderList) {
  16734. meshIndex = shadowMap.renderList.indexOf(_this);
  16735. if (meshIndex !== -1) {
  16736. shadowMap.renderList.splice(meshIndex, 1);
  16737. }
  16738. }
  16739. }
  16740. });
  16741. // Edges
  16742. if (this._edgesRenderer) {
  16743. this._edgesRenderer.dispose();
  16744. this._edgesRenderer = null;
  16745. }
  16746. // SubMeshes
  16747. if (this.getClassName() !== "InstancedMesh") {
  16748. this.releaseSubMeshes();
  16749. }
  16750. // Octree
  16751. var sceneOctree = this.getScene().selectionOctree;
  16752. if (sceneOctree !== undefined && sceneOctree !== null) {
  16753. var index = sceneOctree.dynamicContent.indexOf(this);
  16754. if (index !== -1) {
  16755. sceneOctree.dynamicContent.splice(index, 1);
  16756. }
  16757. }
  16758. // Query
  16759. var engine = this.getScene().getEngine();
  16760. if (this._occlusionQuery) {
  16761. this._isOcclusionQueryInProgress = false;
  16762. engine.deleteQuery(this._occlusionQuery);
  16763. this._occlusionQuery = null;
  16764. }
  16765. // Engine
  16766. engine.wipeCaches();
  16767. // Remove from scene
  16768. this.getScene().removeMesh(this);
  16769. if (disposeMaterialAndTextures) {
  16770. if (this.material) {
  16771. this.material.dispose(false, true);
  16772. }
  16773. }
  16774. if (!doNotRecurse) {
  16775. // Particles
  16776. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16777. if (this.getScene().particleSystems[index].emitter === this) {
  16778. this.getScene().particleSystems[index].dispose();
  16779. index--;
  16780. }
  16781. }
  16782. }
  16783. // facet data
  16784. if (this._facetDataEnabled) {
  16785. this.disableFacetData();
  16786. }
  16787. this.onAfterWorldMatrixUpdateObservable.clear();
  16788. this.onCollideObservable.clear();
  16789. this.onCollisionPositionChangeObservable.clear();
  16790. this._isDisposed = true;
  16791. _super.prototype.dispose.call(this, doNotRecurse);
  16792. };
  16793. /**
  16794. * Adds the passed mesh as a child to the current mesh.
  16795. * Returns the AbstractMesh.
  16796. */
  16797. AbstractMesh.prototype.addChild = function (mesh) {
  16798. mesh.setParent(this);
  16799. return this;
  16800. };
  16801. /**
  16802. * Removes the passed mesh from the current mesh children list.
  16803. * Returns the AbstractMesh.
  16804. */
  16805. AbstractMesh.prototype.removeChild = function (mesh) {
  16806. mesh.setParent(null);
  16807. return this;
  16808. };
  16809. // Facet data
  16810. /**
  16811. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16812. * Returns the AbstractMesh.
  16813. */
  16814. AbstractMesh.prototype._initFacetData = function () {
  16815. if (!this._facetNormals) {
  16816. this._facetNormals = new Array();
  16817. }
  16818. if (!this._facetPositions) {
  16819. this._facetPositions = new Array();
  16820. }
  16821. if (!this._facetPartitioning) {
  16822. this._facetPartitioning = new Array();
  16823. }
  16824. this._facetNb = (this.getIndices().length / 3) | 0;
  16825. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16826. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16827. for (var f = 0; f < this._facetNb; f++) {
  16828. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16829. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16830. }
  16831. this._facetDataEnabled = true;
  16832. return this;
  16833. };
  16834. /**
  16835. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16836. * This method can be called within the render loop.
  16837. * 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.
  16838. * Returns the AbstractMesh.
  16839. */
  16840. AbstractMesh.prototype.updateFacetData = function () {
  16841. if (!this._facetDataEnabled) {
  16842. this._initFacetData();
  16843. }
  16844. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16845. var indices = this.getIndices();
  16846. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16847. var bInfo = this.getBoundingInfo();
  16848. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16849. // init arrays, matrix and sort function on first call
  16850. this._facetDepthSortEnabled = true;
  16851. if (indices instanceof Uint16Array) {
  16852. this._depthSortedIndices = new Uint16Array(indices);
  16853. }
  16854. else if (indices instanceof Uint32Array) {
  16855. this._depthSortedIndices = new Uint32Array(indices);
  16856. }
  16857. else {
  16858. var needs32bits = false;
  16859. for (var i = 0; i < indices.length; i++) {
  16860. if (indices[i] > 65535) {
  16861. needs32bits = true;
  16862. break;
  16863. }
  16864. }
  16865. if (needs32bits) {
  16866. this._depthSortedIndices = new Uint32Array(indices);
  16867. }
  16868. else {
  16869. this._depthSortedIndices = new Uint16Array(indices);
  16870. }
  16871. }
  16872. this._facetDepthSortFunction = function (f1, f2) {
  16873. return (f2.sqDistance - f1.sqDistance);
  16874. };
  16875. if (!this._facetDepthSortFrom) {
  16876. var camera = this.getScene().activeCamera;
  16877. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16878. }
  16879. this._depthSortedFacets = [];
  16880. for (var f = 0; f < this._facetNb; f++) {
  16881. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16882. this._depthSortedFacets.push(depthSortedFacet);
  16883. }
  16884. this._invertedMatrix = BABYLON.Matrix.Identity();
  16885. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16886. }
  16887. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16888. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16889. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16890. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16891. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16892. this._subDiv.max = this._partitioningSubdivisions;
  16893. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16894. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16895. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16896. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16897. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16898. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16899. // set the parameters for ComputeNormals()
  16900. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16901. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16902. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16903. this._facetParameters.bInfo = bInfo;
  16904. this._facetParameters.bbSize = this._bbSize;
  16905. this._facetParameters.subDiv = this._subDiv;
  16906. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16907. this._facetParameters.depthSort = this._facetDepthSort;
  16908. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16909. this.computeWorldMatrix(true);
  16910. this._worldMatrix.invertToRef(this._invertedMatrix);
  16911. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16912. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16913. }
  16914. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16915. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16916. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16917. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16918. var l = (this._depthSortedIndices.length / 3) | 0;
  16919. for (var f = 0; f < l; f++) {
  16920. var sind = this._depthSortedFacets[f].ind;
  16921. this._depthSortedIndices[f * 3] = indices[sind];
  16922. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16923. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16924. }
  16925. this.updateIndices(this._depthSortedIndices);
  16926. }
  16927. return this;
  16928. };
  16929. /**
  16930. * Returns the facetLocalNormals array.
  16931. * The normals are expressed in the mesh local space.
  16932. */
  16933. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16934. if (!this._facetNormals) {
  16935. this.updateFacetData();
  16936. }
  16937. return this._facetNormals;
  16938. };
  16939. /**
  16940. * Returns the facetLocalPositions array.
  16941. * The facet positions are expressed in the mesh local space.
  16942. */
  16943. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16944. if (!this._facetPositions) {
  16945. this.updateFacetData();
  16946. }
  16947. return this._facetPositions;
  16948. };
  16949. /**
  16950. * Returns the facetLocalPartioning array.
  16951. */
  16952. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16953. if (!this._facetPartitioning) {
  16954. this.updateFacetData();
  16955. }
  16956. return this._facetPartitioning;
  16957. };
  16958. /**
  16959. * Returns the i-th facet position in the world system.
  16960. * This method allocates a new Vector3 per call.
  16961. */
  16962. AbstractMesh.prototype.getFacetPosition = function (i) {
  16963. var pos = BABYLON.Vector3.Zero();
  16964. this.getFacetPositionToRef(i, pos);
  16965. return pos;
  16966. };
  16967. /**
  16968. * Sets the reference Vector3 with the i-th facet position in the world system.
  16969. * Returns the AbstractMesh.
  16970. */
  16971. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16972. var localPos = (this.getFacetLocalPositions())[i];
  16973. var world = this.getWorldMatrix();
  16974. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16975. return this;
  16976. };
  16977. /**
  16978. * Returns the i-th facet normal in the world system.
  16979. * This method allocates a new Vector3 per call.
  16980. */
  16981. AbstractMesh.prototype.getFacetNormal = function (i) {
  16982. var norm = BABYLON.Vector3.Zero();
  16983. this.getFacetNormalToRef(i, norm);
  16984. return norm;
  16985. };
  16986. /**
  16987. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16988. * Returns the AbstractMesh.
  16989. */
  16990. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16991. var localNorm = (this.getFacetLocalNormals())[i];
  16992. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16993. return this;
  16994. };
  16995. /**
  16996. * 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).
  16997. */
  16998. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16999. var bInfo = this.getBoundingInfo();
  17000. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17001. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17002. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17003. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17004. return null;
  17005. }
  17006. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17007. };
  17008. /**
  17009. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17010. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17011. * 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.
  17012. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17013. * 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.
  17014. */
  17015. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17016. if (checkFace === void 0) { checkFace = false; }
  17017. if (facing === void 0) { facing = true; }
  17018. var world = this.getWorldMatrix();
  17019. var invMat = BABYLON.Tmp.Matrix[5];
  17020. world.invertToRef(invMat);
  17021. var invVect = BABYLON.Tmp.Vector3[8];
  17022. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17023. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17024. if (projected) {
  17025. // tranform the local computed projected vector to world coordinates
  17026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17027. }
  17028. return closest;
  17029. };
  17030. /**
  17031. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17032. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17033. * 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.
  17034. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17035. * 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.
  17036. */
  17037. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17038. if (checkFace === void 0) { checkFace = false; }
  17039. if (facing === void 0) { facing = true; }
  17040. var closest = null;
  17041. var tmpx = 0.0;
  17042. var tmpy = 0.0;
  17043. var tmpz = 0.0;
  17044. var d = 0.0; // tmp dot facet normal * facet position
  17045. var t0 = 0.0;
  17046. var projx = 0.0;
  17047. var projy = 0.0;
  17048. var projz = 0.0;
  17049. // Get all the facets in the same partitioning block than (x, y, z)
  17050. var facetPositions = this.getFacetLocalPositions();
  17051. var facetNormals = this.getFacetLocalNormals();
  17052. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17053. if (!facetsInBlock) {
  17054. return null;
  17055. }
  17056. // Get the closest facet to (x, y, z)
  17057. var shortest = Number.MAX_VALUE; // init distance vars
  17058. var tmpDistance = shortest;
  17059. var fib; // current facet in the block
  17060. var norm; // current facet normal
  17061. var p0; // current facet barycenter position
  17062. // loop on all the facets in the current partitioning block
  17063. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17064. fib = facetsInBlock[idx];
  17065. norm = facetNormals[fib];
  17066. p0 = facetPositions[fib];
  17067. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17068. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17069. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17070. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17071. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17072. projx = x + norm.x * t0;
  17073. projy = y + norm.y * t0;
  17074. projz = z + norm.z * t0;
  17075. tmpx = projx - x;
  17076. tmpy = projy - y;
  17077. tmpz = projz - z;
  17078. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17079. if (tmpDistance < shortest) {
  17080. shortest = tmpDistance;
  17081. closest = fib;
  17082. if (projected) {
  17083. projected.x = projx;
  17084. projected.y = projy;
  17085. projected.z = projz;
  17086. }
  17087. }
  17088. }
  17089. }
  17090. return closest;
  17091. };
  17092. /**
  17093. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17094. */
  17095. AbstractMesh.prototype.getFacetDataParameters = function () {
  17096. return this._facetParameters;
  17097. };
  17098. /**
  17099. * Disables the feature FacetData and frees the related memory.
  17100. * Returns the AbstractMesh.
  17101. */
  17102. AbstractMesh.prototype.disableFacetData = function () {
  17103. if (this._facetDataEnabled) {
  17104. this._facetDataEnabled = false;
  17105. this._facetPositions = new Array();
  17106. this._facetNormals = new Array();
  17107. this._facetPartitioning = new Array();
  17108. this._facetParameters = null;
  17109. this._depthSortedIndices = new Uint32Array(0);
  17110. }
  17111. return this;
  17112. };
  17113. /**
  17114. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17115. * Returns the mesh.
  17116. */
  17117. AbstractMesh.prototype.updateIndices = function (indices) {
  17118. return this;
  17119. };
  17120. /**
  17121. * The mesh Geometry. Actually used by the Mesh object.
  17122. * Returns a blank geometry object.
  17123. */
  17124. /**
  17125. * Creates new normals data for the mesh.
  17126. * @param updatable.
  17127. */
  17128. AbstractMesh.prototype.createNormals = function (updatable) {
  17129. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17130. var indices = this.getIndices();
  17131. var normals;
  17132. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17133. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17134. }
  17135. else {
  17136. normals = [];
  17137. }
  17138. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17139. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17140. };
  17141. /**
  17142. * Align the mesh with a normal.
  17143. * Returns the mesh.
  17144. */
  17145. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17146. if (!upDirection) {
  17147. upDirection = BABYLON.Axis.Y;
  17148. }
  17149. var axisX = BABYLON.Tmp.Vector3[0];
  17150. var axisZ = BABYLON.Tmp.Vector3[1];
  17151. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17152. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17153. if (this.rotationQuaternion) {
  17154. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17155. }
  17156. else {
  17157. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17158. }
  17159. return this;
  17160. };
  17161. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17162. var engine = this.getEngine();
  17163. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17164. this._isOccluded = false;
  17165. return;
  17166. }
  17167. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17168. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17169. if (isOcclusionQueryAvailable) {
  17170. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17171. this._isOcclusionQueryInProgress = false;
  17172. this._occlusionInternalRetryCounter = 0;
  17173. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17174. }
  17175. else {
  17176. this._occlusionInternalRetryCounter++;
  17177. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17178. this._isOcclusionQueryInProgress = false;
  17179. this._occlusionInternalRetryCounter = 0;
  17180. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17181. // if strict continue the last state of the object.
  17182. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17183. }
  17184. else {
  17185. return;
  17186. }
  17187. }
  17188. }
  17189. var scene = this.getScene();
  17190. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17191. if (!this._occlusionQuery) {
  17192. this._occlusionQuery = engine.createQuery();
  17193. }
  17194. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17195. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17196. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17197. this._isOcclusionQueryInProgress = true;
  17198. };
  17199. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17200. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17201. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17202. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17203. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17204. return AbstractMesh;
  17205. }(BABYLON.TransformNode));
  17206. BABYLON.AbstractMesh = AbstractMesh;
  17207. })(BABYLON || (BABYLON = {}));
  17208. //# sourceMappingURL=babylon.abstractMesh.js.map
  17209. var BABYLON;
  17210. (function (BABYLON) {
  17211. var Light = /** @class */ (function (_super) {
  17212. __extends(Light, _super);
  17213. /**
  17214. * Creates a Light object in the scene.
  17215. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17216. */
  17217. function Light(name, scene) {
  17218. var _this = _super.call(this, name, scene) || this;
  17219. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17220. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17221. _this.intensity = 1.0;
  17222. _this.range = Number.MAX_VALUE;
  17223. /**
  17224. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17225. * of light.
  17226. */
  17227. _this._photometricScale = 1.0;
  17228. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17229. _this._radius = 0.00001;
  17230. _this.renderPriority = 0;
  17231. /**
  17232. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17233. * the current shadow generator.
  17234. */
  17235. _this.shadowEnabled = true;
  17236. _this._excludeWithLayerMask = 0;
  17237. _this._includeOnlyWithLayerMask = 0;
  17238. _this._lightmapMode = 0;
  17239. _this._excludedMeshesIds = new Array();
  17240. _this._includedOnlyMeshesIds = new Array();
  17241. _this.getScene().addLight(_this);
  17242. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17243. _this._buildUniformLayout();
  17244. _this.includedOnlyMeshes = new Array();
  17245. _this.excludedMeshes = new Array();
  17246. _this._resyncMeshes();
  17247. return _this;
  17248. }
  17249. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17250. /**
  17251. * If every light affecting the material is in this lightmapMode,
  17252. * material.lightmapTexture adds or multiplies
  17253. * (depends on material.useLightmapAsShadowmap)
  17254. * after every other light calculations.
  17255. */
  17256. get: function () {
  17257. return Light._LIGHTMAP_DEFAULT;
  17258. },
  17259. enumerable: true,
  17260. configurable: true
  17261. });
  17262. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17263. /**
  17264. * material.lightmapTexture as only diffuse lighting from this light
  17265. * adds only specular lighting from this light
  17266. * adds dynamic shadows
  17267. */
  17268. get: function () {
  17269. return Light._LIGHTMAP_SPECULAR;
  17270. },
  17271. enumerable: true,
  17272. configurable: true
  17273. });
  17274. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17275. /**
  17276. * material.lightmapTexture as only lighting
  17277. * no light calculation from this light
  17278. * only adds dynamic shadows from this light
  17279. */
  17280. get: function () {
  17281. return Light._LIGHTMAP_SHADOWSONLY;
  17282. },
  17283. enumerable: true,
  17284. configurable: true
  17285. });
  17286. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17287. /**
  17288. * Each light type uses the default quantity according to its type:
  17289. * point/spot lights use luminous intensity
  17290. * directional lights use illuminance
  17291. */
  17292. get: function () {
  17293. return Light._INTENSITYMODE_AUTOMATIC;
  17294. },
  17295. enumerable: true,
  17296. configurable: true
  17297. });
  17298. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17299. /**
  17300. * lumen (lm)
  17301. */
  17302. get: function () {
  17303. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17304. },
  17305. enumerable: true,
  17306. configurable: true
  17307. });
  17308. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17309. /**
  17310. * candela (lm/sr)
  17311. */
  17312. get: function () {
  17313. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17314. },
  17315. enumerable: true,
  17316. configurable: true
  17317. });
  17318. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17319. /**
  17320. * lux (lm/m^2)
  17321. */
  17322. get: function () {
  17323. return Light._INTENSITYMODE_ILLUMINANCE;
  17324. },
  17325. enumerable: true,
  17326. configurable: true
  17327. });
  17328. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17329. /**
  17330. * nit (cd/m^2)
  17331. */
  17332. get: function () {
  17333. return Light._INTENSITYMODE_LUMINANCE;
  17334. },
  17335. enumerable: true,
  17336. configurable: true
  17337. });
  17338. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17339. /**
  17340. * Light type const id of the point light.
  17341. */
  17342. get: function () {
  17343. return Light._LIGHTTYPEID_POINTLIGHT;
  17344. },
  17345. enumerable: true,
  17346. configurable: true
  17347. });
  17348. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17349. /**
  17350. * Light type const id of the directional light.
  17351. */
  17352. get: function () {
  17353. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17354. },
  17355. enumerable: true,
  17356. configurable: true
  17357. });
  17358. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17359. /**
  17360. * Light type const id of the spot light.
  17361. */
  17362. get: function () {
  17363. return Light._LIGHTTYPEID_SPOTLIGHT;
  17364. },
  17365. enumerable: true,
  17366. configurable: true
  17367. });
  17368. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17369. /**
  17370. * Light type const id of the hemispheric light.
  17371. */
  17372. get: function () {
  17373. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17374. },
  17375. enumerable: true,
  17376. configurable: true
  17377. });
  17378. Object.defineProperty(Light.prototype, "intensityMode", {
  17379. /**
  17380. * Gets the photometric scale used to interpret the intensity.
  17381. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17382. */
  17383. get: function () {
  17384. return this._intensityMode;
  17385. },
  17386. /**
  17387. * Sets the photometric scale used to interpret the intensity.
  17388. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17389. */
  17390. set: function (value) {
  17391. this._intensityMode = value;
  17392. this._computePhotometricScale();
  17393. },
  17394. enumerable: true,
  17395. configurable: true
  17396. });
  17397. ;
  17398. ;
  17399. Object.defineProperty(Light.prototype, "radius", {
  17400. /**
  17401. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17402. */
  17403. get: function () {
  17404. return this._radius;
  17405. },
  17406. /**
  17407. * sets the light radius used by PBR Materials to simulate soft area lights.
  17408. */
  17409. set: function (value) {
  17410. this._radius = value;
  17411. this._computePhotometricScale();
  17412. },
  17413. enumerable: true,
  17414. configurable: true
  17415. });
  17416. ;
  17417. ;
  17418. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17419. get: function () {
  17420. return this._includedOnlyMeshes;
  17421. },
  17422. set: function (value) {
  17423. this._includedOnlyMeshes = value;
  17424. this._hookArrayForIncludedOnly(value);
  17425. },
  17426. enumerable: true,
  17427. configurable: true
  17428. });
  17429. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17430. get: function () {
  17431. return this._excludedMeshes;
  17432. },
  17433. set: function (value) {
  17434. this._excludedMeshes = value;
  17435. this._hookArrayForExcluded(value);
  17436. },
  17437. enumerable: true,
  17438. configurable: true
  17439. });
  17440. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17441. get: function () {
  17442. return this._excludeWithLayerMask;
  17443. },
  17444. set: function (value) {
  17445. this._excludeWithLayerMask = value;
  17446. this._resyncMeshes();
  17447. },
  17448. enumerable: true,
  17449. configurable: true
  17450. });
  17451. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17452. get: function () {
  17453. return this._includeOnlyWithLayerMask;
  17454. },
  17455. set: function (value) {
  17456. this._includeOnlyWithLayerMask = value;
  17457. this._resyncMeshes();
  17458. },
  17459. enumerable: true,
  17460. configurable: true
  17461. });
  17462. Object.defineProperty(Light.prototype, "lightmapMode", {
  17463. get: function () {
  17464. return this._lightmapMode;
  17465. },
  17466. set: function (value) {
  17467. if (this._lightmapMode === value) {
  17468. return;
  17469. }
  17470. this._lightmapMode = value;
  17471. this._markMeshesAsLightDirty();
  17472. },
  17473. enumerable: true,
  17474. configurable: true
  17475. });
  17476. Light.prototype._buildUniformLayout = function () {
  17477. // Overridden
  17478. };
  17479. /**
  17480. * Returns the string "Light".
  17481. */
  17482. Light.prototype.getClassName = function () {
  17483. return "Light";
  17484. };
  17485. /**
  17486. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17487. */
  17488. Light.prototype.toString = function (fullDetails) {
  17489. var ret = "Name: " + this.name;
  17490. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17491. if (this.animations) {
  17492. for (var i = 0; i < this.animations.length; i++) {
  17493. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17494. }
  17495. }
  17496. if (fullDetails) {
  17497. }
  17498. return ret;
  17499. };
  17500. /**
  17501. * Set the enabled state of this node.
  17502. * @param {boolean} value - the new enabled state
  17503. * @see isEnabled
  17504. */
  17505. Light.prototype.setEnabled = function (value) {
  17506. _super.prototype.setEnabled.call(this, value);
  17507. this._resyncMeshes();
  17508. };
  17509. /**
  17510. * Returns the Light associated shadow generator.
  17511. */
  17512. Light.prototype.getShadowGenerator = function () {
  17513. return this._shadowGenerator;
  17514. };
  17515. /**
  17516. * Returns a Vector3, the absolute light position in the World.
  17517. */
  17518. Light.prototype.getAbsolutePosition = function () {
  17519. return BABYLON.Vector3.Zero();
  17520. };
  17521. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17522. };
  17523. Light.prototype._getWorldMatrix = function () {
  17524. return BABYLON.Matrix.Identity();
  17525. };
  17526. /**
  17527. * Boolean : True if the light will affect the passed mesh.
  17528. */
  17529. Light.prototype.canAffectMesh = function (mesh) {
  17530. if (!mesh) {
  17531. return true;
  17532. }
  17533. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17534. return false;
  17535. }
  17536. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17537. return false;
  17538. }
  17539. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17540. return false;
  17541. }
  17542. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17543. return false;
  17544. }
  17545. return true;
  17546. };
  17547. /**
  17548. * Returns the light World matrix.
  17549. */
  17550. Light.prototype.getWorldMatrix = function () {
  17551. this._currentRenderId = this.getScene().getRenderId();
  17552. var worldMatrix = this._getWorldMatrix();
  17553. if (this.parent && this.parent.getWorldMatrix) {
  17554. if (!this._parentedWorldMatrix) {
  17555. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17556. }
  17557. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17558. this._markSyncedWithParent();
  17559. return this._parentedWorldMatrix;
  17560. }
  17561. return worldMatrix;
  17562. };
  17563. /**
  17564. * Sort function to order lights for rendering.
  17565. * @param a First Light object to compare to second.
  17566. * @param b Second Light object to compare first.
  17567. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17568. */
  17569. Light.compareLightsPriority = function (a, b) {
  17570. //shadow-casting lights have priority over non-shadow-casting lights
  17571. //the renderPrioirty is a secondary sort criterion
  17572. if (a.shadowEnabled !== b.shadowEnabled) {
  17573. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17574. }
  17575. return b.renderPriority - a.renderPriority;
  17576. };
  17577. /**
  17578. * Disposes the light.
  17579. */
  17580. Light.prototype.dispose = function () {
  17581. if (this._shadowGenerator) {
  17582. this._shadowGenerator.dispose();
  17583. this._shadowGenerator = null;
  17584. }
  17585. // Animations
  17586. this.getScene().stopAnimation(this);
  17587. this._uniformBuffer.dispose();
  17588. // Remove from scene
  17589. this.getScene().removeLight(this);
  17590. _super.prototype.dispose.call(this);
  17591. };
  17592. /**
  17593. * Returns the light type ID (integer).
  17594. */
  17595. Light.prototype.getTypeID = function () {
  17596. return 0;
  17597. };
  17598. /**
  17599. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17600. */
  17601. Light.prototype.getScaledIntensity = function () {
  17602. return this._photometricScale * this.intensity;
  17603. };
  17604. /**
  17605. * Returns a new Light object, named "name", from the current one.
  17606. */
  17607. Light.prototype.clone = function (name) {
  17608. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17609. if (!constructor) {
  17610. return null;
  17611. }
  17612. return BABYLON.SerializationHelper.Clone(constructor, this);
  17613. };
  17614. /**
  17615. * Serializes the current light into a Serialization object.
  17616. * Returns the serialized object.
  17617. */
  17618. Light.prototype.serialize = function () {
  17619. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17620. // Type
  17621. serializationObject.type = this.getTypeID();
  17622. // Parent
  17623. if (this.parent) {
  17624. serializationObject.parentId = this.parent.id;
  17625. }
  17626. // Inclusion / exclusions
  17627. if (this.excludedMeshes.length > 0) {
  17628. serializationObject.excludedMeshesIds = [];
  17629. this.excludedMeshes.forEach(function (mesh) {
  17630. serializationObject.excludedMeshesIds.push(mesh.id);
  17631. });
  17632. }
  17633. if (this.includedOnlyMeshes.length > 0) {
  17634. serializationObject.includedOnlyMeshesIds = [];
  17635. this.includedOnlyMeshes.forEach(function (mesh) {
  17636. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17637. });
  17638. }
  17639. // Animations
  17640. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17641. serializationObject.ranges = this.serializeAnimationRanges();
  17642. return serializationObject;
  17643. };
  17644. /**
  17645. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17646. * This new light is named "name" and added to the passed scene.
  17647. */
  17648. Light.GetConstructorFromName = function (type, name, scene) {
  17649. switch (type) {
  17650. case 0:
  17651. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17652. case 1:
  17653. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17654. case 2:
  17655. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17656. case 3:
  17657. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17658. }
  17659. return null;
  17660. };
  17661. /**
  17662. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17663. */
  17664. Light.Parse = function (parsedLight, scene) {
  17665. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17666. if (!constructor) {
  17667. return null;
  17668. }
  17669. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17670. // Inclusion / exclusions
  17671. if (parsedLight.excludedMeshesIds) {
  17672. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17673. }
  17674. if (parsedLight.includedOnlyMeshesIds) {
  17675. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17676. }
  17677. // Parent
  17678. if (parsedLight.parentId) {
  17679. light._waitingParentId = parsedLight.parentId;
  17680. }
  17681. // Animations
  17682. if (parsedLight.animations) {
  17683. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17684. var parsedAnimation = parsedLight.animations[animationIndex];
  17685. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17686. }
  17687. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17688. }
  17689. if (parsedLight.autoAnimate) {
  17690. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17691. }
  17692. return light;
  17693. };
  17694. Light.prototype._hookArrayForExcluded = function (array) {
  17695. var _this = this;
  17696. var oldPush = array.push;
  17697. array.push = function () {
  17698. var items = [];
  17699. for (var _i = 0; _i < arguments.length; _i++) {
  17700. items[_i] = arguments[_i];
  17701. }
  17702. var result = oldPush.apply(array, items);
  17703. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17704. var item = items_1[_a];
  17705. item._resyncLighSource(_this);
  17706. }
  17707. return result;
  17708. };
  17709. var oldSplice = array.splice;
  17710. array.splice = function (index, deleteCount) {
  17711. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17712. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17713. var item = deleted_1[_i];
  17714. item._resyncLighSource(_this);
  17715. }
  17716. return deleted;
  17717. };
  17718. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17719. var item = array_1[_i];
  17720. item._resyncLighSource(this);
  17721. }
  17722. };
  17723. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17724. var _this = this;
  17725. var oldPush = array.push;
  17726. array.push = function () {
  17727. var items = [];
  17728. for (var _i = 0; _i < arguments.length; _i++) {
  17729. items[_i] = arguments[_i];
  17730. }
  17731. var result = oldPush.apply(array, items);
  17732. _this._resyncMeshes();
  17733. return result;
  17734. };
  17735. var oldSplice = array.splice;
  17736. array.splice = function (index, deleteCount) {
  17737. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17738. _this._resyncMeshes();
  17739. return deleted;
  17740. };
  17741. this._resyncMeshes();
  17742. };
  17743. Light.prototype._resyncMeshes = function () {
  17744. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17745. var mesh = _a[_i];
  17746. mesh._resyncLighSource(this);
  17747. }
  17748. };
  17749. Light.prototype._markMeshesAsLightDirty = function () {
  17750. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17751. var mesh = _a[_i];
  17752. if (mesh._lightSources.indexOf(this) !== -1) {
  17753. mesh._markSubMeshesAsLightDirty();
  17754. }
  17755. }
  17756. };
  17757. /**
  17758. * Recomputes the cached photometric scale if needed.
  17759. */
  17760. Light.prototype._computePhotometricScale = function () {
  17761. this._photometricScale = this._getPhotometricScale();
  17762. this.getScene().resetCachedMaterial();
  17763. };
  17764. /**
  17765. * Returns the Photometric Scale according to the light type and intensity mode.
  17766. */
  17767. Light.prototype._getPhotometricScale = function () {
  17768. var photometricScale = 0.0;
  17769. var lightTypeID = this.getTypeID();
  17770. //get photometric mode
  17771. var photometricMode = this.intensityMode;
  17772. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17773. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17774. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17775. }
  17776. else {
  17777. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17778. }
  17779. }
  17780. //compute photometric scale
  17781. switch (lightTypeID) {
  17782. case Light.LIGHTTYPEID_POINTLIGHT:
  17783. case Light.LIGHTTYPEID_SPOTLIGHT:
  17784. switch (photometricMode) {
  17785. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17786. photometricScale = 1.0 / (4.0 * Math.PI);
  17787. break;
  17788. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17789. photometricScale = 1.0;
  17790. break;
  17791. case Light.INTENSITYMODE_LUMINANCE:
  17792. photometricScale = this.radius * this.radius;
  17793. break;
  17794. }
  17795. break;
  17796. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17797. switch (photometricMode) {
  17798. case Light.INTENSITYMODE_ILLUMINANCE:
  17799. photometricScale = 1.0;
  17800. break;
  17801. case Light.INTENSITYMODE_LUMINANCE:
  17802. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17803. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17804. var apexAngleRadians = this.radius;
  17805. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17806. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17807. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17808. photometricScale = solidAngle;
  17809. break;
  17810. }
  17811. break;
  17812. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17813. // No fall off in hemisperic light.
  17814. photometricScale = 1.0;
  17815. break;
  17816. }
  17817. return photometricScale;
  17818. };
  17819. Light.prototype._reorderLightsInScene = function () {
  17820. var scene = this.getScene();
  17821. if (this._renderPriority != 0) {
  17822. scene.requireLightSorting = true;
  17823. }
  17824. this.getScene().sortLightsByPriority();
  17825. };
  17826. //lightmapMode Consts
  17827. Light._LIGHTMAP_DEFAULT = 0;
  17828. Light._LIGHTMAP_SPECULAR = 1;
  17829. Light._LIGHTMAP_SHADOWSONLY = 2;
  17830. // Intensity Mode Consts
  17831. Light._INTENSITYMODE_AUTOMATIC = 0;
  17832. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17833. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17834. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17835. Light._INTENSITYMODE_LUMINANCE = 4;
  17836. // Light types ids const.
  17837. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17838. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17839. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17840. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17841. __decorate([
  17842. BABYLON.serializeAsColor3()
  17843. ], Light.prototype, "diffuse", void 0);
  17844. __decorate([
  17845. BABYLON.serializeAsColor3()
  17846. ], Light.prototype, "specular", void 0);
  17847. __decorate([
  17848. BABYLON.serialize()
  17849. ], Light.prototype, "intensity", void 0);
  17850. __decorate([
  17851. BABYLON.serialize()
  17852. ], Light.prototype, "range", void 0);
  17853. __decorate([
  17854. BABYLON.serialize()
  17855. ], Light.prototype, "intensityMode", null);
  17856. __decorate([
  17857. BABYLON.serialize()
  17858. ], Light.prototype, "radius", null);
  17859. __decorate([
  17860. BABYLON.serialize()
  17861. ], Light.prototype, "_renderPriority", void 0);
  17862. __decorate([
  17863. BABYLON.expandToProperty("_reorderLightsInScene")
  17864. ], Light.prototype, "renderPriority", void 0);
  17865. __decorate([
  17866. BABYLON.serialize()
  17867. ], Light.prototype, "shadowEnabled", void 0);
  17868. __decorate([
  17869. BABYLON.serialize("excludeWithLayerMask")
  17870. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17871. __decorate([
  17872. BABYLON.serialize("includeOnlyWithLayerMask")
  17873. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17874. __decorate([
  17875. BABYLON.serialize("lightmapMode")
  17876. ], Light.prototype, "_lightmapMode", void 0);
  17877. return Light;
  17878. }(BABYLON.Node));
  17879. BABYLON.Light = Light;
  17880. })(BABYLON || (BABYLON = {}));
  17881. //# sourceMappingURL=babylon.light.js.map
  17882. var BABYLON;
  17883. (function (BABYLON) {
  17884. var Camera = /** @class */ (function (_super) {
  17885. __extends(Camera, _super);
  17886. function Camera(name, position, scene) {
  17887. var _this = _super.call(this, name, scene) || this;
  17888. /**
  17889. * The vector the camera should consider as up.
  17890. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  17891. */
  17892. _this.upVector = BABYLON.Vector3.Up();
  17893. _this.orthoLeft = null;
  17894. _this.orthoRight = null;
  17895. _this.orthoBottom = null;
  17896. _this.orthoTop = null;
  17897. /**
  17898. * FOV is set in Radians. (default is 0.8)
  17899. */
  17900. _this.fov = 0.8;
  17901. _this.minZ = 1;
  17902. _this.maxZ = 10000.0;
  17903. _this.inertia = 0.9;
  17904. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17905. _this.isIntermediate = false;
  17906. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17907. /**
  17908. * Restricts the camera to viewing objects with the same layerMask.
  17909. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  17910. */
  17911. _this.layerMask = 0x0FFFFFFF;
  17912. /**
  17913. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  17914. */
  17915. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17916. // Camera rig members
  17917. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17918. _this._rigCameras = new Array();
  17919. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17920. _this._skipRendering = false;
  17921. _this.customRenderTargets = new Array();
  17922. // Observables
  17923. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17924. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17925. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17926. _this.onRestoreStateObservable = new BABYLON.Observable();
  17927. // Cache
  17928. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17929. _this._projectionMatrix = new BABYLON.Matrix();
  17930. _this._doNotComputeProjectionMatrix = false;
  17931. _this._postProcesses = new Array();
  17932. _this._transformMatrix = BABYLON.Matrix.Zero();
  17933. _this._activeMeshes = new BABYLON.SmartArray(256);
  17934. _this._globalPosition = BABYLON.Vector3.Zero();
  17935. _this._refreshFrustumPlanes = true;
  17936. _this.getScene().addCamera(_this);
  17937. if (!_this.getScene().activeCamera) {
  17938. _this.getScene().activeCamera = _this;
  17939. }
  17940. _this.position = position;
  17941. return _this;
  17942. }
  17943. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17944. get: function () {
  17945. return Camera._PERSPECTIVE_CAMERA;
  17946. },
  17947. enumerable: true,
  17948. configurable: true
  17949. });
  17950. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17951. get: function () {
  17952. return Camera._ORTHOGRAPHIC_CAMERA;
  17953. },
  17954. enumerable: true,
  17955. configurable: true
  17956. });
  17957. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17958. /**
  17959. * This is the default FOV mode for perspective cameras.
  17960. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17961. *
  17962. */
  17963. get: function () {
  17964. return Camera._FOVMODE_VERTICAL_FIXED;
  17965. },
  17966. enumerable: true,
  17967. configurable: true
  17968. });
  17969. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17970. /**
  17971. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17972. *
  17973. */
  17974. get: function () {
  17975. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17976. },
  17977. enumerable: true,
  17978. configurable: true
  17979. });
  17980. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17981. get: function () {
  17982. return Camera._RIG_MODE_NONE;
  17983. },
  17984. enumerable: true,
  17985. configurable: true
  17986. });
  17987. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17988. get: function () {
  17989. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17990. },
  17991. enumerable: true,
  17992. configurable: true
  17993. });
  17994. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17995. get: function () {
  17996. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17997. },
  17998. enumerable: true,
  17999. configurable: true
  18000. });
  18001. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18002. get: function () {
  18003. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18004. },
  18005. enumerable: true,
  18006. configurable: true
  18007. });
  18008. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18009. get: function () {
  18010. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18011. },
  18012. enumerable: true,
  18013. configurable: true
  18014. });
  18015. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18016. get: function () {
  18017. return Camera._RIG_MODE_VR;
  18018. },
  18019. enumerable: true,
  18020. configurable: true
  18021. });
  18022. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18023. get: function () {
  18024. return Camera._RIG_MODE_WEBVR;
  18025. },
  18026. enumerable: true,
  18027. configurable: true
  18028. });
  18029. /**
  18030. * Store current camera state (fov, position, etc..)
  18031. */
  18032. Camera.prototype.storeState = function () {
  18033. this._stateStored = true;
  18034. this._storedFov = this.fov;
  18035. return this;
  18036. };
  18037. /**
  18038. * Restores the camera state values if it has been stored. You must call storeState() first
  18039. */
  18040. Camera.prototype._restoreStateValues = function () {
  18041. if (!this._stateStored) {
  18042. return false;
  18043. }
  18044. this.fov = this._storedFov;
  18045. return true;
  18046. };
  18047. /**
  18048. * Restored camera state. You must call storeState() first
  18049. */
  18050. Camera.prototype.restoreState = function () {
  18051. if (this._restoreStateValues()) {
  18052. this.onRestoreStateObservable.notifyObservers(this);
  18053. return true;
  18054. }
  18055. return false;
  18056. };
  18057. Camera.prototype.getClassName = function () {
  18058. return "Camera";
  18059. };
  18060. /**
  18061. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18062. */
  18063. Camera.prototype.toString = function (fullDetails) {
  18064. var ret = "Name: " + this.name;
  18065. ret += ", type: " + this.getClassName();
  18066. if (this.animations) {
  18067. for (var i = 0; i < this.animations.length; i++) {
  18068. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18069. }
  18070. }
  18071. if (fullDetails) {
  18072. }
  18073. return ret;
  18074. };
  18075. Object.defineProperty(Camera.prototype, "globalPosition", {
  18076. get: function () {
  18077. return this._globalPosition;
  18078. },
  18079. enumerable: true,
  18080. configurable: true
  18081. });
  18082. Camera.prototype.getActiveMeshes = function () {
  18083. return this._activeMeshes;
  18084. };
  18085. Camera.prototype.isActiveMesh = function (mesh) {
  18086. return (this._activeMeshes.indexOf(mesh) !== -1);
  18087. };
  18088. //Cache
  18089. Camera.prototype._initCache = function () {
  18090. _super.prototype._initCache.call(this);
  18091. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18092. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18093. this._cache.mode = undefined;
  18094. this._cache.minZ = undefined;
  18095. this._cache.maxZ = undefined;
  18096. this._cache.fov = undefined;
  18097. this._cache.fovMode = undefined;
  18098. this._cache.aspectRatio = undefined;
  18099. this._cache.orthoLeft = undefined;
  18100. this._cache.orthoRight = undefined;
  18101. this._cache.orthoBottom = undefined;
  18102. this._cache.orthoTop = undefined;
  18103. this._cache.renderWidth = undefined;
  18104. this._cache.renderHeight = undefined;
  18105. };
  18106. Camera.prototype._updateCache = function (ignoreParentClass) {
  18107. if (!ignoreParentClass) {
  18108. _super.prototype._updateCache.call(this);
  18109. }
  18110. this._cache.position.copyFrom(this.position);
  18111. this._cache.upVector.copyFrom(this.upVector);
  18112. };
  18113. // Synchronized
  18114. Camera.prototype._isSynchronized = function () {
  18115. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18116. };
  18117. Camera.prototype._isSynchronizedViewMatrix = function () {
  18118. if (!_super.prototype._isSynchronized.call(this))
  18119. return false;
  18120. return this._cache.position.equals(this.position)
  18121. && this._cache.upVector.equals(this.upVector)
  18122. && this.isSynchronizedWithParent();
  18123. };
  18124. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18125. var check = this._cache.mode === this.mode
  18126. && this._cache.minZ === this.minZ
  18127. && this._cache.maxZ === this.maxZ;
  18128. if (!check) {
  18129. return false;
  18130. }
  18131. var engine = this.getEngine();
  18132. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18133. check = this._cache.fov === this.fov
  18134. && this._cache.fovMode === this.fovMode
  18135. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18136. }
  18137. else {
  18138. check = this._cache.orthoLeft === this.orthoLeft
  18139. && this._cache.orthoRight === this.orthoRight
  18140. && this._cache.orthoBottom === this.orthoBottom
  18141. && this._cache.orthoTop === this.orthoTop
  18142. && this._cache.renderWidth === engine.getRenderWidth()
  18143. && this._cache.renderHeight === engine.getRenderHeight();
  18144. }
  18145. return check;
  18146. };
  18147. // Controls
  18148. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18149. };
  18150. Camera.prototype.detachControl = function (element) {
  18151. };
  18152. Camera.prototype.update = function () {
  18153. this._checkInputs();
  18154. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18155. this._updateRigCameras();
  18156. }
  18157. };
  18158. Camera.prototype._checkInputs = function () {
  18159. this.onAfterCheckInputsObservable.notifyObservers(this);
  18160. };
  18161. Object.defineProperty(Camera.prototype, "rigCameras", {
  18162. get: function () {
  18163. return this._rigCameras;
  18164. },
  18165. enumerable: true,
  18166. configurable: true
  18167. });
  18168. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18169. get: function () {
  18170. return this._rigPostProcess;
  18171. },
  18172. enumerable: true,
  18173. configurable: true
  18174. });
  18175. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18176. // invalidate framebuffer
  18177. if (this._postProcesses.length > 0) {
  18178. this._postProcesses[0].markTextureDirty();
  18179. }
  18180. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18181. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18182. var cam = this._rigCameras[i];
  18183. var rigPostProcess = cam._rigPostProcess;
  18184. // for VR rig, there does not have to be a post process
  18185. if (rigPostProcess) {
  18186. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18187. if (isPass) {
  18188. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18189. cam.isIntermediate = this._postProcesses.length === 0;
  18190. }
  18191. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18192. rigPostProcess.markTextureDirty();
  18193. }
  18194. else {
  18195. cam._postProcesses = this._postProcesses.slice(0);
  18196. }
  18197. }
  18198. };
  18199. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18200. if (insertAt === void 0) { insertAt = null; }
  18201. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18202. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18203. return 0;
  18204. }
  18205. if (insertAt == null || insertAt < 0) {
  18206. this._postProcesses.push(postProcess);
  18207. }
  18208. else {
  18209. this._postProcesses.splice(insertAt, 0, postProcess);
  18210. }
  18211. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18212. return this._postProcesses.indexOf(postProcess);
  18213. };
  18214. Camera.prototype.detachPostProcess = function (postProcess) {
  18215. var idx = this._postProcesses.indexOf(postProcess);
  18216. if (idx !== -1) {
  18217. this._postProcesses.splice(idx, 1);
  18218. }
  18219. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18220. };
  18221. Camera.prototype.getWorldMatrix = function () {
  18222. if (!this._worldMatrix) {
  18223. this._worldMatrix = BABYLON.Matrix.Identity();
  18224. }
  18225. var viewMatrix = this.getViewMatrix();
  18226. viewMatrix.invertToRef(this._worldMatrix);
  18227. return this._worldMatrix;
  18228. };
  18229. Camera.prototype._getViewMatrix = function () {
  18230. return BABYLON.Matrix.Identity();
  18231. };
  18232. Camera.prototype.getViewMatrix = function (force) {
  18233. if (!force && this._isSynchronizedViewMatrix()) {
  18234. return this._computedViewMatrix;
  18235. }
  18236. this.updateCache();
  18237. this._computedViewMatrix = this._getViewMatrix();
  18238. this._currentRenderId = this.getScene().getRenderId();
  18239. this._refreshFrustumPlanes = true;
  18240. if (!this.parent || !this.parent.getWorldMatrix) {
  18241. this._globalPosition.copyFrom(this.position);
  18242. }
  18243. else {
  18244. if (!this._worldMatrix) {
  18245. this._worldMatrix = BABYLON.Matrix.Identity();
  18246. }
  18247. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18248. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18249. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18250. this._computedViewMatrix.invert();
  18251. this._markSyncedWithParent();
  18252. }
  18253. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18254. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18255. }
  18256. this.onViewMatrixChangedObservable.notifyObservers(this);
  18257. return this._computedViewMatrix;
  18258. };
  18259. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18260. this._doNotComputeProjectionMatrix = true;
  18261. if (projection !== undefined) {
  18262. this._projectionMatrix = projection;
  18263. }
  18264. };
  18265. ;
  18266. Camera.prototype.unfreezeProjectionMatrix = function () {
  18267. this._doNotComputeProjectionMatrix = false;
  18268. };
  18269. ;
  18270. Camera.prototype.getProjectionMatrix = function (force) {
  18271. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18272. return this._projectionMatrix;
  18273. }
  18274. // Cache
  18275. this._cache.mode = this.mode;
  18276. this._cache.minZ = this.minZ;
  18277. this._cache.maxZ = this.maxZ;
  18278. // Matrix
  18279. this._refreshFrustumPlanes = true;
  18280. var engine = this.getEngine();
  18281. var scene = this.getScene();
  18282. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18283. this._cache.fov = this.fov;
  18284. this._cache.fovMode = this.fovMode;
  18285. this._cache.aspectRatio = engine.getAspectRatio(this);
  18286. if (this.minZ <= 0) {
  18287. this.minZ = 0.1;
  18288. }
  18289. if (scene.useRightHandedSystem) {
  18290. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18291. }
  18292. else {
  18293. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18294. }
  18295. }
  18296. else {
  18297. var halfWidth = engine.getRenderWidth() / 2.0;
  18298. var halfHeight = engine.getRenderHeight() / 2.0;
  18299. if (scene.useRightHandedSystem) {
  18300. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18301. }
  18302. else {
  18303. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18304. }
  18305. this._cache.orthoLeft = this.orthoLeft;
  18306. this._cache.orthoRight = this.orthoRight;
  18307. this._cache.orthoBottom = this.orthoBottom;
  18308. this._cache.orthoTop = this.orthoTop;
  18309. this._cache.renderWidth = engine.getRenderWidth();
  18310. this._cache.renderHeight = engine.getRenderHeight();
  18311. }
  18312. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18313. return this._projectionMatrix;
  18314. };
  18315. Camera.prototype.getTranformationMatrix = function () {
  18316. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18317. return this._transformMatrix;
  18318. };
  18319. Camera.prototype.updateFrustumPlanes = function () {
  18320. if (!this._refreshFrustumPlanes) {
  18321. return;
  18322. }
  18323. this.getTranformationMatrix();
  18324. if (!this._frustumPlanes) {
  18325. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18326. }
  18327. else {
  18328. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18329. }
  18330. this._refreshFrustumPlanes = false;
  18331. };
  18332. Camera.prototype.isInFrustum = function (target) {
  18333. this.updateFrustumPlanes();
  18334. return target.isInFrustum(this._frustumPlanes);
  18335. };
  18336. Camera.prototype.isCompletelyInFrustum = function (target) {
  18337. this.updateFrustumPlanes();
  18338. return target.isCompletelyInFrustum(this._frustumPlanes);
  18339. };
  18340. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18341. if (length === void 0) { length = 100; }
  18342. if (!transform) {
  18343. transform = this.getWorldMatrix();
  18344. }
  18345. if (!origin) {
  18346. origin = this.position;
  18347. }
  18348. var forward = new BABYLON.Vector3(0, 0, 1);
  18349. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18350. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18351. return new BABYLON.Ray(origin, direction, length);
  18352. };
  18353. Camera.prototype.dispose = function () {
  18354. // Observables
  18355. this.onViewMatrixChangedObservable.clear();
  18356. this.onProjectionMatrixChangedObservable.clear();
  18357. this.onAfterCheckInputsObservable.clear();
  18358. this.onRestoreStateObservable.clear();
  18359. // Inputs
  18360. if (this.inputs) {
  18361. this.inputs.clear();
  18362. }
  18363. // Animations
  18364. this.getScene().stopAnimation(this);
  18365. // Remove from scene
  18366. this.getScene().removeCamera(this);
  18367. while (this._rigCameras.length > 0) {
  18368. var camera = this._rigCameras.pop();
  18369. if (camera) {
  18370. camera.dispose();
  18371. }
  18372. }
  18373. // Postprocesses
  18374. if (this._rigPostProcess) {
  18375. this._rigPostProcess.dispose(this);
  18376. this._rigPostProcess = null;
  18377. this._postProcesses = [];
  18378. }
  18379. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18380. this._rigPostProcess = null;
  18381. this._postProcesses = [];
  18382. }
  18383. else {
  18384. var i = this._postProcesses.length;
  18385. while (--i >= 0) {
  18386. this._postProcesses[i].dispose(this);
  18387. }
  18388. }
  18389. // Render targets
  18390. var i = this.customRenderTargets.length;
  18391. while (--i >= 0) {
  18392. this.customRenderTargets[i].dispose();
  18393. }
  18394. this.customRenderTargets = [];
  18395. // Active Meshes
  18396. this._activeMeshes.dispose();
  18397. _super.prototype.dispose.call(this);
  18398. };
  18399. Object.defineProperty(Camera.prototype, "leftCamera", {
  18400. // ---- Camera rigs section ----
  18401. get: function () {
  18402. if (this._rigCameras.length < 1) {
  18403. return null;
  18404. }
  18405. return this._rigCameras[0];
  18406. },
  18407. enumerable: true,
  18408. configurable: true
  18409. });
  18410. Object.defineProperty(Camera.prototype, "rightCamera", {
  18411. get: function () {
  18412. if (this._rigCameras.length < 2) {
  18413. return null;
  18414. }
  18415. return this._rigCameras[1];
  18416. },
  18417. enumerable: true,
  18418. configurable: true
  18419. });
  18420. Camera.prototype.getLeftTarget = function () {
  18421. if (this._rigCameras.length < 1) {
  18422. return null;
  18423. }
  18424. return this._rigCameras[0].getTarget();
  18425. };
  18426. Camera.prototype.getRightTarget = function () {
  18427. if (this._rigCameras.length < 2) {
  18428. return null;
  18429. }
  18430. return this._rigCameras[1].getTarget();
  18431. };
  18432. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18433. if (this.cameraRigMode === mode) {
  18434. return;
  18435. }
  18436. while (this._rigCameras.length > 0) {
  18437. var camera = this._rigCameras.pop();
  18438. if (camera) {
  18439. camera.dispose();
  18440. }
  18441. }
  18442. this.cameraRigMode = mode;
  18443. this._cameraRigParams = {};
  18444. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18445. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18446. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18447. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18448. // create the rig cameras, unless none
  18449. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18450. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18451. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18452. if (leftCamera && rightCamera) {
  18453. this._rigCameras.push(leftCamera);
  18454. this._rigCameras.push(rightCamera);
  18455. }
  18456. }
  18457. switch (this.cameraRigMode) {
  18458. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18459. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18460. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18461. break;
  18462. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18463. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18464. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18465. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18466. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18467. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18468. break;
  18469. case Camera.RIG_MODE_VR:
  18470. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18471. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18472. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18473. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18474. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18475. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18476. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18477. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18478. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18479. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18480. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18481. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18482. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18483. if (metrics.compensateDistortion) {
  18484. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18485. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18486. }
  18487. break;
  18488. case Camera.RIG_MODE_WEBVR:
  18489. if (rigParams.vrDisplay) {
  18490. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18491. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18492. //Left eye
  18493. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18494. this._rigCameras[0].setCameraRigParameter("left", true);
  18495. //leaving this for future reference
  18496. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18497. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18498. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18499. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18500. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18501. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18502. this._rigCameras[0].parent = this;
  18503. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18504. //Right eye
  18505. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18506. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18507. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18508. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18509. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18510. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18511. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18512. this._rigCameras[1].parent = this;
  18513. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18514. if (Camera.UseAlternateWebVRRendering) {
  18515. this._rigCameras[1]._skipRendering = true;
  18516. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18517. }
  18518. }
  18519. break;
  18520. }
  18521. this._cascadePostProcessesToRigCams();
  18522. this.update();
  18523. };
  18524. Camera.prototype._getVRProjectionMatrix = function () {
  18525. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18526. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18527. return this._projectionMatrix;
  18528. };
  18529. Camera.prototype._updateCameraRotationMatrix = function () {
  18530. //Here for WebVR
  18531. };
  18532. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18533. //Here for WebVR
  18534. };
  18535. /**
  18536. * This function MUST be overwritten by the different WebVR cameras available.
  18537. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18538. */
  18539. Camera.prototype._getWebVRProjectionMatrix = function () {
  18540. return BABYLON.Matrix.Identity();
  18541. };
  18542. /**
  18543. * This function MUST be overwritten by the different WebVR cameras available.
  18544. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18545. */
  18546. Camera.prototype._getWebVRViewMatrix = function () {
  18547. return BABYLON.Matrix.Identity();
  18548. };
  18549. Camera.prototype.setCameraRigParameter = function (name, value) {
  18550. if (!this._cameraRigParams) {
  18551. this._cameraRigParams = {};
  18552. }
  18553. this._cameraRigParams[name] = value;
  18554. //provisionnally:
  18555. if (name === "interaxialDistance") {
  18556. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18557. }
  18558. };
  18559. /**
  18560. * needs to be overridden by children so sub has required properties to be copied
  18561. */
  18562. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18563. return null;
  18564. };
  18565. /**
  18566. * May need to be overridden by children
  18567. */
  18568. Camera.prototype._updateRigCameras = function () {
  18569. for (var i = 0; i < this._rigCameras.length; i++) {
  18570. this._rigCameras[i].minZ = this.minZ;
  18571. this._rigCameras[i].maxZ = this.maxZ;
  18572. this._rigCameras[i].fov = this.fov;
  18573. }
  18574. // only update viewport when ANAGLYPH
  18575. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18576. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18577. }
  18578. };
  18579. Camera.prototype._setupInputs = function () {
  18580. };
  18581. Camera.prototype.serialize = function () {
  18582. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18583. // Type
  18584. serializationObject.type = this.getClassName();
  18585. // Parent
  18586. if (this.parent) {
  18587. serializationObject.parentId = this.parent.id;
  18588. }
  18589. if (this.inputs) {
  18590. this.inputs.serialize(serializationObject);
  18591. }
  18592. // Animations
  18593. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18594. serializationObject.ranges = this.serializeAnimationRanges();
  18595. return serializationObject;
  18596. };
  18597. Camera.prototype.clone = function (name) {
  18598. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18599. };
  18600. Camera.prototype.getDirection = function (localAxis) {
  18601. var result = BABYLON.Vector3.Zero();
  18602. this.getDirectionToRef(localAxis, result);
  18603. return result;
  18604. };
  18605. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18606. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18607. };
  18608. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18609. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18610. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18611. switch (type) {
  18612. case "ArcRotateCamera":
  18613. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18614. case "DeviceOrientationCamera":
  18615. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18616. case "FollowCamera":
  18617. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18618. case "ArcFollowCamera":
  18619. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18620. case "GamepadCamera":
  18621. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18622. case "TouchCamera":
  18623. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18624. case "VirtualJoysticksCamera":
  18625. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18626. case "WebVRFreeCamera":
  18627. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18628. case "WebVRGamepadCamera":
  18629. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18630. case "VRDeviceOrientationFreeCamera":
  18631. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18632. case "VRDeviceOrientationGamepadCamera":
  18633. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18634. case "AnaglyphArcRotateCamera":
  18635. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18636. case "AnaglyphFreeCamera":
  18637. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18638. case "AnaglyphGamepadCamera":
  18639. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18640. case "AnaglyphUniversalCamera":
  18641. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18642. case "StereoscopicArcRotateCamera":
  18643. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18644. case "StereoscopicFreeCamera":
  18645. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18646. case "StereoscopicGamepadCamera":
  18647. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18648. case "StereoscopicUniversalCamera":
  18649. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18650. case "FreeCamera":// Forcing Universal here
  18651. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18652. default:// Universal Camera is the default value
  18653. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18654. }
  18655. };
  18656. Camera.prototype.computeWorldMatrix = function () {
  18657. return this.getWorldMatrix();
  18658. };
  18659. Camera.Parse = function (parsedCamera, scene) {
  18660. var type = parsedCamera.type;
  18661. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18662. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18663. // Parent
  18664. if (parsedCamera.parentId) {
  18665. camera._waitingParentId = parsedCamera.parentId;
  18666. }
  18667. //If camera has an input manager, let it parse inputs settings
  18668. if (camera.inputs) {
  18669. camera.inputs.parse(parsedCamera);
  18670. camera._setupInputs();
  18671. }
  18672. if (camera.setPosition) {
  18673. camera.position.copyFromFloats(0, 0, 0);
  18674. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18675. }
  18676. // Target
  18677. if (parsedCamera.target) {
  18678. if (camera.setTarget) {
  18679. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18680. }
  18681. }
  18682. // Apply 3d rig, when found
  18683. if (parsedCamera.cameraRigMode) {
  18684. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18685. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18686. }
  18687. // Animations
  18688. if (parsedCamera.animations) {
  18689. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18690. var parsedAnimation = parsedCamera.animations[animationIndex];
  18691. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18692. }
  18693. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18694. }
  18695. if (parsedCamera.autoAnimate) {
  18696. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18697. }
  18698. return camera;
  18699. };
  18700. // Statics
  18701. Camera._PERSPECTIVE_CAMERA = 0;
  18702. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18703. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18704. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18705. Camera._RIG_MODE_NONE = 0;
  18706. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18707. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18708. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18709. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18710. Camera._RIG_MODE_VR = 20;
  18711. Camera._RIG_MODE_WEBVR = 21;
  18712. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18713. Camera.UseAlternateWebVRRendering = false;
  18714. __decorate([
  18715. BABYLON.serializeAsVector3()
  18716. ], Camera.prototype, "position", void 0);
  18717. __decorate([
  18718. BABYLON.serializeAsVector3()
  18719. ], Camera.prototype, "upVector", void 0);
  18720. __decorate([
  18721. BABYLON.serialize()
  18722. ], Camera.prototype, "orthoLeft", void 0);
  18723. __decorate([
  18724. BABYLON.serialize()
  18725. ], Camera.prototype, "orthoRight", void 0);
  18726. __decorate([
  18727. BABYLON.serialize()
  18728. ], Camera.prototype, "orthoBottom", void 0);
  18729. __decorate([
  18730. BABYLON.serialize()
  18731. ], Camera.prototype, "orthoTop", void 0);
  18732. __decorate([
  18733. BABYLON.serialize()
  18734. ], Camera.prototype, "fov", void 0);
  18735. __decorate([
  18736. BABYLON.serialize()
  18737. ], Camera.prototype, "minZ", void 0);
  18738. __decorate([
  18739. BABYLON.serialize()
  18740. ], Camera.prototype, "maxZ", void 0);
  18741. __decorate([
  18742. BABYLON.serialize()
  18743. ], Camera.prototype, "inertia", void 0);
  18744. __decorate([
  18745. BABYLON.serialize()
  18746. ], Camera.prototype, "mode", void 0);
  18747. __decorate([
  18748. BABYLON.serialize()
  18749. ], Camera.prototype, "layerMask", void 0);
  18750. __decorate([
  18751. BABYLON.serialize()
  18752. ], Camera.prototype, "fovMode", void 0);
  18753. __decorate([
  18754. BABYLON.serialize()
  18755. ], Camera.prototype, "cameraRigMode", void 0);
  18756. __decorate([
  18757. BABYLON.serialize()
  18758. ], Camera.prototype, "interaxialDistance", void 0);
  18759. __decorate([
  18760. BABYLON.serialize()
  18761. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18762. return Camera;
  18763. }(BABYLON.Node));
  18764. BABYLON.Camera = Camera;
  18765. })(BABYLON || (BABYLON = {}));
  18766. //# sourceMappingURL=babylon.camera.js.map
  18767. var BABYLON;
  18768. (function (BABYLON) {
  18769. var RenderingManager = /** @class */ (function () {
  18770. function RenderingManager(scene) {
  18771. this._renderingGroups = new Array();
  18772. this._autoClearDepthStencil = {};
  18773. this._customOpaqueSortCompareFn = {};
  18774. this._customAlphaTestSortCompareFn = {};
  18775. this._customTransparentSortCompareFn = {};
  18776. this._renderinGroupInfo = null;
  18777. this._scene = scene;
  18778. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18779. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18780. }
  18781. }
  18782. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18783. if (depth === void 0) { depth = true; }
  18784. if (stencil === void 0) { stencil = true; }
  18785. if (this._depthStencilBufferAlreadyCleaned) {
  18786. return;
  18787. }
  18788. this._scene.getEngine().clear(null, false, depth, stencil);
  18789. this._depthStencilBufferAlreadyCleaned = true;
  18790. };
  18791. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18792. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18793. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18794. var info = null;
  18795. if (observable) {
  18796. if (!this._renderinGroupInfo) {
  18797. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18798. }
  18799. info = this._renderinGroupInfo;
  18800. info.scene = this._scene;
  18801. info.camera = this._scene.activeCamera;
  18802. }
  18803. // Dispatch sprites
  18804. if (renderSprites) {
  18805. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18806. var manager = this._scene.spriteManagers[index];
  18807. this.dispatchSprites(manager);
  18808. }
  18809. }
  18810. // Render
  18811. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18812. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18813. var renderingGroup = this._renderingGroups[index];
  18814. if (!renderingGroup && !observable)
  18815. continue;
  18816. var renderingGroupMask = 0;
  18817. // Fire PRECLEAR stage
  18818. if (observable && info) {
  18819. renderingGroupMask = Math.pow(2, index);
  18820. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18821. info.renderingGroupId = index;
  18822. observable.notifyObservers(info, renderingGroupMask);
  18823. }
  18824. // Clear depth/stencil if needed
  18825. if (RenderingManager.AUTOCLEAR) {
  18826. var autoClear = this._autoClearDepthStencil[index];
  18827. if (autoClear && autoClear.autoClear) {
  18828. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18829. }
  18830. }
  18831. if (observable && info) {
  18832. // Fire PREOPAQUE stage
  18833. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18834. observable.notifyObservers(info, renderingGroupMask);
  18835. // Fire PRETRANSPARENT stage
  18836. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18837. observable.notifyObservers(info, renderingGroupMask);
  18838. }
  18839. if (renderingGroup)
  18840. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18841. // Fire POSTTRANSPARENT stage
  18842. if (observable && info) {
  18843. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18844. observable.notifyObservers(info, renderingGroupMask);
  18845. }
  18846. }
  18847. };
  18848. RenderingManager.prototype.reset = function () {
  18849. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18850. var renderingGroup = this._renderingGroups[index];
  18851. if (renderingGroup) {
  18852. renderingGroup.prepare();
  18853. }
  18854. }
  18855. };
  18856. RenderingManager.prototype.dispose = function () {
  18857. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18858. var renderingGroup = this._renderingGroups[index];
  18859. if (renderingGroup) {
  18860. renderingGroup.dispose();
  18861. }
  18862. }
  18863. this._renderingGroups.length = 0;
  18864. };
  18865. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18866. if (this._renderingGroups[renderingGroupId] === undefined) {
  18867. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18868. }
  18869. };
  18870. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18871. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18872. this._prepareRenderingGroup(renderingGroupId);
  18873. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18874. };
  18875. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18876. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18877. this._prepareRenderingGroup(renderingGroupId);
  18878. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18879. };
  18880. /**
  18881. * @param subMesh The submesh to dispatch
  18882. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18883. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18884. */
  18885. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18886. if (mesh === undefined) {
  18887. mesh = subMesh.getMesh();
  18888. }
  18889. var renderingGroupId = mesh.renderingGroupId || 0;
  18890. this._prepareRenderingGroup(renderingGroupId);
  18891. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18892. };
  18893. /**
  18894. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18895. * This allowed control for front to back rendering or reversly depending of the special needs.
  18896. *
  18897. * @param renderingGroupId The rendering group id corresponding to its index
  18898. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18899. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18900. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18901. */
  18902. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18903. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18904. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18905. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18906. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18907. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18908. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18909. if (this._renderingGroups[renderingGroupId]) {
  18910. var group = this._renderingGroups[renderingGroupId];
  18911. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18912. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18913. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18914. }
  18915. };
  18916. /**
  18917. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18918. *
  18919. * @param renderingGroupId The rendering group id corresponding to its index
  18920. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18921. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18922. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18923. */
  18924. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18925. if (depth === void 0) { depth = true; }
  18926. if (stencil === void 0) { stencil = true; }
  18927. this._autoClearDepthStencil[renderingGroupId] = {
  18928. autoClear: autoClearDepthStencil,
  18929. depth: depth,
  18930. stencil: stencil
  18931. };
  18932. };
  18933. /**
  18934. * The max id used for rendering groups (not included)
  18935. */
  18936. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18937. /**
  18938. * The min id used for rendering groups (included)
  18939. */
  18940. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18941. /**
  18942. * Used to globally prevent autoclearing scenes.
  18943. */
  18944. RenderingManager.AUTOCLEAR = true;
  18945. return RenderingManager;
  18946. }());
  18947. BABYLON.RenderingManager = RenderingManager;
  18948. })(BABYLON || (BABYLON = {}));
  18949. //# sourceMappingURL=babylon.renderingManager.js.map
  18950. var BABYLON;
  18951. (function (BABYLON) {
  18952. var RenderingGroup = /** @class */ (function () {
  18953. /**
  18954. * Creates a new rendering group.
  18955. * @param index The rendering group index
  18956. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18957. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18958. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18959. */
  18960. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18961. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18962. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18963. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18964. this.index = index;
  18965. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18966. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18967. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18968. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18969. this._particleSystems = new BABYLON.SmartArray(256);
  18970. this._spriteManagers = new BABYLON.SmartArray(256);
  18971. this._edgesRenderers = new BABYLON.SmartArray(16);
  18972. this._scene = scene;
  18973. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18974. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18975. this.transparentSortCompareFn = transparentSortCompareFn;
  18976. }
  18977. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18978. /**
  18979. * Set the opaque sort comparison function.
  18980. * If null the sub meshes will be render in the order they were created
  18981. */
  18982. set: function (value) {
  18983. this._opaqueSortCompareFn = value;
  18984. if (value) {
  18985. this._renderOpaque = this.renderOpaqueSorted;
  18986. }
  18987. else {
  18988. this._renderOpaque = RenderingGroup.renderUnsorted;
  18989. }
  18990. },
  18991. enumerable: true,
  18992. configurable: true
  18993. });
  18994. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18995. /**
  18996. * Set the alpha test sort comparison function.
  18997. * If null the sub meshes will be render in the order they were created
  18998. */
  18999. set: function (value) {
  19000. this._alphaTestSortCompareFn = value;
  19001. if (value) {
  19002. this._renderAlphaTest = this.renderAlphaTestSorted;
  19003. }
  19004. else {
  19005. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19006. }
  19007. },
  19008. enumerable: true,
  19009. configurable: true
  19010. });
  19011. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19012. /**
  19013. * Set the transparent sort comparison function.
  19014. * If null the sub meshes will be render in the order they were created
  19015. */
  19016. set: function (value) {
  19017. if (value) {
  19018. this._transparentSortCompareFn = value;
  19019. }
  19020. else {
  19021. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19022. }
  19023. this._renderTransparent = this.renderTransparentSorted;
  19024. },
  19025. enumerable: true,
  19026. configurable: true
  19027. });
  19028. /**
  19029. * Render all the sub meshes contained in the group.
  19030. * @param customRenderFunction Used to override the default render behaviour of the group.
  19031. * @returns true if rendered some submeshes.
  19032. */
  19033. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19034. if (customRenderFunction) {
  19035. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19036. return;
  19037. }
  19038. var engine = this._scene.getEngine();
  19039. // Depth only
  19040. if (this._depthOnlySubMeshes.length !== 0) {
  19041. engine.setColorWrite(false);
  19042. this._renderAlphaTest(this._depthOnlySubMeshes);
  19043. engine.setColorWrite(true);
  19044. }
  19045. // Opaque
  19046. if (this._opaqueSubMeshes.length !== 0) {
  19047. this._renderOpaque(this._opaqueSubMeshes);
  19048. }
  19049. // Alpha test
  19050. if (this._alphaTestSubMeshes.length !== 0) {
  19051. this._renderAlphaTest(this._alphaTestSubMeshes);
  19052. }
  19053. var stencilState = engine.getStencilBuffer();
  19054. engine.setStencilBuffer(false);
  19055. // Sprites
  19056. if (renderSprites) {
  19057. this._renderSprites();
  19058. }
  19059. // Particles
  19060. if (renderParticles) {
  19061. this._renderParticles(activeMeshes);
  19062. }
  19063. if (this.onBeforeTransparentRendering) {
  19064. this.onBeforeTransparentRendering();
  19065. }
  19066. // Transparent
  19067. if (this._transparentSubMeshes.length !== 0) {
  19068. this._renderTransparent(this._transparentSubMeshes);
  19069. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19070. }
  19071. // Set back stencil to false in case it changes before the edge renderer.
  19072. engine.setStencilBuffer(false);
  19073. // Edges
  19074. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19075. this._edgesRenderers.data[edgesRendererIndex].render();
  19076. }
  19077. // Restore Stencil state.
  19078. engine.setStencilBuffer(stencilState);
  19079. };
  19080. /**
  19081. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19082. * @param subMeshes The submeshes to render
  19083. */
  19084. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19085. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19086. };
  19087. /**
  19088. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19089. * @param subMeshes The submeshes to render
  19090. */
  19091. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19092. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19093. };
  19094. /**
  19095. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19096. * @param subMeshes The submeshes to render
  19097. */
  19098. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19099. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19100. };
  19101. /**
  19102. * Renders the submeshes in a specified order.
  19103. * @param subMeshes The submeshes to sort before render
  19104. * @param sortCompareFn The comparison function use to sort
  19105. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19106. * @param transparent Specifies to activate blending if true
  19107. */
  19108. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19109. var subIndex = 0;
  19110. var subMesh;
  19111. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19112. for (; subIndex < subMeshes.length; subIndex++) {
  19113. subMesh = subMeshes.data[subIndex];
  19114. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19115. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19116. }
  19117. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19118. if (sortCompareFn) {
  19119. sortedArray.sort(sortCompareFn);
  19120. }
  19121. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19122. subMesh = sortedArray[subIndex];
  19123. if (transparent) {
  19124. var material = subMesh.getMaterial();
  19125. if (material && material.needDepthPrePass) {
  19126. var engine = material.getScene().getEngine();
  19127. engine.setColorWrite(false);
  19128. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19129. subMesh.render(false);
  19130. engine.setColorWrite(true);
  19131. }
  19132. }
  19133. subMesh.render(transparent);
  19134. }
  19135. };
  19136. /**
  19137. * Renders the submeshes in the order they were dispatched (no sort applied).
  19138. * @param subMeshes The submeshes to render
  19139. */
  19140. RenderingGroup.renderUnsorted = function (subMeshes) {
  19141. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19142. var submesh = subMeshes.data[subIndex];
  19143. submesh.render(false);
  19144. }
  19145. };
  19146. /**
  19147. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19148. * are rendered back to front if in the same alpha index.
  19149. *
  19150. * @param a The first submesh
  19151. * @param b The second submesh
  19152. * @returns The result of the comparison
  19153. */
  19154. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19155. // Alpha index first
  19156. if (a._alphaIndex > b._alphaIndex) {
  19157. return 1;
  19158. }
  19159. if (a._alphaIndex < b._alphaIndex) {
  19160. return -1;
  19161. }
  19162. // Then distance to camera
  19163. return RenderingGroup.backToFrontSortCompare(a, b);
  19164. };
  19165. /**
  19166. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19167. * are rendered back to front.
  19168. *
  19169. * @param a The first submesh
  19170. * @param b The second submesh
  19171. * @returns The result of the comparison
  19172. */
  19173. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19174. // Then distance to camera
  19175. if (a._distanceToCamera < b._distanceToCamera) {
  19176. return 1;
  19177. }
  19178. if (a._distanceToCamera > b._distanceToCamera) {
  19179. return -1;
  19180. }
  19181. return 0;
  19182. };
  19183. /**
  19184. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19185. * are rendered front to back (prevent overdraw).
  19186. *
  19187. * @param a The first submesh
  19188. * @param b The second submesh
  19189. * @returns The result of the comparison
  19190. */
  19191. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19192. // Then distance to camera
  19193. if (a._distanceToCamera < b._distanceToCamera) {
  19194. return -1;
  19195. }
  19196. if (a._distanceToCamera > b._distanceToCamera) {
  19197. return 1;
  19198. }
  19199. return 0;
  19200. };
  19201. /**
  19202. * Resets the different lists of submeshes to prepare a new frame.
  19203. */
  19204. RenderingGroup.prototype.prepare = function () {
  19205. this._opaqueSubMeshes.reset();
  19206. this._transparentSubMeshes.reset();
  19207. this._alphaTestSubMeshes.reset();
  19208. this._depthOnlySubMeshes.reset();
  19209. this._particleSystems.reset();
  19210. this._spriteManagers.reset();
  19211. this._edgesRenderers.reset();
  19212. };
  19213. RenderingGroup.prototype.dispose = function () {
  19214. this._opaqueSubMeshes.dispose();
  19215. this._transparentSubMeshes.dispose();
  19216. this._alphaTestSubMeshes.dispose();
  19217. this._depthOnlySubMeshes.dispose();
  19218. this._particleSystems.dispose();
  19219. this._spriteManagers.dispose();
  19220. this._edgesRenderers.dispose();
  19221. };
  19222. /**
  19223. * Inserts the submesh in its correct queue depending on its material.
  19224. * @param subMesh The submesh to dispatch
  19225. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19226. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19227. */
  19228. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19229. // Get mesh and materials if not provided
  19230. if (mesh === undefined) {
  19231. mesh = subMesh.getMesh();
  19232. }
  19233. if (material === undefined) {
  19234. material = subMesh.getMaterial();
  19235. }
  19236. if (material === null || material === undefined) {
  19237. return;
  19238. }
  19239. if (material.needAlphaBlendingForMesh(mesh)) {
  19240. this._transparentSubMeshes.push(subMesh);
  19241. }
  19242. else if (material.needAlphaTesting()) {
  19243. if (material.needDepthPrePass) {
  19244. this._depthOnlySubMeshes.push(subMesh);
  19245. }
  19246. this._alphaTestSubMeshes.push(subMesh);
  19247. }
  19248. else {
  19249. if (material.needDepthPrePass) {
  19250. this._depthOnlySubMeshes.push(subMesh);
  19251. }
  19252. this._opaqueSubMeshes.push(subMesh); // Opaque
  19253. }
  19254. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19255. this._edgesRenderers.push(mesh._edgesRenderer);
  19256. }
  19257. };
  19258. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19259. this._spriteManagers.push(spriteManager);
  19260. };
  19261. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19262. this._particleSystems.push(particleSystem);
  19263. };
  19264. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19265. if (this._particleSystems.length === 0) {
  19266. return;
  19267. }
  19268. // Particles
  19269. var activeCamera = this._scene.activeCamera;
  19270. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19271. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19272. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19273. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19274. continue;
  19275. }
  19276. var emitter = particleSystem.emitter;
  19277. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19278. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19279. }
  19280. }
  19281. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19282. };
  19283. RenderingGroup.prototype._renderSprites = function () {
  19284. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19285. return;
  19286. }
  19287. // Sprites
  19288. var activeCamera = this._scene.activeCamera;
  19289. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19290. for (var id = 0; id < this._spriteManagers.length; id++) {
  19291. var spriteManager = this._spriteManagers.data[id];
  19292. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19293. spriteManager.render();
  19294. }
  19295. }
  19296. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19297. };
  19298. return RenderingGroup;
  19299. }());
  19300. BABYLON.RenderingGroup = RenderingGroup;
  19301. })(BABYLON || (BABYLON = {}));
  19302. //# sourceMappingURL=babylon.renderingGroup.js.map
  19303. var BABYLON;
  19304. (function (BABYLON) {
  19305. var ClickInfo = /** @class */ (function () {
  19306. function ClickInfo() {
  19307. this._singleClick = false;
  19308. this._doubleClick = false;
  19309. this._hasSwiped = false;
  19310. this._ignore = false;
  19311. }
  19312. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19313. get: function () {
  19314. return this._singleClick;
  19315. },
  19316. set: function (b) {
  19317. this._singleClick = b;
  19318. },
  19319. enumerable: true,
  19320. configurable: true
  19321. });
  19322. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19323. get: function () {
  19324. return this._doubleClick;
  19325. },
  19326. set: function (b) {
  19327. this._doubleClick = b;
  19328. },
  19329. enumerable: true,
  19330. configurable: true
  19331. });
  19332. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19333. get: function () {
  19334. return this._hasSwiped;
  19335. },
  19336. set: function (b) {
  19337. this._hasSwiped = b;
  19338. },
  19339. enumerable: true,
  19340. configurable: true
  19341. });
  19342. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19343. get: function () {
  19344. return this._ignore;
  19345. },
  19346. set: function (b) {
  19347. this._ignore = b;
  19348. },
  19349. enumerable: true,
  19350. configurable: true
  19351. });
  19352. return ClickInfo;
  19353. }());
  19354. /**
  19355. * This class is used by the onRenderingGroupObservable
  19356. */
  19357. var RenderingGroupInfo = /** @class */ (function () {
  19358. function RenderingGroupInfo() {
  19359. }
  19360. /**
  19361. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19362. * This stage will be fired no matter what
  19363. */
  19364. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19365. /**
  19366. * Called before opaque object are rendered.
  19367. * This stage will be fired only if there's 3D Opaque content to render
  19368. */
  19369. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19370. /**
  19371. * Called after the opaque objects are rendered and before the transparent ones
  19372. * This stage will be fired only if there's 3D transparent content to render
  19373. */
  19374. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19375. /**
  19376. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19377. * This stage will be fired no matter what
  19378. */
  19379. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19380. return RenderingGroupInfo;
  19381. }());
  19382. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19383. /**
  19384. * Represents a scene to be rendered by the engine.
  19385. * @see http://doc.babylonjs.com/page.php?p=21911
  19386. */
  19387. var Scene = /** @class */ (function () {
  19388. /**
  19389. * @constructor
  19390. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19391. */
  19392. function Scene(engine) {
  19393. // Members
  19394. this.autoClear = true;
  19395. this.autoClearDepthAndStencil = true;
  19396. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19397. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19398. this.forceWireframe = false;
  19399. this._forcePointsCloud = false;
  19400. this.forceShowBoundingBoxes = false;
  19401. this.animationsEnabled = true;
  19402. this.useConstantAnimationDeltaTime = false;
  19403. this.constantlyUpdateMeshUnderPointer = false;
  19404. this.hoverCursor = "pointer";
  19405. this.defaultCursor = "";
  19406. /**
  19407. * This is used to call preventDefault() on pointer down
  19408. * in order to block unwanted artifacts like system double clicks
  19409. */
  19410. this.preventDefaultOnPointerDown = true;
  19411. // Metadata
  19412. this.metadata = null;
  19413. /**
  19414. * An event triggered when the scene is disposed.
  19415. * @type {BABYLON.Observable}
  19416. */
  19417. this.onDisposeObservable = new BABYLON.Observable();
  19418. /**
  19419. * An event triggered before rendering the scene (right after animations and physics)
  19420. * @type {BABYLON.Observable}
  19421. */
  19422. this.onBeforeRenderObservable = new BABYLON.Observable();
  19423. /**
  19424. * An event triggered after rendering the scene
  19425. * @type {BABYLON.Observable}
  19426. */
  19427. this.onAfterRenderObservable = new BABYLON.Observable();
  19428. /**
  19429. * An event triggered before animating the scene
  19430. * @type {BABYLON.Observable}
  19431. */
  19432. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19433. /**
  19434. * An event triggered after animations processing
  19435. * @type {BABYLON.Observable}
  19436. */
  19437. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19438. /**
  19439. * An event triggered before draw calls are ready to be sent
  19440. * @type {BABYLON.Observable}
  19441. */
  19442. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19443. /**
  19444. * An event triggered after draw calls have been sent
  19445. * @type {BABYLON.Observable}
  19446. */
  19447. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19448. /**
  19449. * An event triggered when physic simulation is about to be run
  19450. * @type {BABYLON.Observable}
  19451. */
  19452. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19453. /**
  19454. * An event triggered when physic simulation has been done
  19455. * @type {BABYLON.Observable}
  19456. */
  19457. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19458. /**
  19459. * An event triggered when the scene is ready
  19460. * @type {BABYLON.Observable}
  19461. */
  19462. this.onReadyObservable = new BABYLON.Observable();
  19463. /**
  19464. * An event triggered before rendering a camera
  19465. * @type {BABYLON.Observable}
  19466. */
  19467. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19468. /**
  19469. * An event triggered after rendering a camera
  19470. * @type {BABYLON.Observable}
  19471. */
  19472. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19473. /**
  19474. * An event triggered when active meshes evaluation is about to start
  19475. * @type {BABYLON.Observable}
  19476. */
  19477. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19478. /**
  19479. * An event triggered when active meshes evaluation is done
  19480. * @type {BABYLON.Observable}
  19481. */
  19482. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19483. /**
  19484. * An event triggered when particles rendering is about to start
  19485. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19486. * @type {BABYLON.Observable}
  19487. */
  19488. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19489. /**
  19490. * An event triggered when particles rendering is done
  19491. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19492. * @type {BABYLON.Observable}
  19493. */
  19494. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19495. /**
  19496. * An event triggered when sprites rendering is about to start
  19497. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19498. * @type {BABYLON.Observable}
  19499. */
  19500. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19501. /**
  19502. * An event triggered when sprites rendering is done
  19503. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19504. * @type {BABYLON.Observable}
  19505. */
  19506. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19507. /**
  19508. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19509. * @type {BABYLON.Observable}
  19510. */
  19511. this.onDataLoadedObservable = new BABYLON.Observable();
  19512. /**
  19513. * An event triggered when a camera is created
  19514. * @type {BABYLON.Observable}
  19515. */
  19516. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19517. /**
  19518. * An event triggered when a camera is removed
  19519. * @type {BABYLON.Observable}
  19520. */
  19521. this.onCameraRemovedObservable = new BABYLON.Observable();
  19522. /**
  19523. * An event triggered when a light is created
  19524. * @type {BABYLON.Observable}
  19525. */
  19526. this.onNewLightAddedObservable = new BABYLON.Observable();
  19527. /**
  19528. * An event triggered when a light is removed
  19529. * @type {BABYLON.Observable}
  19530. */
  19531. this.onLightRemovedObservable = new BABYLON.Observable();
  19532. /**
  19533. * An event triggered when a geometry is created
  19534. * @type {BABYLON.Observable}
  19535. */
  19536. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19537. /**
  19538. * An event triggered when a geometry is removed
  19539. * @type {BABYLON.Observable}
  19540. */
  19541. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19542. /**
  19543. * An event triggered when a transform node is created
  19544. * @type {BABYLON.Observable}
  19545. */
  19546. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19547. /**
  19548. * An event triggered when a transform node is removed
  19549. * @type {BABYLON.Observable}
  19550. */
  19551. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19552. /**
  19553. * An event triggered when a mesh is created
  19554. * @type {BABYLON.Observable}
  19555. */
  19556. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19557. /**
  19558. * An event triggered when a mesh is removed
  19559. * @type {BABYLON.Observable}
  19560. */
  19561. this.onMeshRemovedObservable = new BABYLON.Observable();
  19562. /**
  19563. * An event triggered when render targets are about to be rendered
  19564. * Can happen multiple times per frame.
  19565. * @type {BABYLON.Observable}
  19566. */
  19567. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19568. /**
  19569. * An event triggered when render targets were rendered.
  19570. * Can happen multiple times per frame.
  19571. * @type {BABYLON.Observable}
  19572. */
  19573. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19574. /**
  19575. * An event triggered before calculating deterministic simulation step
  19576. * @type {BABYLON.Observable}
  19577. */
  19578. this.onBeforeStepObservable = new BABYLON.Observable();
  19579. /**
  19580. * An event triggered after calculating deterministic simulation step
  19581. * @type {BABYLON.Observable}
  19582. */
  19583. this.onAfterStepObservable = new BABYLON.Observable();
  19584. /**
  19585. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19586. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19587. * 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)
  19588. */
  19589. this.onRenderingGroupObservable = new BABYLON.Observable();
  19590. // Animations
  19591. this.animations = [];
  19592. /**
  19593. * 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).
  19594. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19595. */
  19596. this.onPrePointerObservable = new BABYLON.Observable();
  19597. /**
  19598. * Observable event triggered each time an input event is received from the rendering canvas
  19599. */
  19600. this.onPointerObservable = new BABYLON.Observable();
  19601. this._meshPickProceed = false;
  19602. this._currentPickResult = null;
  19603. this._previousPickResult = null;
  19604. this._totalPointersPressed = 0;
  19605. this._doubleClickOccured = false;
  19606. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19607. this.cameraToUseForPointers = null;
  19608. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19609. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19610. this._startingPointerTime = 0;
  19611. this._previousStartingPointerTime = 0;
  19612. // Deterministic lockstep
  19613. this._timeAccumulator = 0;
  19614. this._currentStepId = 0;
  19615. this._currentInternalStep = 0;
  19616. // Keyboard
  19617. /**
  19618. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19619. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19620. */
  19621. this.onPreKeyboardObservable = new BABYLON.Observable();
  19622. /**
  19623. * Observable event triggered each time an keyboard event is received from the hosting window
  19624. */
  19625. this.onKeyboardObservable = new BABYLON.Observable();
  19626. // Coordinate system
  19627. /**
  19628. * use right-handed coordinate system on this scene.
  19629. * @type {boolean}
  19630. */
  19631. this._useRightHandedSystem = false;
  19632. // Fog
  19633. this._fogEnabled = true;
  19634. this._fogMode = Scene.FOGMODE_NONE;
  19635. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19636. this.fogDensity = 0.1;
  19637. this.fogStart = 0;
  19638. this.fogEnd = 1000.0;
  19639. // Lights
  19640. /**
  19641. * is shadow enabled on this scene.
  19642. * @type {boolean}
  19643. */
  19644. this._shadowsEnabled = true;
  19645. /**
  19646. * is light enabled on this scene.
  19647. * @type {boolean}
  19648. */
  19649. this._lightsEnabled = true;
  19650. /**
  19651. * All of the lights added to this scene.
  19652. * @see BABYLON.Light
  19653. * @type {BABYLON.Light[]}
  19654. */
  19655. this.lights = new Array();
  19656. // Cameras
  19657. /** All of the cameras added to this scene. */
  19658. this.cameras = new Array();
  19659. /** All of the active cameras added to this scene. */
  19660. this.activeCameras = new Array();
  19661. // Meshes
  19662. /**
  19663. * All of the tranform nodes added to this scene.
  19664. * @see BABYLON.TransformNode
  19665. * @type {BABYLON.TransformNode[]}
  19666. */
  19667. this.transformNodes = new Array();
  19668. /**
  19669. * All of the (abstract) meshes added to this scene.
  19670. * @see BABYLON.AbstractMesh
  19671. * @type {BABYLON.AbstractMesh[]}
  19672. */
  19673. this.meshes = new Array();
  19674. /**
  19675. * All of the animation groups added to this scene.
  19676. * @see BABYLON.AnimationGroup
  19677. * @type {BABYLON.AnimationGroup[]}
  19678. */
  19679. this.animationGroups = new Array();
  19680. // Geometries
  19681. this._geometries = new Array();
  19682. this.materials = new Array();
  19683. this.multiMaterials = new Array();
  19684. // Textures
  19685. this._texturesEnabled = true;
  19686. this.textures = new Array();
  19687. // Particles
  19688. this.particlesEnabled = true;
  19689. this.particleSystems = new Array();
  19690. // Sprites
  19691. this.spritesEnabled = true;
  19692. this.spriteManagers = new Array();
  19693. // Layers
  19694. this.layers = new Array();
  19695. this.highlightLayers = new Array();
  19696. // Skeletons
  19697. this._skeletonsEnabled = true;
  19698. this.skeletons = new Array();
  19699. // Morph targets
  19700. this.morphTargetManagers = new Array();
  19701. // Lens flares
  19702. this.lensFlaresEnabled = true;
  19703. this.lensFlareSystems = new Array();
  19704. // Collisions
  19705. this.collisionsEnabled = true;
  19706. /** Defines the gravity applied to this scene */
  19707. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19708. // Postprocesses
  19709. this.postProcesses = new Array();
  19710. this.postProcessesEnabled = true;
  19711. // Customs render targets
  19712. this.renderTargetsEnabled = true;
  19713. this.dumpNextRenderTargets = false;
  19714. this.customRenderTargets = new Array();
  19715. // Imported meshes
  19716. this.importedMeshesFiles = new Array();
  19717. // Probes
  19718. this.probesEnabled = true;
  19719. this.reflectionProbes = new Array();
  19720. this._actionManagers = new Array();
  19721. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19722. // Procedural textures
  19723. this.proceduralTexturesEnabled = true;
  19724. this._proceduralTextures = new Array();
  19725. this.soundTracks = new Array();
  19726. this._audioEnabled = true;
  19727. this._headphone = false;
  19728. // Performance counters
  19729. this._totalVertices = new BABYLON.PerfCounter();
  19730. this._activeIndices = new BABYLON.PerfCounter();
  19731. this._activeParticles = new BABYLON.PerfCounter();
  19732. this._activeBones = new BABYLON.PerfCounter();
  19733. this._animationTime = 0;
  19734. this.animationTimeScale = 1;
  19735. this._renderId = 0;
  19736. this._executeWhenReadyTimeoutId = -1;
  19737. this._intermediateRendering = false;
  19738. this._viewUpdateFlag = -1;
  19739. this._projectionUpdateFlag = -1;
  19740. this._alternateViewUpdateFlag = -1;
  19741. this._alternateProjectionUpdateFlag = -1;
  19742. this._toBeDisposed = new BABYLON.SmartArray(256);
  19743. this._activeRequests = new Array();
  19744. this._pendingData = new Array();
  19745. this._isDisposed = false;
  19746. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19747. this._activeMeshes = new BABYLON.SmartArray(256);
  19748. this._processedMaterials = new BABYLON.SmartArray(256);
  19749. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19750. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19751. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19752. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19753. this._activeAnimatables = new Array();
  19754. this._transformMatrix = BABYLON.Matrix.Zero();
  19755. this._useAlternateCameraConfiguration = false;
  19756. this._alternateRendering = false;
  19757. this.requireLightSorting = false;
  19758. this._activeMeshesFrozen = false;
  19759. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19760. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19761. this._engine.scenes.push(this);
  19762. this._uid = null;
  19763. this._renderingManager = new BABYLON.RenderingManager(this);
  19764. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19765. if (BABYLON.OutlineRenderer) {
  19766. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19767. }
  19768. if (BABYLON.Tools.IsWindowObjectExist()) {
  19769. this.attachControl();
  19770. }
  19771. //simplification queue
  19772. if (BABYLON.SimplificationQueue) {
  19773. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19774. }
  19775. //collision coordinator initialization. For now legacy per default.
  19776. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19777. // Uniform Buffer
  19778. this._createUbo();
  19779. // Default Image processing definition.
  19780. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19781. }
  19782. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19783. /** The fog is deactivated */
  19784. get: function () {
  19785. return Scene._FOGMODE_NONE;
  19786. },
  19787. enumerable: true,
  19788. configurable: true
  19789. });
  19790. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19791. /** The fog density is following an exponential function */
  19792. get: function () {
  19793. return Scene._FOGMODE_EXP;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19799. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19800. get: function () {
  19801. return Scene._FOGMODE_EXP2;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19807. /** The fog density is following a linear function. */
  19808. get: function () {
  19809. return Scene._FOGMODE_LINEAR;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19815. /**
  19816. * Texture used in all pbr material as the reflection texture.
  19817. * As in the majority of the scene they are the same (exception for multi room and so on),
  19818. * this is easier to reference from here than from all the materials.
  19819. */
  19820. get: function () {
  19821. return this._environmentTexture;
  19822. },
  19823. /**
  19824. * Texture used in all pbr material as the reflection texture.
  19825. * As in the majority of the scene they are the same (exception for multi room and so on),
  19826. * this is easier to set here than in all the materials.
  19827. */
  19828. set: function (value) {
  19829. if (this._environmentTexture === value) {
  19830. return;
  19831. }
  19832. this._environmentTexture = value;
  19833. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19839. /**
  19840. * Default image processing configuration used either in the rendering
  19841. * Forward main pass or through the imageProcessingPostProcess if present.
  19842. * As in the majority of the scene they are the same (exception for multi camera),
  19843. * this is easier to reference from here than from all the materials and post process.
  19844. *
  19845. * No setter as we it is a shared configuration, you can set the values instead.
  19846. */
  19847. get: function () {
  19848. return this._imageProcessingConfiguration;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19854. get: function () {
  19855. return this._forcePointsCloud;
  19856. },
  19857. set: function (value) {
  19858. if (this._forcePointsCloud === value) {
  19859. return;
  19860. }
  19861. this._forcePointsCloud = value;
  19862. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(Scene.prototype, "onDispose", {
  19868. /** A function to be executed when this scene is disposed. */
  19869. set: function (callback) {
  19870. if (this._onDisposeObserver) {
  19871. this.onDisposeObservable.remove(this._onDisposeObserver);
  19872. }
  19873. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19874. },
  19875. enumerable: true,
  19876. configurable: true
  19877. });
  19878. Object.defineProperty(Scene.prototype, "beforeRender", {
  19879. /** A function to be executed before rendering this scene */
  19880. set: function (callback) {
  19881. if (this._onBeforeRenderObserver) {
  19882. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19883. }
  19884. if (callback) {
  19885. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19886. }
  19887. },
  19888. enumerable: true,
  19889. configurable: true
  19890. });
  19891. Object.defineProperty(Scene.prototype, "afterRender", {
  19892. /** A function to be executed after rendering this scene */
  19893. set: function (callback) {
  19894. if (this._onAfterRenderObserver) {
  19895. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19896. }
  19897. if (callback) {
  19898. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19899. }
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19905. set: function (callback) {
  19906. if (this._onBeforeCameraRenderObserver) {
  19907. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19908. }
  19909. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19915. set: function (callback) {
  19916. if (this._onAfterCameraRenderObserver) {
  19917. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19918. }
  19919. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19920. },
  19921. enumerable: true,
  19922. configurable: true
  19923. });
  19924. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19925. get: function () {
  19926. if (!this._gamepadManager) {
  19927. this._gamepadManager = new BABYLON.GamepadManager(this);
  19928. }
  19929. return this._gamepadManager;
  19930. },
  19931. enumerable: true,
  19932. configurable: true
  19933. });
  19934. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19935. get: function () {
  19936. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19942. get: function () {
  19943. return this._useRightHandedSystem;
  19944. },
  19945. set: function (value) {
  19946. if (this._useRightHandedSystem === value) {
  19947. return;
  19948. }
  19949. this._useRightHandedSystem = value;
  19950. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. Scene.prototype.setStepId = function (newStepId) {
  19956. this._currentStepId = newStepId;
  19957. };
  19958. ;
  19959. Scene.prototype.getStepId = function () {
  19960. return this._currentStepId;
  19961. };
  19962. ;
  19963. Scene.prototype.getInternalStep = function () {
  19964. return this._currentInternalStep;
  19965. };
  19966. ;
  19967. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19968. get: function () {
  19969. return this._fogEnabled;
  19970. },
  19971. /**
  19972. * is fog enabled on this scene.
  19973. */
  19974. set: function (value) {
  19975. if (this._fogEnabled === value) {
  19976. return;
  19977. }
  19978. this._fogEnabled = value;
  19979. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19980. },
  19981. enumerable: true,
  19982. configurable: true
  19983. });
  19984. Object.defineProperty(Scene.prototype, "fogMode", {
  19985. get: function () {
  19986. return this._fogMode;
  19987. },
  19988. set: function (value) {
  19989. if (this._fogMode === value) {
  19990. return;
  19991. }
  19992. this._fogMode = value;
  19993. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19994. },
  19995. enumerable: true,
  19996. configurable: true
  19997. });
  19998. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19999. get: function () {
  20000. return this._shadowsEnabled;
  20001. },
  20002. set: function (value) {
  20003. if (this._shadowsEnabled === value) {
  20004. return;
  20005. }
  20006. this._shadowsEnabled = value;
  20007. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20008. },
  20009. enumerable: true,
  20010. configurable: true
  20011. });
  20012. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20013. get: function () {
  20014. return this._lightsEnabled;
  20015. },
  20016. set: function (value) {
  20017. if (this._lightsEnabled === value) {
  20018. return;
  20019. }
  20020. this._lightsEnabled = value;
  20021. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20022. },
  20023. enumerable: true,
  20024. configurable: true
  20025. });
  20026. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20027. /** The default material used on meshes when no material is affected */
  20028. get: function () {
  20029. if (!this._defaultMaterial) {
  20030. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20031. }
  20032. return this._defaultMaterial;
  20033. },
  20034. /** The default material used on meshes when no material is affected */
  20035. set: function (value) {
  20036. this._defaultMaterial = value;
  20037. },
  20038. enumerable: true,
  20039. configurable: true
  20040. });
  20041. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20042. get: function () {
  20043. return this._texturesEnabled;
  20044. },
  20045. set: function (value) {
  20046. if (this._texturesEnabled === value) {
  20047. return;
  20048. }
  20049. this._texturesEnabled = value;
  20050. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20051. },
  20052. enumerable: true,
  20053. configurable: true
  20054. });
  20055. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20056. get: function () {
  20057. return this._skeletonsEnabled;
  20058. },
  20059. set: function (value) {
  20060. if (this._skeletonsEnabled === value) {
  20061. return;
  20062. }
  20063. this._skeletonsEnabled = value;
  20064. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20065. },
  20066. enumerable: true,
  20067. configurable: true
  20068. });
  20069. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20070. get: function () {
  20071. if (!this._postProcessRenderPipelineManager) {
  20072. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20073. }
  20074. return this._postProcessRenderPipelineManager;
  20075. },
  20076. enumerable: true,
  20077. configurable: true
  20078. });
  20079. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20080. get: function () {
  20081. if (!this._mainSoundTrack) {
  20082. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20083. }
  20084. return this._mainSoundTrack;
  20085. },
  20086. enumerable: true,
  20087. configurable: true
  20088. });
  20089. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20090. get: function () {
  20091. return this._alternateRendering;
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20097. get: function () {
  20098. return this._frustumPlanes;
  20099. },
  20100. enumerable: true,
  20101. configurable: true
  20102. });
  20103. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20104. /**
  20105. * Gets the current geometry buffer associated to the scene.
  20106. */
  20107. get: function () {
  20108. return this._geometryBufferRenderer;
  20109. },
  20110. /**
  20111. * Sets the current geometry buffer for the scene.
  20112. */
  20113. set: function (geometryBufferRenderer) {
  20114. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20115. this._geometryBufferRenderer = geometryBufferRenderer;
  20116. }
  20117. },
  20118. enumerable: true,
  20119. configurable: true
  20120. });
  20121. Object.defineProperty(Scene.prototype, "debugLayer", {
  20122. // Properties
  20123. get: function () {
  20124. if (!this._debugLayer) {
  20125. this._debugLayer = new BABYLON.DebugLayer(this);
  20126. }
  20127. return this._debugLayer;
  20128. },
  20129. enumerable: true,
  20130. configurable: true
  20131. });
  20132. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20133. get: function () {
  20134. return this._workerCollisions;
  20135. },
  20136. set: function (enabled) {
  20137. if (!BABYLON.CollisionCoordinatorLegacy) {
  20138. return;
  20139. }
  20140. enabled = (enabled && !!Worker);
  20141. this._workerCollisions = enabled;
  20142. if (this.collisionCoordinator) {
  20143. this.collisionCoordinator.destroy();
  20144. }
  20145. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20146. this.collisionCoordinator.init(this);
  20147. },
  20148. enumerable: true,
  20149. configurable: true
  20150. });
  20151. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20152. get: function () {
  20153. return this._selectionOctree;
  20154. },
  20155. enumerable: true,
  20156. configurable: true
  20157. });
  20158. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20159. /**
  20160. * The mesh that is currently under the pointer.
  20161. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20162. */
  20163. get: function () {
  20164. return this._pointerOverMesh;
  20165. },
  20166. enumerable: true,
  20167. configurable: true
  20168. });
  20169. Object.defineProperty(Scene.prototype, "pointerX", {
  20170. /**
  20171. * Current on-screen X position of the pointer
  20172. * @return {number} X position of the pointer
  20173. */
  20174. get: function () {
  20175. return this._pointerX;
  20176. },
  20177. enumerable: true,
  20178. configurable: true
  20179. });
  20180. Object.defineProperty(Scene.prototype, "pointerY", {
  20181. /**
  20182. * Current on-screen Y position of the pointer
  20183. * @return {number} Y position of the pointer
  20184. */
  20185. get: function () {
  20186. return this._pointerY;
  20187. },
  20188. enumerable: true,
  20189. configurable: true
  20190. });
  20191. Scene.prototype.getCachedMaterial = function () {
  20192. return this._cachedMaterial;
  20193. };
  20194. Scene.prototype.getCachedEffect = function () {
  20195. return this._cachedEffect;
  20196. };
  20197. Scene.prototype.getCachedVisibility = function () {
  20198. return this._cachedVisibility;
  20199. };
  20200. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20201. if (visibility === void 0) { visibility = 1; }
  20202. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20203. };
  20204. Scene.prototype.getBoundingBoxRenderer = function () {
  20205. if (!this._boundingBoxRenderer) {
  20206. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20207. }
  20208. return this._boundingBoxRenderer;
  20209. };
  20210. Scene.prototype.getOutlineRenderer = function () {
  20211. return this._outlineRenderer;
  20212. };
  20213. Scene.prototype.getEngine = function () {
  20214. return this._engine;
  20215. };
  20216. Scene.prototype.getTotalVertices = function () {
  20217. return this._totalVertices.current;
  20218. };
  20219. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20220. get: function () {
  20221. return this._totalVertices;
  20222. },
  20223. enumerable: true,
  20224. configurable: true
  20225. });
  20226. Scene.prototype.getActiveIndices = function () {
  20227. return this._activeIndices.current;
  20228. };
  20229. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20230. get: function () {
  20231. return this._activeIndices;
  20232. },
  20233. enumerable: true,
  20234. configurable: true
  20235. });
  20236. Scene.prototype.getActiveParticles = function () {
  20237. return this._activeParticles.current;
  20238. };
  20239. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20240. get: function () {
  20241. return this._activeParticles;
  20242. },
  20243. enumerable: true,
  20244. configurable: true
  20245. });
  20246. Scene.prototype.getActiveBones = function () {
  20247. return this._activeBones.current;
  20248. };
  20249. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20250. get: function () {
  20251. return this._activeBones;
  20252. },
  20253. enumerable: true,
  20254. configurable: true
  20255. });
  20256. // Stats
  20257. Scene.prototype.getInterFramePerfCounter = function () {
  20258. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20259. return 0;
  20260. };
  20261. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20262. get: function () {
  20263. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20264. return null;
  20265. },
  20266. enumerable: true,
  20267. configurable: true
  20268. });
  20269. Scene.prototype.getLastFrameDuration = function () {
  20270. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20271. return 0;
  20272. };
  20273. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20274. get: function () {
  20275. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20276. return null;
  20277. },
  20278. enumerable: true,
  20279. configurable: true
  20280. });
  20281. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20282. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20283. return 0;
  20284. };
  20285. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20286. get: function () {
  20287. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20288. return null;
  20289. },
  20290. enumerable: true,
  20291. configurable: true
  20292. });
  20293. Scene.prototype.getActiveMeshes = function () {
  20294. return this._activeMeshes;
  20295. };
  20296. Scene.prototype.getRenderTargetsDuration = function () {
  20297. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20298. return 0;
  20299. };
  20300. Scene.prototype.getRenderDuration = function () {
  20301. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20302. return 0;
  20303. };
  20304. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20305. get: function () {
  20306. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20307. return null;
  20308. },
  20309. enumerable: true,
  20310. configurable: true
  20311. });
  20312. Scene.prototype.getParticlesDuration = function () {
  20313. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20314. return 0;
  20315. };
  20316. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20317. get: function () {
  20318. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20319. return null;
  20320. },
  20321. enumerable: true,
  20322. configurable: true
  20323. });
  20324. Scene.prototype.getSpritesDuration = function () {
  20325. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20326. return 0;
  20327. };
  20328. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20329. get: function () {
  20330. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20331. return null;
  20332. },
  20333. enumerable: true,
  20334. configurable: true
  20335. });
  20336. Scene.prototype.getAnimationRatio = function () {
  20337. return this._animationRatio;
  20338. };
  20339. Scene.prototype.getRenderId = function () {
  20340. return this._renderId;
  20341. };
  20342. Scene.prototype.incrementRenderId = function () {
  20343. this._renderId++;
  20344. };
  20345. Scene.prototype._updatePointerPosition = function (evt) {
  20346. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20347. if (!canvasRect) {
  20348. return;
  20349. }
  20350. this._pointerX = evt.clientX - canvasRect.left;
  20351. this._pointerY = evt.clientY - canvasRect.top;
  20352. this._unTranslatedPointerX = this._pointerX;
  20353. this._unTranslatedPointerY = this._pointerY;
  20354. };
  20355. Scene.prototype._createUbo = function () {
  20356. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20357. this._sceneUbo.addUniform("viewProjection", 16);
  20358. this._sceneUbo.addUniform("view", 16);
  20359. };
  20360. Scene.prototype._createAlternateUbo = function () {
  20361. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20362. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20363. this._alternateSceneUbo.addUniform("view", 16);
  20364. };
  20365. // Pointers handling
  20366. /**
  20367. * Use this method to simulate a pointer move on a mesh
  20368. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20369. */
  20370. Scene.prototype.simulatePointerMove = function (pickResult) {
  20371. var evt = new PointerEvent("pointermove");
  20372. return this._processPointerMove(pickResult, evt);
  20373. };
  20374. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20375. var canvas = this._engine.getRenderingCanvas();
  20376. if (!canvas) {
  20377. return this;
  20378. }
  20379. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20380. this.setPointerOverSprite(null);
  20381. this.setPointerOverMesh(pickResult.pickedMesh);
  20382. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20383. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20384. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20385. }
  20386. else {
  20387. canvas.style.cursor = this.hoverCursor;
  20388. }
  20389. }
  20390. else {
  20391. canvas.style.cursor = this.defaultCursor;
  20392. }
  20393. }
  20394. else {
  20395. this.setPointerOverMesh(null);
  20396. // Sprites
  20397. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20398. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20399. this.setPointerOverSprite(pickResult.pickedSprite);
  20400. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20401. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20402. }
  20403. else {
  20404. canvas.style.cursor = this.hoverCursor;
  20405. }
  20406. }
  20407. else {
  20408. this.setPointerOverSprite(null);
  20409. // Restore pointer
  20410. canvas.style.cursor = this.defaultCursor;
  20411. }
  20412. }
  20413. if (pickResult) {
  20414. if (this.onPointerMove) {
  20415. this.onPointerMove(evt, pickResult);
  20416. }
  20417. if (this.onPointerObservable.hasObservers()) {
  20418. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20419. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20420. this.onPointerObservable.notifyObservers(pi, type);
  20421. }
  20422. }
  20423. return this;
  20424. };
  20425. /**
  20426. * Use this method to simulate a pointer down on a mesh
  20427. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20428. */
  20429. Scene.prototype.simulatePointerDown = function (pickResult) {
  20430. var evt = new PointerEvent("pointerdown");
  20431. return this._processPointerDown(pickResult, evt);
  20432. };
  20433. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20434. var _this = this;
  20435. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20436. this._pickedDownMesh = pickResult.pickedMesh;
  20437. var actionManager = pickResult.pickedMesh.actionManager;
  20438. if (actionManager) {
  20439. if (actionManager.hasPickTriggers) {
  20440. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20441. switch (evt.button) {
  20442. case 0:
  20443. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20444. break;
  20445. case 1:
  20446. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20447. break;
  20448. case 2:
  20449. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20450. break;
  20451. }
  20452. }
  20453. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20454. window.setTimeout(function () {
  20455. 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);
  20456. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20457. if (_this._totalPointersPressed !== 0 &&
  20458. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20459. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20460. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20461. _this._startingPointerTime = 0;
  20462. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20463. }
  20464. }
  20465. }, Scene.LongPressDelay);
  20466. }
  20467. }
  20468. }
  20469. if (pickResult) {
  20470. if (this.onPointerDown) {
  20471. this.onPointerDown(evt, pickResult);
  20472. }
  20473. if (this.onPointerObservable.hasObservers()) {
  20474. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20475. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20476. this.onPointerObservable.notifyObservers(pi, type);
  20477. }
  20478. }
  20479. return this;
  20480. };
  20481. /**
  20482. * Use this method to simulate a pointer up on a mesh
  20483. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20484. */
  20485. Scene.prototype.simulatePointerUp = function (pickResult) {
  20486. var evt = new PointerEvent("pointerup");
  20487. var clickInfo = new ClickInfo();
  20488. clickInfo.singleClick = true;
  20489. clickInfo.ignore = true;
  20490. return this._processPointerUp(pickResult, evt, clickInfo);
  20491. };
  20492. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20493. if (pickResult && pickResult && pickResult.pickedMesh) {
  20494. this._pickedUpMesh = pickResult.pickedMesh;
  20495. if (this._pickedDownMesh === this._pickedUpMesh) {
  20496. if (this.onPointerPick) {
  20497. this.onPointerPick(evt, pickResult);
  20498. }
  20499. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20500. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20501. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20502. this.onPointerObservable.notifyObservers(pi, type);
  20503. }
  20504. }
  20505. if (pickResult.pickedMesh.actionManager) {
  20506. if (clickInfo.ignore) {
  20507. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20508. }
  20509. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20510. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20511. }
  20512. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20513. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20514. }
  20515. }
  20516. }
  20517. if (this._pickedDownMesh &&
  20518. this._pickedDownMesh.actionManager &&
  20519. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20520. this._pickedDownMesh !== this._pickedUpMesh) {
  20521. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20522. }
  20523. if (this.onPointerUp) {
  20524. this.onPointerUp(evt, pickResult);
  20525. }
  20526. if (this.onPointerObservable.hasObservers()) {
  20527. if (!clickInfo.ignore) {
  20528. if (!clickInfo.hasSwiped) {
  20529. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20530. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20531. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20532. this.onPointerObservable.notifyObservers(pi, type);
  20533. }
  20534. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20535. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20536. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20537. this.onPointerObservable.notifyObservers(pi, type);
  20538. }
  20539. }
  20540. }
  20541. else {
  20542. var type = BABYLON.PointerEventTypes.POINTERUP;
  20543. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20544. this.onPointerObservable.notifyObservers(pi, type);
  20545. }
  20546. }
  20547. return this;
  20548. };
  20549. /**
  20550. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20551. * @param attachUp defines if you want to attach events to pointerup
  20552. * @param attachDown defines if you want to attach events to pointerdown
  20553. * @param attachMove defines if you want to attach events to pointermove
  20554. */
  20555. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20556. var _this = this;
  20557. if (attachUp === void 0) { attachUp = true; }
  20558. if (attachDown === void 0) { attachDown = true; }
  20559. if (attachMove === void 0) { attachMove = true; }
  20560. this._initActionManager = function (act, clickInfo) {
  20561. if (!_this._meshPickProceed) {
  20562. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20563. _this._currentPickResult = pickResult;
  20564. if (pickResult) {
  20565. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20566. }
  20567. _this._meshPickProceed = true;
  20568. }
  20569. return act;
  20570. };
  20571. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20572. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20573. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20574. btn !== _this._previousButtonPressed) {
  20575. _this._doubleClickOccured = false;
  20576. clickInfo.singleClick = true;
  20577. clickInfo.ignore = false;
  20578. cb(clickInfo, _this._currentPickResult);
  20579. }
  20580. };
  20581. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20582. var clickInfo = new ClickInfo();
  20583. _this._currentPickResult = null;
  20584. var act = null;
  20585. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20586. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20587. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20588. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20589. act = _this._initActionManager(act, clickInfo);
  20590. if (act)
  20591. checkPicking = act.hasPickTriggers;
  20592. }
  20593. if (checkPicking) {
  20594. var btn = evt.button;
  20595. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20596. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20597. if (!clickInfo.hasSwiped) {
  20598. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20599. if (!checkSingleClickImmediately) {
  20600. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20601. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20602. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20603. act = _this._initActionManager(act, clickInfo);
  20604. if (act)
  20605. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20606. }
  20607. }
  20608. if (checkSingleClickImmediately) {
  20609. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20610. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20611. btn !== _this._previousButtonPressed) {
  20612. clickInfo.singleClick = true;
  20613. cb(clickInfo, _this._currentPickResult);
  20614. }
  20615. }
  20616. else {
  20617. // wait that no double click has been raised during the double click delay
  20618. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20619. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20620. }
  20621. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20622. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20623. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20624. act = _this._initActionManager(act, clickInfo);
  20625. if (act)
  20626. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20627. }
  20628. if (checkDoubleClick) {
  20629. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20630. if (btn === _this._previousButtonPressed &&
  20631. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20632. !_this._doubleClickOccured) {
  20633. // pointer has not moved for 2 clicks, it's a double click
  20634. if (!clickInfo.hasSwiped &&
  20635. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20636. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20637. _this._previousStartingPointerTime = 0;
  20638. _this._doubleClickOccured = true;
  20639. clickInfo.doubleClick = true;
  20640. clickInfo.ignore = false;
  20641. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20642. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20643. }
  20644. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20645. cb(clickInfo, _this._currentPickResult);
  20646. }
  20647. else {
  20648. _this._doubleClickOccured = false;
  20649. _this._previousStartingPointerTime = _this._startingPointerTime;
  20650. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20651. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20652. _this._previousButtonPressed = btn;
  20653. if (Scene.ExclusiveDoubleClickMode) {
  20654. if (_this._previousDelayedSimpleClickTimeout) {
  20655. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20656. }
  20657. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20658. cb(clickInfo, _this._previousPickResult);
  20659. }
  20660. else {
  20661. cb(clickInfo, _this._currentPickResult);
  20662. }
  20663. }
  20664. }
  20665. else {
  20666. _this._doubleClickOccured = false;
  20667. _this._previousStartingPointerTime = _this._startingPointerTime;
  20668. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20669. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20670. _this._previousButtonPressed = btn;
  20671. }
  20672. }
  20673. }
  20674. }
  20675. clickInfo.ignore = true;
  20676. cb(clickInfo, _this._currentPickResult);
  20677. };
  20678. this._spritePredicate = function (sprite) {
  20679. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20680. };
  20681. this._onPointerMove = function (evt) {
  20682. _this._updatePointerPosition(evt);
  20683. // PreObservable support
  20684. if (_this.onPrePointerObservable.hasObservers()) {
  20685. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20686. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20687. _this.onPrePointerObservable.notifyObservers(pi, type);
  20688. if (pi.skipOnPointerObservable) {
  20689. return;
  20690. }
  20691. }
  20692. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20693. return;
  20694. }
  20695. if (!_this.pointerMovePredicate) {
  20696. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20697. }
  20698. // Meshes
  20699. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20700. _this._processPointerMove(pickResult, evt);
  20701. };
  20702. this._onPointerDown = function (evt) {
  20703. _this._totalPointersPressed++;
  20704. _this._pickedDownMesh = null;
  20705. _this._meshPickProceed = false;
  20706. _this._updatePointerPosition(evt);
  20707. if (_this.preventDefaultOnPointerDown && canvas) {
  20708. evt.preventDefault();
  20709. canvas.focus();
  20710. }
  20711. // PreObservable support
  20712. if (_this.onPrePointerObservable.hasObservers()) {
  20713. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20714. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20715. _this.onPrePointerObservable.notifyObservers(pi, type);
  20716. if (pi.skipOnPointerObservable) {
  20717. return;
  20718. }
  20719. }
  20720. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20721. return;
  20722. }
  20723. _this._startingPointerPosition.x = _this._pointerX;
  20724. _this._startingPointerPosition.y = _this._pointerY;
  20725. _this._startingPointerTime = new Date().getTime();
  20726. if (!_this.pointerDownPredicate) {
  20727. _this.pointerDownPredicate = function (mesh) {
  20728. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20729. };
  20730. }
  20731. // Meshes
  20732. _this._pickedDownMesh = null;
  20733. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20734. _this._processPointerDown(pickResult, evt);
  20735. // Sprites
  20736. _this._pickedDownSprite = null;
  20737. if (_this.spriteManagers.length > 0) {
  20738. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20739. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20740. if (pickResult.pickedSprite.actionManager) {
  20741. _this._pickedDownSprite = pickResult.pickedSprite;
  20742. switch (evt.button) {
  20743. case 0:
  20744. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20745. break;
  20746. case 1:
  20747. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20748. break;
  20749. case 2:
  20750. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20751. break;
  20752. }
  20753. if (pickResult.pickedSprite.actionManager) {
  20754. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20755. }
  20756. }
  20757. }
  20758. }
  20759. };
  20760. this._onPointerUp = function (evt) {
  20761. if (_this._totalPointersPressed === 0) {
  20762. return; // So we need to test it the pointer down was pressed before.
  20763. }
  20764. _this._totalPointersPressed--;
  20765. _this._pickedUpMesh = null;
  20766. _this._meshPickProceed = false;
  20767. _this._updatePointerPosition(evt);
  20768. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20769. // PreObservable support
  20770. if (_this.onPrePointerObservable.hasObservers()) {
  20771. if (!clickInfo.ignore) {
  20772. if (!clickInfo.hasSwiped) {
  20773. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20774. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20775. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20776. _this.onPrePointerObservable.notifyObservers(pi, type);
  20777. if (pi.skipOnPointerObservable) {
  20778. return;
  20779. }
  20780. }
  20781. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20782. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20783. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20784. _this.onPrePointerObservable.notifyObservers(pi, type);
  20785. if (pi.skipOnPointerObservable) {
  20786. return;
  20787. }
  20788. }
  20789. }
  20790. }
  20791. else {
  20792. var type = BABYLON.PointerEventTypes.POINTERUP;
  20793. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20794. _this.onPrePointerObservable.notifyObservers(pi, type);
  20795. if (pi.skipOnPointerObservable) {
  20796. return;
  20797. }
  20798. }
  20799. }
  20800. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20801. return;
  20802. }
  20803. if (!_this.pointerUpPredicate) {
  20804. _this.pointerUpPredicate = function (mesh) {
  20805. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20806. };
  20807. }
  20808. // Meshes
  20809. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20810. _this._initActionManager(null, clickInfo);
  20811. }
  20812. if (!pickResult) {
  20813. pickResult = _this._currentPickResult;
  20814. }
  20815. _this._processPointerUp(pickResult, evt, clickInfo);
  20816. // Sprites
  20817. if (_this.spriteManagers.length > 0) {
  20818. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20819. if (spritePickResult) {
  20820. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20821. if (spritePickResult.pickedSprite.actionManager) {
  20822. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20823. if (spritePickResult.pickedSprite.actionManager) {
  20824. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20825. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20826. }
  20827. }
  20828. }
  20829. }
  20830. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20831. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20832. }
  20833. }
  20834. }
  20835. _this._previousPickResult = _this._currentPickResult;
  20836. });
  20837. };
  20838. this._onKeyDown = function (evt) {
  20839. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20840. if (_this.onPreKeyboardObservable.hasObservers()) {
  20841. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20842. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20843. if (pi.skipOnPointerObservable) {
  20844. return;
  20845. }
  20846. }
  20847. if (_this.onKeyboardObservable.hasObservers()) {
  20848. var pi = new BABYLON.KeyboardInfo(type, evt);
  20849. _this.onKeyboardObservable.notifyObservers(pi, type);
  20850. }
  20851. if (_this.actionManager) {
  20852. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20853. }
  20854. };
  20855. this._onKeyUp = function (evt) {
  20856. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20857. if (_this.onPreKeyboardObservable.hasObservers()) {
  20858. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20859. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20860. if (pi.skipOnPointerObservable) {
  20861. return;
  20862. }
  20863. }
  20864. if (_this.onKeyboardObservable.hasObservers()) {
  20865. var pi = new BABYLON.KeyboardInfo(type, evt);
  20866. _this.onKeyboardObservable.notifyObservers(pi, type);
  20867. }
  20868. if (_this.actionManager) {
  20869. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20870. }
  20871. };
  20872. var engine = this.getEngine();
  20873. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20874. if (!canvas) {
  20875. return;
  20876. }
  20877. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20878. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20879. });
  20880. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20881. if (!canvas) {
  20882. return;
  20883. }
  20884. canvas.removeEventListener("keydown", _this._onKeyDown);
  20885. canvas.removeEventListener("keyup", _this._onKeyUp);
  20886. });
  20887. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20888. var canvas = this._engine.getRenderingCanvas();
  20889. if (!canvas) {
  20890. return;
  20891. }
  20892. if (attachMove) {
  20893. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20894. // Wheel
  20895. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20896. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20897. }
  20898. if (attachDown) {
  20899. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20900. }
  20901. if (attachUp) {
  20902. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20903. }
  20904. canvas.tabIndex = 1;
  20905. };
  20906. Scene.prototype.detachControl = function () {
  20907. var engine = this.getEngine();
  20908. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20909. var canvas = engine.getRenderingCanvas();
  20910. if (!canvas) {
  20911. return;
  20912. }
  20913. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20914. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20915. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20916. if (this._onCanvasBlurObserver) {
  20917. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20918. }
  20919. if (this._onCanvasFocusObserver) {
  20920. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20921. }
  20922. // Wheel
  20923. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20924. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20925. // Keyboard
  20926. canvas.removeEventListener("keydown", this._onKeyDown);
  20927. canvas.removeEventListener("keyup", this._onKeyUp);
  20928. // Observables
  20929. this.onKeyboardObservable.clear();
  20930. this.onPreKeyboardObservable.clear();
  20931. this.onPointerObservable.clear();
  20932. this.onPrePointerObservable.clear();
  20933. };
  20934. /**
  20935. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20936. * Delay loaded resources are not taking in account
  20937. * @return true if all required resources are ready
  20938. */
  20939. Scene.prototype.isReady = function () {
  20940. if (this._isDisposed) {
  20941. return false;
  20942. }
  20943. if (this._pendingData.length > 0) {
  20944. return false;
  20945. }
  20946. var index;
  20947. var engine = this.getEngine();
  20948. // Geometries
  20949. for (index = 0; index < this._geometries.length; index++) {
  20950. var geometry = this._geometries[index];
  20951. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20952. return false;
  20953. }
  20954. }
  20955. // Meshes
  20956. for (index = 0; index < this.meshes.length; index++) {
  20957. var mesh = this.meshes[index];
  20958. if (!mesh.isEnabled()) {
  20959. continue;
  20960. }
  20961. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20962. continue;
  20963. }
  20964. if (!mesh.isReady()) {
  20965. return false;
  20966. }
  20967. // Highlight layers
  20968. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  20969. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  20970. var layer = _a[_i];
  20971. if (!layer.hasMesh(mesh)) {
  20972. continue;
  20973. }
  20974. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  20975. var subMesh = _c[_b];
  20976. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  20977. return false;
  20978. }
  20979. }
  20980. }
  20981. }
  20982. return true;
  20983. };
  20984. Scene.prototype.resetCachedMaterial = function () {
  20985. this._cachedMaterial = null;
  20986. this._cachedEffect = null;
  20987. this._cachedVisibility = null;
  20988. };
  20989. Scene.prototype.registerBeforeRender = function (func) {
  20990. this.onBeforeRenderObservable.add(func);
  20991. };
  20992. Scene.prototype.unregisterBeforeRender = function (func) {
  20993. this.onBeforeRenderObservable.removeCallback(func);
  20994. };
  20995. Scene.prototype.registerAfterRender = function (func) {
  20996. this.onAfterRenderObservable.add(func);
  20997. };
  20998. Scene.prototype.unregisterAfterRender = function (func) {
  20999. this.onAfterRenderObservable.removeCallback(func);
  21000. };
  21001. Scene.prototype._executeOnceBeforeRender = function (func) {
  21002. var _this = this;
  21003. var execFunc = function () {
  21004. func();
  21005. setTimeout(function () {
  21006. _this.unregisterBeforeRender(execFunc);
  21007. });
  21008. };
  21009. this.registerBeforeRender(execFunc);
  21010. };
  21011. /**
  21012. * The provided function will run before render once and will be disposed afterwards.
  21013. * A timeout delay can be provided so that the function will be executed in N ms.
  21014. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21015. * @param func The function to be executed.
  21016. * @param timeout optional delay in ms
  21017. */
  21018. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21019. var _this = this;
  21020. if (timeout !== undefined) {
  21021. setTimeout(function () {
  21022. _this._executeOnceBeforeRender(func);
  21023. }, timeout);
  21024. }
  21025. else {
  21026. this._executeOnceBeforeRender(func);
  21027. }
  21028. };
  21029. Scene.prototype._addPendingData = function (data) {
  21030. this._pendingData.push(data);
  21031. };
  21032. Scene.prototype._removePendingData = function (data) {
  21033. var wasLoading = this.isLoading;
  21034. var index = this._pendingData.indexOf(data);
  21035. if (index !== -1) {
  21036. this._pendingData.splice(index, 1);
  21037. }
  21038. if (wasLoading && !this.isLoading) {
  21039. this.onDataLoadedObservable.notifyObservers(this);
  21040. }
  21041. };
  21042. Scene.prototype.getWaitingItemsCount = function () {
  21043. return this._pendingData.length;
  21044. };
  21045. Object.defineProperty(Scene.prototype, "isLoading", {
  21046. get: function () {
  21047. return this._pendingData.length > 0;
  21048. },
  21049. enumerable: true,
  21050. configurable: true
  21051. });
  21052. /**
  21053. * Registers a function to be executed when the scene is ready.
  21054. * @param {Function} func - the function to be executed.
  21055. */
  21056. Scene.prototype.executeWhenReady = function (func) {
  21057. var _this = this;
  21058. this.onReadyObservable.add(func);
  21059. if (this._executeWhenReadyTimeoutId !== -1) {
  21060. return;
  21061. }
  21062. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21063. _this._checkIsReady();
  21064. }, 150);
  21065. };
  21066. Scene.prototype._checkIsReady = function () {
  21067. var _this = this;
  21068. if (this.isReady()) {
  21069. this.onReadyObservable.notifyObservers(this);
  21070. this.onReadyObservable.clear();
  21071. this._executeWhenReadyTimeoutId = -1;
  21072. return;
  21073. }
  21074. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21075. _this._checkIsReady();
  21076. }, 150);
  21077. };
  21078. // Animations
  21079. /**
  21080. * Will start the animation sequence of a given target
  21081. * @param target - the target
  21082. * @param {number} from - from which frame should animation start
  21083. * @param {number} to - till which frame should animation run.
  21084. * @param {boolean} [loop] - should the animation loop
  21085. * @param {number} [speedRatio] - the speed in which to run the animation
  21086. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21087. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21088. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21089. * See BABYLON.Animatable
  21090. */
  21091. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21092. if (speedRatio === void 0) { speedRatio = 1.0; }
  21093. if (from > to && speedRatio > 0) {
  21094. speedRatio *= -1;
  21095. }
  21096. this.stopAnimation(target);
  21097. if (!animatable) {
  21098. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21099. }
  21100. // Local animations
  21101. if (target.animations) {
  21102. animatable.appendAnimations(target, target.animations);
  21103. }
  21104. // Children animations
  21105. if (target.getAnimatables) {
  21106. var animatables = target.getAnimatables();
  21107. for (var index = 0; index < animatables.length; index++) {
  21108. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21109. }
  21110. }
  21111. animatable.reset();
  21112. return animatable;
  21113. };
  21114. /**
  21115. * Begin a new animation on a given node
  21116. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21117. * @param {BABYLON.Animation[]} defines the list of animations to start
  21118. * @param {number} from defines the initial value
  21119. * @param {number} to defines the final value
  21120. * @param {boolean} loop defines if you want animation to loop (off by default)
  21121. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21122. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21123. * @returns the list of created animatables
  21124. */
  21125. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21126. if (speedRatio === undefined) {
  21127. speedRatio = 1.0;
  21128. }
  21129. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21130. return animatable;
  21131. };
  21132. /**
  21133. * Begin a new animation on a given node and its hierarchy
  21134. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21135. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  21136. * @param {BABYLON.Animation[]} defines the list of animations to start
  21137. * @param {number} from defines the initial value
  21138. * @param {number} to defines the final value
  21139. * @param {boolean} loop defines if you want animation to loop (off by default)
  21140. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21141. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21142. * @returns the list of animatables created for all nodes
  21143. */
  21144. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21145. var children = target.getDescendants(directDescendantsOnly);
  21146. var result = [];
  21147. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21148. var child = children_1[_i];
  21149. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21150. }
  21151. return result;
  21152. };
  21153. Scene.prototype.getAnimatableByTarget = function (target) {
  21154. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21155. if (this._activeAnimatables[index].target === target) {
  21156. return this._activeAnimatables[index];
  21157. }
  21158. }
  21159. return null;
  21160. };
  21161. Object.defineProperty(Scene.prototype, "animatables", {
  21162. get: function () {
  21163. return this._activeAnimatables;
  21164. },
  21165. enumerable: true,
  21166. configurable: true
  21167. });
  21168. /**
  21169. * Will stop the animation of the given target
  21170. * @param target - the target
  21171. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21172. * @see beginAnimation
  21173. */
  21174. Scene.prototype.stopAnimation = function (target, animationName) {
  21175. var animatable = this.getAnimatableByTarget(target);
  21176. if (animatable) {
  21177. animatable.stop(animationName);
  21178. }
  21179. };
  21180. /**
  21181. * Stops and removes all animations that have been applied to the scene
  21182. */
  21183. Scene.prototype.stopAllAnimations = function () {
  21184. if (this._activeAnimatables) {
  21185. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21186. this._activeAnimatables[i].stop();
  21187. }
  21188. this._activeAnimatables = [];
  21189. }
  21190. };
  21191. Scene.prototype._animate = function () {
  21192. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21193. return;
  21194. }
  21195. // Getting time
  21196. var now = BABYLON.Tools.Now;
  21197. if (!this._animationTimeLast) {
  21198. if (this._pendingData.length > 0) {
  21199. return;
  21200. }
  21201. this._animationTimeLast = now;
  21202. }
  21203. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21204. this._animationTime += deltaTime;
  21205. this._animationTimeLast = now;
  21206. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21207. this._activeAnimatables[index]._animate(this._animationTime);
  21208. }
  21209. };
  21210. // Matrix
  21211. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21212. this._useAlternateCameraConfiguration = active;
  21213. };
  21214. Scene.prototype.getViewMatrix = function () {
  21215. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21216. };
  21217. Scene.prototype.getProjectionMatrix = function () {
  21218. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21219. };
  21220. Scene.prototype.getTransformMatrix = function () {
  21221. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21222. };
  21223. Scene.prototype.setTransformMatrix = function (view, projection) {
  21224. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21225. return;
  21226. }
  21227. this._viewUpdateFlag = view.updateFlag;
  21228. this._projectionUpdateFlag = projection.updateFlag;
  21229. this._viewMatrix = view;
  21230. this._projectionMatrix = projection;
  21231. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21232. // Update frustum
  21233. if (!this._frustumPlanes) {
  21234. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21235. }
  21236. else {
  21237. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21238. }
  21239. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21240. var otherCamera = this.activeCamera._alternateCamera;
  21241. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21242. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21243. }
  21244. if (this._sceneUbo.useUbo) {
  21245. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21246. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21247. this._sceneUbo.update();
  21248. }
  21249. };
  21250. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21251. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21252. return;
  21253. }
  21254. this._alternateViewUpdateFlag = view.updateFlag;
  21255. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21256. this._alternateViewMatrix = view;
  21257. this._alternateProjectionMatrix = projection;
  21258. if (!this._alternateTransformMatrix) {
  21259. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21260. }
  21261. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21262. if (!this._alternateSceneUbo) {
  21263. this._createAlternateUbo();
  21264. }
  21265. if (this._alternateSceneUbo.useUbo) {
  21266. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21267. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21268. this._alternateSceneUbo.update();
  21269. }
  21270. };
  21271. Scene.prototype.getSceneUniformBuffer = function () {
  21272. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21273. };
  21274. // Methods
  21275. Scene.prototype.getUniqueId = function () {
  21276. var result = Scene._uniqueIdCounter;
  21277. Scene._uniqueIdCounter++;
  21278. return result;
  21279. };
  21280. Scene.prototype.addMesh = function (newMesh) {
  21281. this.meshes.push(newMesh);
  21282. //notify the collision coordinator
  21283. if (this.collisionCoordinator) {
  21284. this.collisionCoordinator.onMeshAdded(newMesh);
  21285. }
  21286. newMesh._resyncLightSources();
  21287. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21288. };
  21289. Scene.prototype.removeMesh = function (toRemove) {
  21290. var index = this.meshes.indexOf(toRemove);
  21291. if (index !== -1) {
  21292. // Remove from the scene if mesh found
  21293. this.meshes.splice(index, 1);
  21294. }
  21295. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21296. return index;
  21297. };
  21298. Scene.prototype.addTransformNode = function (newTransformNode) {
  21299. this.transformNodes.push(newTransformNode);
  21300. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21301. };
  21302. Scene.prototype.removeTransformNode = function (toRemove) {
  21303. var index = this.transformNodes.indexOf(toRemove);
  21304. if (index !== -1) {
  21305. // Remove from the scene if found
  21306. this.transformNodes.splice(index, 1);
  21307. }
  21308. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21309. return index;
  21310. };
  21311. Scene.prototype.removeSkeleton = function (toRemove) {
  21312. var index = this.skeletons.indexOf(toRemove);
  21313. if (index !== -1) {
  21314. // Remove from the scene if found
  21315. this.skeletons.splice(index, 1);
  21316. }
  21317. return index;
  21318. };
  21319. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21320. var index = this.morphTargetManagers.indexOf(toRemove);
  21321. if (index !== -1) {
  21322. // Remove from the scene if found
  21323. this.morphTargetManagers.splice(index, 1);
  21324. }
  21325. return index;
  21326. };
  21327. Scene.prototype.removeLight = function (toRemove) {
  21328. var index = this.lights.indexOf(toRemove);
  21329. if (index !== -1) {
  21330. // Remove from meshes
  21331. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21332. var mesh = _a[_i];
  21333. mesh._removeLightSource(toRemove);
  21334. }
  21335. // Remove from the scene if mesh found
  21336. this.lights.splice(index, 1);
  21337. this.sortLightsByPriority();
  21338. }
  21339. this.onLightRemovedObservable.notifyObservers(toRemove);
  21340. return index;
  21341. };
  21342. Scene.prototype.removeCamera = function (toRemove) {
  21343. var index = this.cameras.indexOf(toRemove);
  21344. if (index !== -1) {
  21345. // Remove from the scene if mesh found
  21346. this.cameras.splice(index, 1);
  21347. }
  21348. // Remove from activeCameras
  21349. var index2 = this.activeCameras.indexOf(toRemove);
  21350. if (index2 !== -1) {
  21351. // Remove from the scene if mesh found
  21352. this.activeCameras.splice(index2, 1);
  21353. }
  21354. // Reset the activeCamera
  21355. if (this.activeCamera === toRemove) {
  21356. if (this.cameras.length > 0) {
  21357. this.activeCamera = this.cameras[0];
  21358. }
  21359. else {
  21360. this.activeCamera = null;
  21361. }
  21362. }
  21363. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21364. return index;
  21365. };
  21366. Scene.prototype.removeParticleSystem = function (toRemove) {
  21367. var index = this.particleSystems.indexOf(toRemove);
  21368. if (index !== -1) {
  21369. this.particleSystems.splice(index, 1);
  21370. }
  21371. return index;
  21372. };
  21373. ;
  21374. Scene.prototype.removeAnimation = function (toRemove) {
  21375. var index = this.animations.indexOf(toRemove);
  21376. if (index !== -1) {
  21377. this.animations.splice(index, 1);
  21378. }
  21379. return index;
  21380. };
  21381. ;
  21382. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21383. var index = this.multiMaterials.indexOf(toRemove);
  21384. if (index !== -1) {
  21385. this.multiMaterials.splice(index, 1);
  21386. }
  21387. return index;
  21388. };
  21389. ;
  21390. Scene.prototype.removeMaterial = function (toRemove) {
  21391. var index = this.materials.indexOf(toRemove);
  21392. if (index !== -1) {
  21393. this.materials.splice(index, 1);
  21394. }
  21395. return index;
  21396. };
  21397. ;
  21398. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21399. var index = this.lensFlareSystems.indexOf(toRemove);
  21400. if (index !== -1) {
  21401. this.lensFlareSystems.splice(index, 1);
  21402. }
  21403. return index;
  21404. };
  21405. ;
  21406. Scene.prototype.removeActionManager = function (toRemove) {
  21407. var index = this._actionManagers.indexOf(toRemove);
  21408. if (index !== -1) {
  21409. this._actionManagers.splice(index, 1);
  21410. }
  21411. return index;
  21412. };
  21413. ;
  21414. Scene.prototype.addLight = function (newLight) {
  21415. this.lights.push(newLight);
  21416. this.sortLightsByPriority();
  21417. // Add light to all meshes (To support if the light is removed and then readded)
  21418. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21419. var mesh = _a[_i];
  21420. if (mesh._lightSources.indexOf(newLight) === -1) {
  21421. mesh._lightSources.push(newLight);
  21422. mesh._resyncLightSources();
  21423. }
  21424. }
  21425. this.onNewLightAddedObservable.notifyObservers(newLight);
  21426. };
  21427. Scene.prototype.sortLightsByPriority = function () {
  21428. if (this.requireLightSorting) {
  21429. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21430. }
  21431. };
  21432. Scene.prototype.addCamera = function (newCamera) {
  21433. this.cameras.push(newCamera);
  21434. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21435. };
  21436. Scene.prototype.addSkeleton = function (newSkeleton) {
  21437. this.skeletons.push(newSkeleton);
  21438. };
  21439. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21440. this.particleSystems.push(newParticleSystem);
  21441. };
  21442. Scene.prototype.addAnimation = function (newAnimation) {
  21443. this.animations.push(newAnimation);
  21444. };
  21445. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21446. this.multiMaterials.push(newMultiMaterial);
  21447. };
  21448. Scene.prototype.addMaterial = function (newMaterial) {
  21449. this.materials.push(newMaterial);
  21450. };
  21451. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21452. this.morphTargetManagers.push(newMorphTargetManager);
  21453. };
  21454. Scene.prototype.addGeometry = function (newGeometrie) {
  21455. this._geometries.push(newGeometrie);
  21456. };
  21457. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21458. this.lensFlareSystems.push(newLensFlareSystem);
  21459. };
  21460. Scene.prototype.addActionManager = function (newActionManager) {
  21461. this._actionManagers.push(newActionManager);
  21462. };
  21463. /**
  21464. * Switch active camera
  21465. * @param {Camera} newCamera - new active camera
  21466. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21467. */
  21468. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21469. if (attachControl === void 0) { attachControl = true; }
  21470. var canvas = this._engine.getRenderingCanvas();
  21471. if (!canvas) {
  21472. return;
  21473. }
  21474. if (this.activeCamera) {
  21475. this.activeCamera.detachControl(canvas);
  21476. }
  21477. this.activeCamera = newCamera;
  21478. if (attachControl) {
  21479. newCamera.attachControl(canvas);
  21480. }
  21481. };
  21482. /**
  21483. * sets the active camera of the scene using its ID
  21484. * @param {string} id - the camera's ID
  21485. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21486. * @see activeCamera
  21487. */
  21488. Scene.prototype.setActiveCameraByID = function (id) {
  21489. var camera = this.getCameraByID(id);
  21490. if (camera) {
  21491. this.activeCamera = camera;
  21492. return camera;
  21493. }
  21494. return null;
  21495. };
  21496. /**
  21497. * sets the active camera of the scene using its name
  21498. * @param {string} name - the camera's name
  21499. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21500. * @see activeCamera
  21501. */
  21502. Scene.prototype.setActiveCameraByName = function (name) {
  21503. var camera = this.getCameraByName(name);
  21504. if (camera) {
  21505. this.activeCamera = camera;
  21506. return camera;
  21507. }
  21508. return null;
  21509. };
  21510. /**
  21511. * get an animation group using its name
  21512. * @param {string} the material's name
  21513. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21514. */
  21515. Scene.prototype.getAnimationGroupByName = function (name) {
  21516. for (var index = 0; index < this.animationGroups.length; index++) {
  21517. if (this.animationGroups[index].name === name) {
  21518. return this.animationGroups[index];
  21519. }
  21520. }
  21521. return null;
  21522. };
  21523. /**
  21524. * get a material using its id
  21525. * @param {string} the material's ID
  21526. * @return {BABYLON.Material|null} the material or null if none found.
  21527. */
  21528. Scene.prototype.getMaterialByID = function (id) {
  21529. for (var index = 0; index < this.materials.length; index++) {
  21530. if (this.materials[index].id === id) {
  21531. return this.materials[index];
  21532. }
  21533. }
  21534. return null;
  21535. };
  21536. /**
  21537. * get a material using its name
  21538. * @param {string} the material's name
  21539. * @return {BABYLON.Material|null} the material or null if none found.
  21540. */
  21541. Scene.prototype.getMaterialByName = function (name) {
  21542. for (var index = 0; index < this.materials.length; index++) {
  21543. if (this.materials[index].name === name) {
  21544. return this.materials[index];
  21545. }
  21546. }
  21547. return null;
  21548. };
  21549. Scene.prototype.getLensFlareSystemByName = function (name) {
  21550. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21551. if (this.lensFlareSystems[index].name === name) {
  21552. return this.lensFlareSystems[index];
  21553. }
  21554. }
  21555. return null;
  21556. };
  21557. Scene.prototype.getLensFlareSystemByID = function (id) {
  21558. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21559. if (this.lensFlareSystems[index].id === id) {
  21560. return this.lensFlareSystems[index];
  21561. }
  21562. }
  21563. return null;
  21564. };
  21565. Scene.prototype.getCameraByID = function (id) {
  21566. for (var index = 0; index < this.cameras.length; index++) {
  21567. if (this.cameras[index].id === id) {
  21568. return this.cameras[index];
  21569. }
  21570. }
  21571. return null;
  21572. };
  21573. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21574. for (var index = 0; index < this.cameras.length; index++) {
  21575. if (this.cameras[index].uniqueId === uniqueId) {
  21576. return this.cameras[index];
  21577. }
  21578. }
  21579. return null;
  21580. };
  21581. /**
  21582. * get a camera using its name
  21583. * @param {string} the camera's name
  21584. * @return {BABYLON.Camera|null} the camera or null if none found.
  21585. */
  21586. Scene.prototype.getCameraByName = function (name) {
  21587. for (var index = 0; index < this.cameras.length; index++) {
  21588. if (this.cameras[index].name === name) {
  21589. return this.cameras[index];
  21590. }
  21591. }
  21592. return null;
  21593. };
  21594. /**
  21595. * get a bone using its id
  21596. * @param {string} the bone's id
  21597. * @return {BABYLON.Bone|null} the bone or null if not found
  21598. */
  21599. Scene.prototype.getBoneByID = function (id) {
  21600. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21601. var skeleton = this.skeletons[skeletonIndex];
  21602. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21603. if (skeleton.bones[boneIndex].id === id) {
  21604. return skeleton.bones[boneIndex];
  21605. }
  21606. }
  21607. }
  21608. return null;
  21609. };
  21610. /**
  21611. * get a bone using its id
  21612. * @param {string} the bone's name
  21613. * @return {BABYLON.Bone|null} the bone or null if not found
  21614. */
  21615. Scene.prototype.getBoneByName = function (name) {
  21616. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21617. var skeleton = this.skeletons[skeletonIndex];
  21618. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21619. if (skeleton.bones[boneIndex].name === name) {
  21620. return skeleton.bones[boneIndex];
  21621. }
  21622. }
  21623. }
  21624. return null;
  21625. };
  21626. /**
  21627. * get a light node using its name
  21628. * @param {string} the light's name
  21629. * @return {BABYLON.Light|null} the light or null if none found.
  21630. */
  21631. Scene.prototype.getLightByName = function (name) {
  21632. for (var index = 0; index < this.lights.length; index++) {
  21633. if (this.lights[index].name === name) {
  21634. return this.lights[index];
  21635. }
  21636. }
  21637. return null;
  21638. };
  21639. /**
  21640. * get a light node using its ID
  21641. * @param {string} the light's id
  21642. * @return {BABYLON.Light|null} the light or null if none found.
  21643. */
  21644. Scene.prototype.getLightByID = function (id) {
  21645. for (var index = 0; index < this.lights.length; index++) {
  21646. if (this.lights[index].id === id) {
  21647. return this.lights[index];
  21648. }
  21649. }
  21650. return null;
  21651. };
  21652. /**
  21653. * get a light node using its scene-generated unique ID
  21654. * @param {number} the light's unique id
  21655. * @return {BABYLON.Light|null} the light or null if none found.
  21656. */
  21657. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21658. for (var index = 0; index < this.lights.length; index++) {
  21659. if (this.lights[index].uniqueId === uniqueId) {
  21660. return this.lights[index];
  21661. }
  21662. }
  21663. return null;
  21664. };
  21665. /**
  21666. * get a particle system by id
  21667. * @param id {number} the particle system id
  21668. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21669. */
  21670. Scene.prototype.getParticleSystemByID = function (id) {
  21671. for (var index = 0; index < this.particleSystems.length; index++) {
  21672. if (this.particleSystems[index].id === id) {
  21673. return this.particleSystems[index];
  21674. }
  21675. }
  21676. return null;
  21677. };
  21678. /**
  21679. * get a geometry using its ID
  21680. * @param {string} the geometry's id
  21681. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21682. */
  21683. Scene.prototype.getGeometryByID = function (id) {
  21684. for (var index = 0; index < this._geometries.length; index++) {
  21685. if (this._geometries[index].id === id) {
  21686. return this._geometries[index];
  21687. }
  21688. }
  21689. return null;
  21690. };
  21691. /**
  21692. * add a new geometry to this scene.
  21693. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21694. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21695. * @return {boolean} was the geometry added or not
  21696. */
  21697. Scene.prototype.pushGeometry = function (geometry, force) {
  21698. if (!force && this.getGeometryByID(geometry.id)) {
  21699. return false;
  21700. }
  21701. this._geometries.push(geometry);
  21702. //notify the collision coordinator
  21703. if (this.collisionCoordinator) {
  21704. this.collisionCoordinator.onGeometryAdded(geometry);
  21705. }
  21706. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21707. return true;
  21708. };
  21709. /**
  21710. * Removes an existing geometry
  21711. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21712. * @return {boolean} was the geometry removed or not
  21713. */
  21714. Scene.prototype.removeGeometry = function (geometry) {
  21715. var index = this._geometries.indexOf(geometry);
  21716. if (index > -1) {
  21717. this._geometries.splice(index, 1);
  21718. //notify the collision coordinator
  21719. if (this.collisionCoordinator) {
  21720. this.collisionCoordinator.onGeometryDeleted(geometry);
  21721. }
  21722. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21723. return true;
  21724. }
  21725. return false;
  21726. };
  21727. Scene.prototype.getGeometries = function () {
  21728. return this._geometries;
  21729. };
  21730. /**
  21731. * Get the first added mesh found of a given ID
  21732. * @param {string} id - the id to search for
  21733. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21734. */
  21735. Scene.prototype.getMeshByID = function (id) {
  21736. for (var index = 0; index < this.meshes.length; index++) {
  21737. if (this.meshes[index].id === id) {
  21738. return this.meshes[index];
  21739. }
  21740. }
  21741. return null;
  21742. };
  21743. Scene.prototype.getMeshesByID = function (id) {
  21744. return this.meshes.filter(function (m) {
  21745. return m.id === id;
  21746. });
  21747. };
  21748. /**
  21749. * Get the first added transform node found of a given ID
  21750. * @param {string} id - the id to search for
  21751. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21752. */
  21753. Scene.prototype.getTransformNodeByID = function (id) {
  21754. for (var index = 0; index < this.transformNodes.length; index++) {
  21755. if (this.transformNodes[index].id === id) {
  21756. return this.transformNodes[index];
  21757. }
  21758. }
  21759. return null;
  21760. };
  21761. Scene.prototype.getTransformNodesByID = function (id) {
  21762. return this.transformNodes.filter(function (m) {
  21763. return m.id === id;
  21764. });
  21765. };
  21766. /**
  21767. * Get a mesh with its auto-generated unique id
  21768. * @param {number} uniqueId - the unique id to search for
  21769. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21770. */
  21771. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21772. for (var index = 0; index < this.meshes.length; index++) {
  21773. if (this.meshes[index].uniqueId === uniqueId) {
  21774. return this.meshes[index];
  21775. }
  21776. }
  21777. return null;
  21778. };
  21779. /**
  21780. * Get a the last added mesh found of a given ID
  21781. * @param {string} id - the id to search for
  21782. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21783. */
  21784. Scene.prototype.getLastMeshByID = function (id) {
  21785. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21786. if (this.meshes[index].id === id) {
  21787. return this.meshes[index];
  21788. }
  21789. }
  21790. return null;
  21791. };
  21792. /**
  21793. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21794. * @param {string} id - the id to search for
  21795. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21796. */
  21797. Scene.prototype.getLastEntryByID = function (id) {
  21798. var index;
  21799. for (index = this.meshes.length - 1; index >= 0; index--) {
  21800. if (this.meshes[index].id === id) {
  21801. return this.meshes[index];
  21802. }
  21803. }
  21804. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21805. if (this.transformNodes[index].id === id) {
  21806. return this.transformNodes[index];
  21807. }
  21808. }
  21809. for (index = this.cameras.length - 1; index >= 0; index--) {
  21810. if (this.cameras[index].id === id) {
  21811. return this.cameras[index];
  21812. }
  21813. }
  21814. for (index = this.lights.length - 1; index >= 0; index--) {
  21815. if (this.lights[index].id === id) {
  21816. return this.lights[index];
  21817. }
  21818. }
  21819. return null;
  21820. };
  21821. Scene.prototype.getNodeByID = function (id) {
  21822. var mesh = this.getMeshByID(id);
  21823. if (mesh) {
  21824. return mesh;
  21825. }
  21826. var light = this.getLightByID(id);
  21827. if (light) {
  21828. return light;
  21829. }
  21830. var camera = this.getCameraByID(id);
  21831. if (camera) {
  21832. return camera;
  21833. }
  21834. var bone = this.getBoneByID(id);
  21835. return bone;
  21836. };
  21837. Scene.prototype.getNodeByName = function (name) {
  21838. var mesh = this.getMeshByName(name);
  21839. if (mesh) {
  21840. return mesh;
  21841. }
  21842. var light = this.getLightByName(name);
  21843. if (light) {
  21844. return light;
  21845. }
  21846. var camera = this.getCameraByName(name);
  21847. if (camera) {
  21848. return camera;
  21849. }
  21850. var bone = this.getBoneByName(name);
  21851. return bone;
  21852. };
  21853. Scene.prototype.getMeshByName = function (name) {
  21854. for (var index = 0; index < this.meshes.length; index++) {
  21855. if (this.meshes[index].name === name) {
  21856. return this.meshes[index];
  21857. }
  21858. }
  21859. return null;
  21860. };
  21861. Scene.prototype.getTransformNodeByName = function (name) {
  21862. for (var index = 0; index < this.transformNodes.length; index++) {
  21863. if (this.transformNodes[index].name === name) {
  21864. return this.transformNodes[index];
  21865. }
  21866. }
  21867. return null;
  21868. };
  21869. Scene.prototype.getSoundByName = function (name) {
  21870. var index;
  21871. if (BABYLON.AudioEngine) {
  21872. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21873. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21874. return this.mainSoundTrack.soundCollection[index];
  21875. }
  21876. }
  21877. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21878. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21879. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21880. return this.soundTracks[sdIndex].soundCollection[index];
  21881. }
  21882. }
  21883. }
  21884. }
  21885. return null;
  21886. };
  21887. Scene.prototype.getLastSkeletonByID = function (id) {
  21888. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21889. if (this.skeletons[index].id === id) {
  21890. return this.skeletons[index];
  21891. }
  21892. }
  21893. return null;
  21894. };
  21895. Scene.prototype.getSkeletonById = function (id) {
  21896. for (var index = 0; index < this.skeletons.length; index++) {
  21897. if (this.skeletons[index].id === id) {
  21898. return this.skeletons[index];
  21899. }
  21900. }
  21901. return null;
  21902. };
  21903. Scene.prototype.getSkeletonByName = function (name) {
  21904. for (var index = 0; index < this.skeletons.length; index++) {
  21905. if (this.skeletons[index].name === name) {
  21906. return this.skeletons[index];
  21907. }
  21908. }
  21909. return null;
  21910. };
  21911. Scene.prototype.getMorphTargetManagerById = function (id) {
  21912. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21913. if (this.morphTargetManagers[index].uniqueId === id) {
  21914. return this.morphTargetManagers[index];
  21915. }
  21916. }
  21917. return null;
  21918. };
  21919. Scene.prototype.isActiveMesh = function (mesh) {
  21920. return (this._activeMeshes.indexOf(mesh) !== -1);
  21921. };
  21922. /**
  21923. * Return a the first highlight layer of the scene with a given name.
  21924. * @param name The name of the highlight layer to look for.
  21925. * @return The highlight layer if found otherwise null.
  21926. */
  21927. Scene.prototype.getHighlightLayerByName = function (name) {
  21928. for (var index = 0; index < this.highlightLayers.length; index++) {
  21929. if (this.highlightLayers[index].name === name) {
  21930. return this.highlightLayers[index];
  21931. }
  21932. }
  21933. return null;
  21934. };
  21935. Object.defineProperty(Scene.prototype, "uid", {
  21936. /**
  21937. * Return a unique id as a string which can serve as an identifier for the scene
  21938. */
  21939. get: function () {
  21940. if (!this._uid) {
  21941. this._uid = BABYLON.Tools.RandomId();
  21942. }
  21943. return this._uid;
  21944. },
  21945. enumerable: true,
  21946. configurable: true
  21947. });
  21948. /**
  21949. * Add an externaly attached data from its key.
  21950. * This method call will fail and return false, if such key already exists.
  21951. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21952. * @param key the unique key that identifies the data
  21953. * @param data the data object to associate to the key for this Engine instance
  21954. * @return true if no such key were already present and the data was added successfully, false otherwise
  21955. */
  21956. Scene.prototype.addExternalData = function (key, data) {
  21957. if (!this._externalData) {
  21958. this._externalData = new BABYLON.StringDictionary();
  21959. }
  21960. return this._externalData.add(key, data);
  21961. };
  21962. /**
  21963. * Get an externaly attached data from its key
  21964. * @param key the unique key that identifies the data
  21965. * @return the associated data, if present (can be null), or undefined if not present
  21966. */
  21967. Scene.prototype.getExternalData = function (key) {
  21968. if (!this._externalData) {
  21969. return null;
  21970. }
  21971. return this._externalData.get(key);
  21972. };
  21973. /**
  21974. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21975. * @param key the unique key that identifies the data
  21976. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21977. * @return the associated data, can be null if the factory returned null.
  21978. */
  21979. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21980. if (!this._externalData) {
  21981. this._externalData = new BABYLON.StringDictionary();
  21982. }
  21983. return this._externalData.getOrAddWithFactory(key, factory);
  21984. };
  21985. /**
  21986. * Remove an externaly attached data from the Engine instance
  21987. * @param key the unique key that identifies the data
  21988. * @return true if the data was successfully removed, false if it doesn't exist
  21989. */
  21990. Scene.prototype.removeExternalData = function (key) {
  21991. return this._externalData.remove(key);
  21992. };
  21993. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21994. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21995. if (mesh.showSubMeshesBoundingBox) {
  21996. var boundingInfo = subMesh.getBoundingInfo();
  21997. if (boundingInfo !== null && boundingInfo !== undefined) {
  21998. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21999. }
  22000. }
  22001. var material = subMesh.getMaterial();
  22002. if (material !== null && material !== undefined) {
  22003. // Render targets
  22004. if (material.getRenderTargetTextures !== undefined) {
  22005. if (this._processedMaterials.indexOf(material) === -1) {
  22006. this._processedMaterials.push(material);
  22007. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22008. }
  22009. }
  22010. // Dispatch
  22011. this._activeIndices.addCount(subMesh.indexCount, false);
  22012. this._renderingManager.dispatch(subMesh, mesh, material);
  22013. }
  22014. }
  22015. };
  22016. Scene.prototype._isInIntermediateRendering = function () {
  22017. return this._intermediateRendering;
  22018. };
  22019. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22020. this._activeMeshCandidateProvider = provider;
  22021. };
  22022. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22023. return this._activeMeshCandidateProvider;
  22024. };
  22025. /**
  22026. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22027. */
  22028. Scene.prototype.freezeActiveMeshes = function () {
  22029. this._evaluateActiveMeshes();
  22030. this._activeMeshesFrozen = true;
  22031. return this;
  22032. };
  22033. /**
  22034. * Use this function to restart evaluating active meshes on every frame
  22035. */
  22036. Scene.prototype.unfreezeActiveMeshes = function () {
  22037. this._activeMeshesFrozen = false;
  22038. return this;
  22039. };
  22040. Scene.prototype._evaluateActiveMeshes = function () {
  22041. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22042. return;
  22043. }
  22044. if (!this.activeCamera) {
  22045. return;
  22046. }
  22047. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22048. this.activeCamera._activeMeshes.reset();
  22049. this._activeMeshes.reset();
  22050. this._renderingManager.reset();
  22051. this._processedMaterials.reset();
  22052. this._activeParticleSystems.reset();
  22053. this._activeSkeletons.reset();
  22054. this._softwareSkinnedMeshes.reset();
  22055. if (this._boundingBoxRenderer) {
  22056. this._boundingBoxRenderer.reset();
  22057. }
  22058. // Meshes
  22059. var meshes;
  22060. var len;
  22061. var checkIsEnabled = true;
  22062. // Determine mesh candidates
  22063. if (this._activeMeshCandidateProvider !== undefined) {
  22064. // Use _activeMeshCandidateProvider
  22065. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22066. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22067. if (meshes !== undefined) {
  22068. len = meshes.length;
  22069. }
  22070. else {
  22071. len = 0;
  22072. }
  22073. }
  22074. else if (this._selectionOctree !== undefined) {
  22075. // Octree
  22076. var selection = this._selectionOctree.select(this._frustumPlanes);
  22077. meshes = selection.data;
  22078. len = selection.length;
  22079. }
  22080. else {
  22081. // Full scene traversal
  22082. len = this.meshes.length;
  22083. meshes = this.meshes;
  22084. }
  22085. // Check each mesh
  22086. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22087. mesh = meshes[meshIndex];
  22088. if (mesh.isBlocked) {
  22089. continue;
  22090. }
  22091. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22092. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22093. continue;
  22094. }
  22095. mesh.computeWorldMatrix();
  22096. // Intersections
  22097. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22098. this._meshesForIntersections.pushNoDuplicate(mesh);
  22099. }
  22100. // Switch to current LOD
  22101. meshLOD = mesh.getLOD(this.activeCamera);
  22102. if (meshLOD === undefined || meshLOD === null) {
  22103. continue;
  22104. }
  22105. mesh._preActivate();
  22106. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22107. this._activeMeshes.push(mesh);
  22108. this.activeCamera._activeMeshes.push(mesh);
  22109. mesh._activate(this._renderId);
  22110. if (meshLOD !== mesh) {
  22111. meshLOD._activate(this._renderId);
  22112. }
  22113. this._activeMesh(mesh, meshLOD);
  22114. }
  22115. }
  22116. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22117. // Particle systems
  22118. if (this.particlesEnabled) {
  22119. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22120. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22121. var particleSystem = this.particleSystems[particleIndex];
  22122. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22123. continue;
  22124. }
  22125. var emitter = particleSystem.emitter;
  22126. if (!emitter.position || emitter.isEnabled()) {
  22127. this._activeParticleSystems.push(particleSystem);
  22128. particleSystem.animate();
  22129. this._renderingManager.dispatchParticles(particleSystem);
  22130. }
  22131. }
  22132. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22133. }
  22134. };
  22135. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22136. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22137. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22138. mesh.skeleton.prepare();
  22139. }
  22140. if (!mesh.computeBonesUsingShaders) {
  22141. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22142. }
  22143. }
  22144. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22145. var boundingInfo = sourceMesh.getBoundingInfo();
  22146. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22147. }
  22148. if (mesh !== undefined && mesh !== null
  22149. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22150. // Submeshes Octrees
  22151. var len;
  22152. var subMeshes;
  22153. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22154. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22155. len = intersections.length;
  22156. subMeshes = intersections.data;
  22157. }
  22158. else {
  22159. subMeshes = mesh.subMeshes;
  22160. len = subMeshes.length;
  22161. }
  22162. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22163. subMesh = subMeshes[subIndex];
  22164. this._evaluateSubMesh(subMesh, mesh);
  22165. }
  22166. }
  22167. };
  22168. Scene.prototype.updateTransformMatrix = function (force) {
  22169. if (!this.activeCamera) {
  22170. return;
  22171. }
  22172. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22173. };
  22174. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22175. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22176. };
  22177. Scene.prototype._renderForCamera = function (camera) {
  22178. if (camera && camera._skipRendering) {
  22179. return;
  22180. }
  22181. var engine = this._engine;
  22182. this.activeCamera = camera;
  22183. if (!this.activeCamera)
  22184. throw new Error("Active camera not set");
  22185. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22186. // Viewport
  22187. engine.setViewport(this.activeCamera.viewport);
  22188. // Camera
  22189. this.resetCachedMaterial();
  22190. this._renderId++;
  22191. this.activeCamera.update();
  22192. this.updateTransformMatrix();
  22193. if (camera._alternateCamera) {
  22194. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22195. this._alternateRendering = true;
  22196. }
  22197. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22198. // Meshes
  22199. this._evaluateActiveMeshes();
  22200. // Software skinning
  22201. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22202. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22203. mesh.applySkeleton(mesh.skeleton);
  22204. }
  22205. // Render targets
  22206. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22207. var needsRestoreFrameBuffer = false;
  22208. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22209. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22210. }
  22211. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22212. this._intermediateRendering = true;
  22213. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22214. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22215. var renderTarget = this._renderTargets.data[renderIndex];
  22216. if (renderTarget._shouldRender()) {
  22217. this._renderId++;
  22218. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22219. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22220. }
  22221. }
  22222. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22223. this._intermediateRendering = false;
  22224. this._renderId++;
  22225. needsRestoreFrameBuffer = true; // Restore back buffer
  22226. }
  22227. // Render HighlightLayer Texture
  22228. var stencilState = this._engine.getStencilBuffer();
  22229. var renderhighlights = false;
  22230. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22231. this._intermediateRendering = true;
  22232. for (var i = 0; i < this.highlightLayers.length; i++) {
  22233. var highlightLayer = this.highlightLayers[i];
  22234. if (highlightLayer.shouldRender() &&
  22235. (!highlightLayer.camera ||
  22236. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22237. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22238. renderhighlights = true;
  22239. var renderTarget = highlightLayer._mainTexture;
  22240. if (renderTarget._shouldRender()) {
  22241. this._renderId++;
  22242. renderTarget.render(false, false);
  22243. needsRestoreFrameBuffer = true;
  22244. }
  22245. }
  22246. }
  22247. this._intermediateRendering = false;
  22248. this._renderId++;
  22249. }
  22250. if (needsRestoreFrameBuffer) {
  22251. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22252. }
  22253. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22254. // Prepare Frame
  22255. this.postProcessManager._prepareFrame();
  22256. // Backgrounds
  22257. var layerIndex;
  22258. var layer;
  22259. if (this.layers.length) {
  22260. engine.setDepthBuffer(false);
  22261. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22262. layer = this.layers[layerIndex];
  22263. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22264. layer.render();
  22265. }
  22266. }
  22267. engine.setDepthBuffer(true);
  22268. }
  22269. // Activate HighlightLayer stencil
  22270. if (renderhighlights) {
  22271. this._engine.setStencilBuffer(true);
  22272. }
  22273. // Render
  22274. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22275. this._renderingManager.render(null, null, true, true);
  22276. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22277. // Restore HighlightLayer stencil
  22278. if (renderhighlights) {
  22279. this._engine.setStencilBuffer(stencilState);
  22280. }
  22281. // Bounding boxes
  22282. if (this._boundingBoxRenderer) {
  22283. this._boundingBoxRenderer.render();
  22284. }
  22285. // Lens flares
  22286. if (this.lensFlaresEnabled) {
  22287. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22288. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22289. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22290. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22291. lensFlareSystem.render();
  22292. }
  22293. }
  22294. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22295. }
  22296. // Foregrounds
  22297. if (this.layers.length) {
  22298. engine.setDepthBuffer(false);
  22299. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22300. layer = this.layers[layerIndex];
  22301. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22302. layer.render();
  22303. }
  22304. }
  22305. engine.setDepthBuffer(true);
  22306. }
  22307. // Highlight Layer
  22308. if (renderhighlights) {
  22309. engine.setDepthBuffer(false);
  22310. for (var i = 0; i < this.highlightLayers.length; i++) {
  22311. if (this.highlightLayers[i].shouldRender()) {
  22312. this.highlightLayers[i].render();
  22313. }
  22314. }
  22315. engine.setDepthBuffer(true);
  22316. }
  22317. // Finalize frame
  22318. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22319. // Reset some special arrays
  22320. this._renderTargets.reset();
  22321. this._alternateRendering = false;
  22322. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22323. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22324. };
  22325. Scene.prototype._processSubCameras = function (camera) {
  22326. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22327. this._renderForCamera(camera);
  22328. return;
  22329. }
  22330. // Update camera
  22331. if (this.activeCamera) {
  22332. this.activeCamera.update();
  22333. }
  22334. // rig cameras
  22335. for (var index = 0; index < camera._rigCameras.length; index++) {
  22336. this._renderForCamera(camera._rigCameras[index]);
  22337. }
  22338. this.activeCamera = camera;
  22339. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22340. };
  22341. Scene.prototype._checkIntersections = function () {
  22342. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22343. var sourceMesh = this._meshesForIntersections.data[index];
  22344. if (!sourceMesh.actionManager) {
  22345. continue;
  22346. }
  22347. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22348. var action = sourceMesh.actionManager.actions[actionIndex];
  22349. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22350. var parameters = action.getTriggerParameter();
  22351. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22352. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22353. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22354. if (areIntersecting && currentIntersectionInProgress === -1) {
  22355. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22356. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22357. sourceMesh._intersectionsInProgress.push(otherMesh);
  22358. }
  22359. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22360. sourceMesh._intersectionsInProgress.push(otherMesh);
  22361. }
  22362. }
  22363. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22364. //They intersected, and now they don't.
  22365. //is this trigger an exit trigger? execute an event.
  22366. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22367. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22368. }
  22369. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22370. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22371. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22372. }
  22373. }
  22374. }
  22375. }
  22376. }
  22377. };
  22378. Scene.prototype.render = function () {
  22379. if (this.isDisposed) {
  22380. return;
  22381. }
  22382. this._activeParticles.fetchNewFrame();
  22383. this._totalVertices.fetchNewFrame();
  22384. this._activeIndices.fetchNewFrame();
  22385. this._activeBones.fetchNewFrame();
  22386. this._meshesForIntersections.reset();
  22387. this.resetCachedMaterial();
  22388. this.onBeforeAnimationsObservable.notifyObservers(this);
  22389. // Actions
  22390. if (this.actionManager) {
  22391. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22392. }
  22393. //Simplification Queue
  22394. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22395. this.simplificationQueue.executeNext();
  22396. }
  22397. if (this._engine.isDeterministicLockStep()) {
  22398. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22399. var defaultFPS = (60.0 / 1000.0);
  22400. var defaultFrameTime = 1000 / 60; // frame time in MS
  22401. if (this._physicsEngine) {
  22402. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22403. }
  22404. var stepsTaken = 0;
  22405. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22406. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22407. internalSteps = Math.min(internalSteps, maxSubSteps);
  22408. do {
  22409. this.onBeforeStepObservable.notifyObservers(this);
  22410. // Animations
  22411. this._animationRatio = defaultFrameTime * defaultFPS;
  22412. this._animate();
  22413. this.onAfterAnimationsObservable.notifyObservers(this);
  22414. // Physics
  22415. if (this._physicsEngine) {
  22416. this.onBeforePhysicsObservable.notifyObservers(this);
  22417. this._physicsEngine._step(defaultFrameTime / 1000);
  22418. this.onAfterPhysicsObservable.notifyObservers(this);
  22419. }
  22420. this.onAfterStepObservable.notifyObservers(this);
  22421. this._currentStepId++;
  22422. stepsTaken++;
  22423. deltaTime -= defaultFrameTime;
  22424. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22425. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22426. }
  22427. else {
  22428. // Animations
  22429. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22430. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22431. this._animate();
  22432. this.onAfterAnimationsObservable.notifyObservers(this);
  22433. // Physics
  22434. if (this._physicsEngine) {
  22435. this.onBeforePhysicsObservable.notifyObservers(this);
  22436. this._physicsEngine._step(deltaTime / 1000.0);
  22437. this.onAfterPhysicsObservable.notifyObservers(this);
  22438. }
  22439. }
  22440. // update gamepad manager
  22441. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22442. this._gamepadManager._checkGamepadsStatus();
  22443. }
  22444. // Before render
  22445. this.onBeforeRenderObservable.notifyObservers(this);
  22446. // Customs render targets
  22447. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22448. var engine = this.getEngine();
  22449. var currentActiveCamera = this.activeCamera;
  22450. if (this.renderTargetsEnabled) {
  22451. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22452. this._intermediateRendering = true;
  22453. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22454. var renderTarget = this.customRenderTargets[customIndex];
  22455. if (renderTarget._shouldRender()) {
  22456. this._renderId++;
  22457. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22458. if (!this.activeCamera)
  22459. throw new Error("Active camera not set");
  22460. // Viewport
  22461. engine.setViewport(this.activeCamera.viewport);
  22462. // Camera
  22463. this.updateTransformMatrix();
  22464. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22465. }
  22466. }
  22467. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22468. this._intermediateRendering = false;
  22469. this._renderId++;
  22470. }
  22471. // Restore back buffer
  22472. if (this.customRenderTargets.length > 0) {
  22473. engine.restoreDefaultFramebuffer();
  22474. }
  22475. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22476. this.activeCamera = currentActiveCamera;
  22477. // Procedural textures
  22478. if (this.proceduralTexturesEnabled) {
  22479. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22480. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22481. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22482. if (proceduralTexture._shouldRender()) {
  22483. proceduralTexture.render();
  22484. }
  22485. }
  22486. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22487. }
  22488. // Clear
  22489. if (this.autoClearDepthAndStencil || this.autoClear) {
  22490. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22491. }
  22492. // Shadows
  22493. if (this.shadowsEnabled) {
  22494. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22495. var light = this.lights[lightIndex];
  22496. var shadowGenerator = light.getShadowGenerator();
  22497. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22498. var shadowMap = (shadowGenerator.getShadowMap());
  22499. if (this.textures.indexOf(shadowMap) !== -1) {
  22500. this._renderTargets.push(shadowMap);
  22501. }
  22502. }
  22503. }
  22504. }
  22505. // Depth renderer
  22506. if (this._depthRenderer) {
  22507. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22508. }
  22509. // Geometry renderer
  22510. if (this._geometryBufferRenderer) {
  22511. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22512. }
  22513. // RenderPipeline
  22514. if (this._postProcessRenderPipelineManager) {
  22515. this._postProcessRenderPipelineManager.update();
  22516. }
  22517. // Multi-cameras?
  22518. if (this.activeCameras.length > 0) {
  22519. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22520. if (cameraIndex > 0) {
  22521. this._engine.clear(null, false, true, true);
  22522. }
  22523. this._processSubCameras(this.activeCameras[cameraIndex]);
  22524. }
  22525. }
  22526. else {
  22527. if (!this.activeCamera) {
  22528. throw new Error("No camera defined");
  22529. }
  22530. this._processSubCameras(this.activeCamera);
  22531. }
  22532. // Intersection checks
  22533. this._checkIntersections();
  22534. // Update the audio listener attached to the camera
  22535. if (BABYLON.AudioEngine) {
  22536. this._updateAudioParameters();
  22537. }
  22538. // After render
  22539. if (this.afterRender) {
  22540. this.afterRender();
  22541. }
  22542. this.onAfterRenderObservable.notifyObservers(this);
  22543. // Cleaning
  22544. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22545. var data = this._toBeDisposed.data[index];
  22546. if (data) {
  22547. data.dispose();
  22548. }
  22549. this._toBeDisposed[index] = null;
  22550. }
  22551. this._toBeDisposed.reset();
  22552. if (this.dumpNextRenderTargets) {
  22553. this.dumpNextRenderTargets = false;
  22554. }
  22555. this._activeBones.addCount(0, true);
  22556. this._activeIndices.addCount(0, true);
  22557. this._activeParticles.addCount(0, true);
  22558. };
  22559. Scene.prototype._updateAudioParameters = function () {
  22560. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22561. return;
  22562. }
  22563. var listeningCamera;
  22564. var audioEngine = BABYLON.Engine.audioEngine;
  22565. if (this.activeCameras.length > 0) {
  22566. listeningCamera = this.activeCameras[0];
  22567. }
  22568. else {
  22569. listeningCamera = this.activeCamera;
  22570. }
  22571. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22572. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22573. // for VR cameras
  22574. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22575. listeningCamera = listeningCamera.rigCameras[0];
  22576. }
  22577. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22578. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22579. cameraDirection.normalize();
  22580. // To avoid some errors on GearVR
  22581. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22582. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22583. }
  22584. var i;
  22585. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22586. var sound = this.mainSoundTrack.soundCollection[i];
  22587. if (sound.useCustomAttenuation) {
  22588. sound.updateDistanceFromListener();
  22589. }
  22590. }
  22591. for (i = 0; i < this.soundTracks.length; i++) {
  22592. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22593. sound = this.soundTracks[i].soundCollection[j];
  22594. if (sound.useCustomAttenuation) {
  22595. sound.updateDistanceFromListener();
  22596. }
  22597. }
  22598. }
  22599. }
  22600. };
  22601. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22602. // Audio
  22603. get: function () {
  22604. return this._audioEnabled;
  22605. },
  22606. set: function (value) {
  22607. this._audioEnabled = value;
  22608. if (BABYLON.AudioEngine) {
  22609. if (this._audioEnabled) {
  22610. this._enableAudio();
  22611. }
  22612. else {
  22613. this._disableAudio();
  22614. }
  22615. }
  22616. },
  22617. enumerable: true,
  22618. configurable: true
  22619. });
  22620. Scene.prototype._disableAudio = function () {
  22621. var i;
  22622. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22623. this.mainSoundTrack.soundCollection[i].pause();
  22624. }
  22625. for (i = 0; i < this.soundTracks.length; i++) {
  22626. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22627. this.soundTracks[i].soundCollection[j].pause();
  22628. }
  22629. }
  22630. };
  22631. Scene.prototype._enableAudio = function () {
  22632. var i;
  22633. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22634. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22635. this.mainSoundTrack.soundCollection[i].play();
  22636. }
  22637. }
  22638. for (i = 0; i < this.soundTracks.length; i++) {
  22639. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22640. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22641. this.soundTracks[i].soundCollection[j].play();
  22642. }
  22643. }
  22644. }
  22645. };
  22646. Object.defineProperty(Scene.prototype, "headphone", {
  22647. get: function () {
  22648. return this._headphone;
  22649. },
  22650. set: function (value) {
  22651. this._headphone = value;
  22652. if (BABYLON.AudioEngine) {
  22653. if (this._headphone) {
  22654. this._switchAudioModeForHeadphones();
  22655. }
  22656. else {
  22657. this._switchAudioModeForNormalSpeakers();
  22658. }
  22659. }
  22660. },
  22661. enumerable: true,
  22662. configurable: true
  22663. });
  22664. Scene.prototype._switchAudioModeForHeadphones = function () {
  22665. this.mainSoundTrack.switchPanningModelToHRTF();
  22666. for (var i = 0; i < this.soundTracks.length; i++) {
  22667. this.soundTracks[i].switchPanningModelToHRTF();
  22668. }
  22669. };
  22670. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22671. this.mainSoundTrack.switchPanningModelToEqualPower();
  22672. for (var i = 0; i < this.soundTracks.length; i++) {
  22673. this.soundTracks[i].switchPanningModelToEqualPower();
  22674. }
  22675. };
  22676. Scene.prototype.enableDepthRenderer = function () {
  22677. if (this._depthRenderer) {
  22678. return this._depthRenderer;
  22679. }
  22680. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22681. return this._depthRenderer;
  22682. };
  22683. Scene.prototype.disableDepthRenderer = function () {
  22684. if (!this._depthRenderer) {
  22685. return;
  22686. }
  22687. this._depthRenderer.dispose();
  22688. this._depthRenderer = null;
  22689. };
  22690. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22691. if (ratio === void 0) { ratio = 1; }
  22692. if (this._geometryBufferRenderer) {
  22693. return this._geometryBufferRenderer;
  22694. }
  22695. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22696. if (!this._geometryBufferRenderer.isSupported) {
  22697. this._geometryBufferRenderer = null;
  22698. }
  22699. return this._geometryBufferRenderer;
  22700. };
  22701. Scene.prototype.disableGeometryBufferRenderer = function () {
  22702. if (!this._geometryBufferRenderer) {
  22703. return;
  22704. }
  22705. this._geometryBufferRenderer.dispose();
  22706. this._geometryBufferRenderer = null;
  22707. };
  22708. Scene.prototype.freezeMaterials = function () {
  22709. for (var i = 0; i < this.materials.length; i++) {
  22710. this.materials[i].freeze();
  22711. }
  22712. };
  22713. Scene.prototype.unfreezeMaterials = function () {
  22714. for (var i = 0; i < this.materials.length; i++) {
  22715. this.materials[i].unfreeze();
  22716. }
  22717. };
  22718. Scene.prototype.dispose = function () {
  22719. this.beforeRender = null;
  22720. this.afterRender = null;
  22721. this.skeletons = [];
  22722. this.morphTargetManagers = [];
  22723. this.importedMeshesFiles = new Array();
  22724. this.stopAllAnimations();
  22725. this.resetCachedMaterial();
  22726. if (this._depthRenderer) {
  22727. this._depthRenderer.dispose();
  22728. }
  22729. if (this._gamepadManager) {
  22730. this._gamepadManager.dispose();
  22731. this._gamepadManager = null;
  22732. }
  22733. // Smart arrays
  22734. if (this.activeCamera) {
  22735. this.activeCamera._activeMeshes.dispose();
  22736. this.activeCamera = null;
  22737. }
  22738. this._activeMeshes.dispose();
  22739. this._renderingManager.dispose();
  22740. this._processedMaterials.dispose();
  22741. this._activeParticleSystems.dispose();
  22742. this._activeSkeletons.dispose();
  22743. this._softwareSkinnedMeshes.dispose();
  22744. this._renderTargets.dispose();
  22745. if (this._boundingBoxRenderer) {
  22746. this._boundingBoxRenderer.dispose();
  22747. }
  22748. this._meshesForIntersections.dispose();
  22749. this._toBeDisposed.dispose();
  22750. // Abort active requests
  22751. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22752. var request = _a[_i];
  22753. request.abort();
  22754. }
  22755. // Debug layer
  22756. if (this._debugLayer) {
  22757. this._debugLayer.hide();
  22758. }
  22759. // Events
  22760. this.onDisposeObservable.notifyObservers(this);
  22761. this.onDisposeObservable.clear();
  22762. this.onBeforeRenderObservable.clear();
  22763. this.onAfterRenderObservable.clear();
  22764. this.OnBeforeRenderTargetsRenderObservable.clear();
  22765. this.OnAfterRenderTargetsRenderObservable.clear();
  22766. this.onAfterStepObservable.clear();
  22767. this.onBeforeStepObservable.clear();
  22768. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22769. this.onAfterActiveMeshesEvaluationObservable.clear();
  22770. this.onBeforeParticlesRenderingObservable.clear();
  22771. this.onAfterParticlesRenderingObservable.clear();
  22772. this.onBeforeSpritesRenderingObservable.clear();
  22773. this.onAfterSpritesRenderingObservable.clear();
  22774. this.onBeforeDrawPhaseObservable.clear();
  22775. this.onAfterDrawPhaseObservable.clear();
  22776. this.onBeforePhysicsObservable.clear();
  22777. this.onAfterPhysicsObservable.clear();
  22778. this.onBeforeAnimationsObservable.clear();
  22779. this.onAfterAnimationsObservable.clear();
  22780. this.onDataLoadedObservable.clear();
  22781. this.detachControl();
  22782. // Release sounds & sounds tracks
  22783. if (BABYLON.AudioEngine) {
  22784. this.disposeSounds();
  22785. }
  22786. // VR Helper
  22787. if (this.VRHelper) {
  22788. this.VRHelper.dispose();
  22789. }
  22790. // Detach cameras
  22791. var canvas = this._engine.getRenderingCanvas();
  22792. if (canvas) {
  22793. var index;
  22794. for (index = 0; index < this.cameras.length; index++) {
  22795. this.cameras[index].detachControl(canvas);
  22796. }
  22797. }
  22798. // Release animation groups
  22799. while (this.animationGroups.length) {
  22800. this.animationGroups[0].dispose();
  22801. }
  22802. // Release lights
  22803. while (this.lights.length) {
  22804. this.lights[0].dispose();
  22805. }
  22806. // Release meshes
  22807. while (this.meshes.length) {
  22808. this.meshes[0].dispose(true);
  22809. }
  22810. while (this.transformNodes.length) {
  22811. this.removeTransformNode(this.transformNodes[0]);
  22812. }
  22813. // Release cameras
  22814. while (this.cameras.length) {
  22815. this.cameras[0].dispose();
  22816. }
  22817. // Release materials
  22818. if (this.defaultMaterial) {
  22819. this.defaultMaterial.dispose();
  22820. }
  22821. while (this.multiMaterials.length) {
  22822. this.multiMaterials[0].dispose();
  22823. }
  22824. while (this.materials.length) {
  22825. this.materials[0].dispose();
  22826. }
  22827. // Release particles
  22828. while (this.particleSystems.length) {
  22829. this.particleSystems[0].dispose();
  22830. }
  22831. // Release sprites
  22832. while (this.spriteManagers.length) {
  22833. this.spriteManagers[0].dispose();
  22834. }
  22835. // Release postProcesses
  22836. while (this.postProcesses.length) {
  22837. this.postProcesses[0].dispose();
  22838. }
  22839. // Release layers
  22840. while (this.layers.length) {
  22841. this.layers[0].dispose();
  22842. }
  22843. while (this.highlightLayers.length) {
  22844. this.highlightLayers[0].dispose();
  22845. }
  22846. // Release textures
  22847. while (this.textures.length) {
  22848. this.textures[0].dispose();
  22849. }
  22850. // Release UBO
  22851. this._sceneUbo.dispose();
  22852. if (this._alternateSceneUbo) {
  22853. this._alternateSceneUbo.dispose();
  22854. }
  22855. // Post-processes
  22856. this.postProcessManager.dispose();
  22857. if (this._postProcessRenderPipelineManager) {
  22858. this._postProcessRenderPipelineManager.dispose();
  22859. }
  22860. // Physics
  22861. if (this._physicsEngine) {
  22862. this.disablePhysicsEngine();
  22863. }
  22864. // Remove from engine
  22865. index = this._engine.scenes.indexOf(this);
  22866. if (index > -1) {
  22867. this._engine.scenes.splice(index, 1);
  22868. }
  22869. this._engine.wipeCaches(true);
  22870. this._isDisposed = true;
  22871. };
  22872. Object.defineProperty(Scene.prototype, "isDisposed", {
  22873. get: function () {
  22874. return this._isDisposed;
  22875. },
  22876. enumerable: true,
  22877. configurable: true
  22878. });
  22879. // Release sounds & sounds tracks
  22880. Scene.prototype.disposeSounds = function () {
  22881. if (!this._mainSoundTrack) {
  22882. return;
  22883. }
  22884. this.mainSoundTrack.dispose();
  22885. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22886. this.soundTracks[scIndex].dispose();
  22887. }
  22888. };
  22889. // Octrees
  22890. Scene.prototype.getWorldExtends = function () {
  22891. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22892. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22893. for (var index = 0; index < this.meshes.length; index++) {
  22894. var mesh = this.meshes[index];
  22895. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22896. continue;
  22897. }
  22898. mesh.computeWorldMatrix(true);
  22899. var boundingInfo = mesh.getBoundingInfo();
  22900. var minBox = boundingInfo.boundingBox.minimumWorld;
  22901. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22902. BABYLON.Tools.CheckExtends(minBox, min, max);
  22903. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22904. }
  22905. return {
  22906. min: min,
  22907. max: max
  22908. };
  22909. };
  22910. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22911. if (maxCapacity === void 0) { maxCapacity = 64; }
  22912. if (maxDepth === void 0) { maxDepth = 2; }
  22913. if (!this._selectionOctree) {
  22914. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22915. }
  22916. var worldExtends = this.getWorldExtends();
  22917. // Update octree
  22918. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22919. return this._selectionOctree;
  22920. };
  22921. // Picking
  22922. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22923. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22924. var result = BABYLON.Ray.Zero();
  22925. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22926. return result;
  22927. };
  22928. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22929. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22930. var engine = this._engine;
  22931. if (!camera) {
  22932. if (!this.activeCamera)
  22933. throw new Error("Active camera not set");
  22934. camera = this.activeCamera;
  22935. }
  22936. var cameraViewport = camera.viewport;
  22937. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22938. // Moving coordinates to local viewport world
  22939. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22940. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22941. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22942. return this;
  22943. };
  22944. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22945. var result = BABYLON.Ray.Zero();
  22946. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22947. return result;
  22948. };
  22949. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22950. if (!BABYLON.PickingInfo) {
  22951. return this;
  22952. }
  22953. var engine = this._engine;
  22954. if (!camera) {
  22955. if (!this.activeCamera)
  22956. throw new Error("Active camera not set");
  22957. camera = this.activeCamera;
  22958. }
  22959. var cameraViewport = camera.viewport;
  22960. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22961. var identity = BABYLON.Matrix.Identity();
  22962. // Moving coordinates to local viewport world
  22963. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22964. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22965. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22966. return this;
  22967. };
  22968. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22969. if (!BABYLON.PickingInfo) {
  22970. return null;
  22971. }
  22972. var pickingInfo = null;
  22973. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22974. var mesh = this.meshes[meshIndex];
  22975. if (predicate) {
  22976. if (!predicate(mesh)) {
  22977. continue;
  22978. }
  22979. }
  22980. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22981. continue;
  22982. }
  22983. var world = mesh.getWorldMatrix();
  22984. var ray = rayFunction(world);
  22985. var result = mesh.intersects(ray, fastCheck);
  22986. if (!result || !result.hit)
  22987. continue;
  22988. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22989. continue;
  22990. pickingInfo = result;
  22991. if (fastCheck) {
  22992. break;
  22993. }
  22994. }
  22995. return pickingInfo || new BABYLON.PickingInfo();
  22996. };
  22997. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22998. if (!BABYLON.PickingInfo) {
  22999. return null;
  23000. }
  23001. var pickingInfos = new Array();
  23002. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23003. var mesh = this.meshes[meshIndex];
  23004. if (predicate) {
  23005. if (!predicate(mesh)) {
  23006. continue;
  23007. }
  23008. }
  23009. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23010. continue;
  23011. }
  23012. var world = mesh.getWorldMatrix();
  23013. var ray = rayFunction(world);
  23014. var result = mesh.intersects(ray, false);
  23015. if (!result || !result.hit)
  23016. continue;
  23017. pickingInfos.push(result);
  23018. }
  23019. return pickingInfos;
  23020. };
  23021. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23022. if (!BABYLON.PickingInfo) {
  23023. return null;
  23024. }
  23025. var pickingInfo = null;
  23026. if (!camera) {
  23027. if (!this.activeCamera) {
  23028. return null;
  23029. }
  23030. camera = this.activeCamera;
  23031. }
  23032. if (this.spriteManagers.length > 0) {
  23033. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23034. var spriteManager = this.spriteManagers[spriteIndex];
  23035. if (!spriteManager.isPickable) {
  23036. continue;
  23037. }
  23038. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23039. if (!result || !result.hit)
  23040. continue;
  23041. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23042. continue;
  23043. pickingInfo = result;
  23044. if (fastCheck) {
  23045. break;
  23046. }
  23047. }
  23048. }
  23049. return pickingInfo || new BABYLON.PickingInfo();
  23050. };
  23051. /** Launch a ray to try to pick a mesh in the scene
  23052. * @param x position on screen
  23053. * @param y position on screen
  23054. * @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
  23055. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23056. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23057. */
  23058. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23059. var _this = this;
  23060. if (!BABYLON.PickingInfo) {
  23061. return null;
  23062. }
  23063. return this._internalPick(function (world) {
  23064. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23065. return _this._tempPickingRay;
  23066. }, predicate, fastCheck);
  23067. };
  23068. /** Launch a ray to try to pick a sprite in the scene
  23069. * @param x position on screen
  23070. * @param y position on screen
  23071. * @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
  23072. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23073. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23074. */
  23075. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23076. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23077. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23078. };
  23079. /** Use the given ray to pick a mesh in the scene
  23080. * @param ray The ray to use to pick meshes
  23081. * @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
  23082. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23083. */
  23084. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23085. var _this = this;
  23086. return this._internalPick(function (world) {
  23087. if (!_this._pickWithRayInverseMatrix) {
  23088. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23089. }
  23090. world.invertToRef(_this._pickWithRayInverseMatrix);
  23091. if (!_this._cachedRayForTransform) {
  23092. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23093. }
  23094. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23095. return _this._cachedRayForTransform;
  23096. }, predicate, fastCheck);
  23097. };
  23098. /**
  23099. * Launch a ray to try to pick a mesh in the scene
  23100. * @param x X position on screen
  23101. * @param y Y position on screen
  23102. * @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
  23103. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23104. */
  23105. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23106. var _this = this;
  23107. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23108. };
  23109. /**
  23110. * Launch a ray to try to pick a mesh in the scene
  23111. * @param ray Ray to use
  23112. * @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
  23113. */
  23114. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23115. var _this = this;
  23116. return this._internalMultiPick(function (world) {
  23117. if (!_this._pickWithRayInverseMatrix) {
  23118. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23119. }
  23120. world.invertToRef(_this._pickWithRayInverseMatrix);
  23121. if (!_this._cachedRayForTransform) {
  23122. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23123. }
  23124. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23125. return _this._cachedRayForTransform;
  23126. }, predicate);
  23127. };
  23128. Scene.prototype.setPointerOverMesh = function (mesh) {
  23129. if (this._pointerOverMesh === mesh) {
  23130. return;
  23131. }
  23132. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23133. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23134. }
  23135. this._pointerOverMesh = mesh;
  23136. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23137. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23138. }
  23139. };
  23140. Scene.prototype.getPointerOverMesh = function () {
  23141. return this._pointerOverMesh;
  23142. };
  23143. Scene.prototype.setPointerOverSprite = function (sprite) {
  23144. if (this._pointerOverSprite === sprite) {
  23145. return;
  23146. }
  23147. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23148. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23149. }
  23150. this._pointerOverSprite = sprite;
  23151. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23152. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23153. }
  23154. };
  23155. Scene.prototype.getPointerOverSprite = function () {
  23156. return this._pointerOverSprite;
  23157. };
  23158. // Physics
  23159. Scene.prototype.getPhysicsEngine = function () {
  23160. return this._physicsEngine;
  23161. };
  23162. /**
  23163. * Enables physics to the current scene
  23164. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23165. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23166. * @return {boolean} was the physics engine initialized
  23167. */
  23168. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23169. if (gravity === void 0) { gravity = null; }
  23170. if (this._physicsEngine) {
  23171. return true;
  23172. }
  23173. try {
  23174. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23175. return true;
  23176. }
  23177. catch (e) {
  23178. BABYLON.Tools.Error(e.message);
  23179. return false;
  23180. }
  23181. };
  23182. Scene.prototype.disablePhysicsEngine = function () {
  23183. if (!this._physicsEngine) {
  23184. return;
  23185. }
  23186. this._physicsEngine.dispose();
  23187. this._physicsEngine = null;
  23188. };
  23189. Scene.prototype.isPhysicsEnabled = function () {
  23190. return this._physicsEngine !== undefined;
  23191. };
  23192. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23193. var mesh = compound.parts[0].mesh;
  23194. if (mesh.physicsImpostor) {
  23195. mesh.physicsImpostor.dispose();
  23196. mesh.physicsImpostor = null;
  23197. }
  23198. };
  23199. // Misc.
  23200. Scene.prototype._rebuildGeometries = function () {
  23201. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23202. var geometry = _a[_i];
  23203. geometry._rebuild();
  23204. }
  23205. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23206. var mesh = _c[_b];
  23207. mesh._rebuild();
  23208. }
  23209. if (this.postProcessManager) {
  23210. this.postProcessManager._rebuild();
  23211. }
  23212. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23213. var layer = _e[_d];
  23214. layer._rebuild();
  23215. }
  23216. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23217. var highlightLayer = _g[_f];
  23218. highlightLayer._rebuild();
  23219. }
  23220. if (this._boundingBoxRenderer) {
  23221. this._boundingBoxRenderer._rebuild();
  23222. }
  23223. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23224. var system = _j[_h];
  23225. system.rebuild();
  23226. }
  23227. if (this._postProcessRenderPipelineManager) {
  23228. this._postProcessRenderPipelineManager._rebuild();
  23229. }
  23230. };
  23231. Scene.prototype._rebuildTextures = function () {
  23232. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23233. var texture = _a[_i];
  23234. texture._rebuild();
  23235. }
  23236. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23237. };
  23238. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23239. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23240. if (replace === void 0) { replace = false; }
  23241. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23242. // Dispose existing camera or light in replace mode.
  23243. if (replace) {
  23244. if (this.activeCamera) {
  23245. this.activeCamera.dispose();
  23246. this.activeCamera = null;
  23247. }
  23248. if (this.lights) {
  23249. for (var i = 0; i < this.lights.length; i++) {
  23250. this.lights[i].dispose();
  23251. }
  23252. }
  23253. }
  23254. // Light
  23255. if (this.lights.length === 0) {
  23256. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23257. }
  23258. // Camera
  23259. if (!this.activeCamera) {
  23260. var worldExtends = this.getWorldExtends();
  23261. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23262. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23263. var camera;
  23264. var radius = worldSize.length() * 1.5;
  23265. if (createArcRotateCamera) {
  23266. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23267. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23268. arcRotateCamera.wheelPrecision = 100 / radius;
  23269. camera = arcRotateCamera;
  23270. }
  23271. else {
  23272. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23273. freeCamera.setTarget(worldCenter);
  23274. camera = freeCamera;
  23275. }
  23276. camera.minZ = radius * 0.01;
  23277. camera.maxZ = radius * 1000;
  23278. camera.speed = radius * 0.2;
  23279. this.activeCamera = camera;
  23280. var canvas = this.getEngine().getRenderingCanvas();
  23281. if (attachCameraControls && canvas) {
  23282. camera.attachControl(canvas);
  23283. }
  23284. }
  23285. };
  23286. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23287. if (pbr === void 0) { pbr = false; }
  23288. if (scale === void 0) { scale = 1000; }
  23289. if (blur === void 0) { blur = 0; }
  23290. if (environmentTexture) {
  23291. this.environmentTexture = environmentTexture;
  23292. }
  23293. if (!this.environmentTexture) {
  23294. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23295. return null;
  23296. }
  23297. // Skybox
  23298. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23299. if (pbr) {
  23300. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23301. hdrSkyboxMaterial.backFaceCulling = false;
  23302. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23303. if (hdrSkyboxMaterial.reflectionTexture) {
  23304. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23305. }
  23306. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23307. hdrSkyboxMaterial.disableLighting = true;
  23308. hdrSkyboxMaterial.twoSidedLighting = true;
  23309. hdrSkybox.infiniteDistance = true;
  23310. hdrSkybox.material = hdrSkyboxMaterial;
  23311. }
  23312. else {
  23313. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23314. skyboxMaterial.backFaceCulling = false;
  23315. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23316. if (skyboxMaterial.reflectionTexture) {
  23317. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23318. }
  23319. skyboxMaterial.disableLighting = true;
  23320. hdrSkybox.infiniteDistance = true;
  23321. hdrSkybox.material = skyboxMaterial;
  23322. }
  23323. return hdrSkybox;
  23324. };
  23325. Scene.prototype.createDefaultEnvironment = function (options) {
  23326. if (BABYLON.EnvironmentHelper) {
  23327. return new BABYLON.EnvironmentHelper(options, this);
  23328. }
  23329. return null;
  23330. };
  23331. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23332. if (webVROptions === void 0) { webVROptions = {}; }
  23333. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23334. };
  23335. // Tags
  23336. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23337. if (tagsQuery === undefined) {
  23338. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23339. return list;
  23340. }
  23341. var listByTags = [];
  23342. forEach = forEach || (function (item) { return; });
  23343. for (var i in list) {
  23344. var item = list[i];
  23345. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23346. listByTags.push(item);
  23347. forEach(item);
  23348. }
  23349. }
  23350. return listByTags;
  23351. };
  23352. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23353. return this._getByTags(this.meshes, tagsQuery, forEach);
  23354. };
  23355. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23356. return this._getByTags(this.cameras, tagsQuery, forEach);
  23357. };
  23358. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23359. return this._getByTags(this.lights, tagsQuery, forEach);
  23360. };
  23361. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23362. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23363. };
  23364. /**
  23365. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23366. * This allowed control for front to back rendering or reversly depending of the special needs.
  23367. *
  23368. * @param renderingGroupId The rendering group id corresponding to its index
  23369. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23370. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23371. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23372. */
  23373. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23374. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23375. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23376. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23377. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23378. };
  23379. /**
  23380. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23381. *
  23382. * @param renderingGroupId The rendering group id corresponding to its index
  23383. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23384. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23385. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23386. */
  23387. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23388. if (depth === void 0) { depth = true; }
  23389. if (stencil === void 0) { stencil = true; }
  23390. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23391. };
  23392. /**
  23393. * Will flag all materials as dirty to trigger new shader compilation
  23394. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23395. */
  23396. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23397. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23398. var material = _a[_i];
  23399. if (predicate && !predicate(material)) {
  23400. continue;
  23401. }
  23402. material.markAsDirty(flag);
  23403. }
  23404. };
  23405. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23406. var _this = this;
  23407. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23408. this._activeRequests.push(request);
  23409. request.onCompleteObservable.add(function (request) {
  23410. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23411. });
  23412. return request;
  23413. };
  23414. // Statics
  23415. Scene._FOGMODE_NONE = 0;
  23416. Scene._FOGMODE_EXP = 1;
  23417. Scene._FOGMODE_EXP2 = 2;
  23418. Scene._FOGMODE_LINEAR = 3;
  23419. Scene._uniqueIdCounter = 0;
  23420. Scene.MinDeltaTime = 1.0;
  23421. Scene.MaxDeltaTime = 1000.0;
  23422. /** The distance in pixel that you have to move to prevent some events */
  23423. Scene.DragMovementThreshold = 10; // in pixels
  23424. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23425. Scene.LongPressDelay = 500; // in milliseconds
  23426. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23427. Scene.DoubleClickDelay = 300; // in milliseconds
  23428. /** If you need to check double click without raising a single click at first click, enable this flag */
  23429. Scene.ExclusiveDoubleClickMode = false;
  23430. return Scene;
  23431. }());
  23432. BABYLON.Scene = Scene;
  23433. })(BABYLON || (BABYLON = {}));
  23434. //# sourceMappingURL=babylon.scene.js.map
  23435. var BABYLON;
  23436. (function (BABYLON) {
  23437. /**
  23438. * Set of assets to keep when moving a scene into an asset container.
  23439. */
  23440. var KeepAssets = /** @class */ (function () {
  23441. function KeepAssets() {
  23442. /**
  23443. * Cameras to keep.
  23444. */
  23445. this.cameras = new Array();
  23446. /**
  23447. * Lights to keep.
  23448. */
  23449. this.lights = new Array();
  23450. /**
  23451. * Meshes to keep.
  23452. */
  23453. this.meshes = new Array();
  23454. /**
  23455. * Skeletons to keep.
  23456. */
  23457. this.skeletons = new Array();
  23458. /**
  23459. * ParticleSystems to keep.
  23460. */
  23461. this.particleSystems = new Array();
  23462. /**
  23463. * Animations to keep.
  23464. */
  23465. this.animations = new Array();
  23466. /**
  23467. * MultiMaterials to keep.
  23468. */
  23469. this.multiMaterials = new Array();
  23470. /**
  23471. * Materials to keep.
  23472. */
  23473. this.materials = new Array();
  23474. /**
  23475. * MorphTargetManagers to keep.
  23476. */
  23477. this.morphTargetManagers = new Array();
  23478. /**
  23479. * Geometries to keep.
  23480. */
  23481. this.geometries = new Array();
  23482. /**
  23483. * TransformNodes to keep.
  23484. */
  23485. this.transformNodes = new Array();
  23486. /**
  23487. * LensFlareSystems to keep.
  23488. */
  23489. this.lensFlareSystems = new Array();
  23490. /**
  23491. * ShadowGenerators to keep.
  23492. */
  23493. this.shadowGenerators = new Array();
  23494. /**
  23495. * ActionManagers to keep.
  23496. */
  23497. this.actionManagers = new Array();
  23498. /**
  23499. * Sounds to keep.
  23500. */
  23501. this.sounds = new Array();
  23502. }
  23503. return KeepAssets;
  23504. }());
  23505. BABYLON.KeepAssets = KeepAssets;
  23506. /**
  23507. * Container with a set of assets that can be added or removed from a scene.
  23508. */
  23509. var AssetContainer = /** @class */ (function () {
  23510. /**
  23511. * Instantiates an AssetContainer.
  23512. * @param scene The scene the AssetContainer belongs to.
  23513. */
  23514. function AssetContainer(scene) {
  23515. // Objects
  23516. /**
  23517. * Cameras populated in the container.
  23518. */
  23519. this.cameras = new Array();
  23520. /**
  23521. * Lights populated in the container.
  23522. */
  23523. this.lights = new Array();
  23524. /**
  23525. * Meshes populated in the container.
  23526. */
  23527. this.meshes = new Array();
  23528. /**
  23529. * Skeletons populated in the container.
  23530. */
  23531. this.skeletons = new Array();
  23532. /**
  23533. * ParticleSystems populated in the container.
  23534. */
  23535. this.particleSystems = new Array();
  23536. /**
  23537. * Animations populated in the container.
  23538. */
  23539. this.animations = new Array();
  23540. /**
  23541. * MultiMaterials populated in the container.
  23542. */
  23543. this.multiMaterials = new Array();
  23544. /**
  23545. * Materials populated in the container.
  23546. */
  23547. this.materials = new Array();
  23548. /**
  23549. * MorphTargetManagers populated in the container.
  23550. */
  23551. this.morphTargetManagers = new Array();
  23552. /**
  23553. * Geometries populated in the container.
  23554. */
  23555. this.geometries = new Array();
  23556. /**
  23557. * TransformNodes populated in the container.
  23558. */
  23559. this.transformNodes = new Array();
  23560. /**
  23561. * LensFlareSystems populated in the container.
  23562. */
  23563. this.lensFlareSystems = new Array();
  23564. /**
  23565. * ShadowGenerators populated in the container.
  23566. */
  23567. this.shadowGenerators = new Array();
  23568. /**
  23569. * ActionManagers populated in the container.
  23570. */
  23571. this.actionManagers = new Array();
  23572. /**
  23573. * Sounds populated in the container.
  23574. */
  23575. this.sounds = new Array();
  23576. this.scene = scene;
  23577. }
  23578. /**
  23579. * Adds all the assets from the container to the scene.
  23580. */
  23581. AssetContainer.prototype.addAllToScene = function () {
  23582. var _this = this;
  23583. this.cameras.forEach(function (o) {
  23584. _this.scene.addCamera(o);
  23585. });
  23586. this.lights.forEach(function (o) {
  23587. _this.scene.addLight(o);
  23588. });
  23589. this.meshes.forEach(function (o) {
  23590. _this.scene.addMesh(o);
  23591. });
  23592. this.skeletons.forEach(function (o) {
  23593. _this.scene.addSkeleton(o);
  23594. });
  23595. this.particleSystems.forEach(function (o) {
  23596. _this.scene.addParticleSystem(o);
  23597. });
  23598. this.animations.forEach(function (o) {
  23599. _this.scene.addAnimation(o);
  23600. });
  23601. this.multiMaterials.forEach(function (o) {
  23602. _this.scene.addMultiMaterial(o);
  23603. });
  23604. this.materials.forEach(function (o) {
  23605. _this.scene.addMaterial(o);
  23606. });
  23607. this.morphTargetManagers.forEach(function (o) {
  23608. _this.scene.addMorphTargetManager(o);
  23609. });
  23610. this.geometries.forEach(function (o) {
  23611. _this.scene.addGeometry(o);
  23612. });
  23613. this.transformNodes.forEach(function (o) {
  23614. _this.scene.addTransformNode(o);
  23615. });
  23616. this.lensFlareSystems.forEach(function (o) {
  23617. _this.scene.addLensFlareSystem(o);
  23618. });
  23619. this.actionManagers.forEach(function (o) {
  23620. _this.scene.addActionManager(o);
  23621. });
  23622. this.sounds.forEach(function (o) {
  23623. o.play();
  23624. o.autoplay = true;
  23625. _this.scene.mainSoundTrack.AddSound(o);
  23626. });
  23627. };
  23628. /**
  23629. * Removes all the assets in the container from the scene
  23630. */
  23631. AssetContainer.prototype.removeAllFromScene = function () {
  23632. var _this = this;
  23633. this.cameras.forEach(function (o) {
  23634. _this.scene.removeCamera(o);
  23635. });
  23636. this.lights.forEach(function (o) {
  23637. _this.scene.removeLight(o);
  23638. });
  23639. this.meshes.forEach(function (o) {
  23640. _this.scene.removeMesh(o);
  23641. });
  23642. this.skeletons.forEach(function (o) {
  23643. _this.scene.removeSkeleton(o);
  23644. });
  23645. this.particleSystems.forEach(function (o) {
  23646. _this.scene.removeParticleSystem(o);
  23647. });
  23648. this.animations.forEach(function (o) {
  23649. _this.scene.removeAnimation(o);
  23650. });
  23651. this.multiMaterials.forEach(function (o) {
  23652. _this.scene.removeMultiMaterial(o);
  23653. });
  23654. this.materials.forEach(function (o) {
  23655. _this.scene.removeMaterial(o);
  23656. });
  23657. this.morphTargetManagers.forEach(function (o) {
  23658. _this.scene.removeMorphTargetManager(o);
  23659. });
  23660. this.geometries.forEach(function (o) {
  23661. _this.scene.removeGeometry(o);
  23662. });
  23663. this.transformNodes.forEach(function (o) {
  23664. _this.scene.removeTransformNode(o);
  23665. });
  23666. this.lensFlareSystems.forEach(function (o) {
  23667. _this.scene.removeLensFlareSystem(o);
  23668. });
  23669. this.actionManagers.forEach(function (o) {
  23670. _this.scene.removeActionManager(o);
  23671. });
  23672. this.sounds.forEach(function (o) {
  23673. o.stop();
  23674. o.autoplay = false;
  23675. _this.scene.mainSoundTrack.RemoveSound(o);
  23676. });
  23677. };
  23678. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  23679. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  23680. var asset = sourceAssets_1[_i];
  23681. var move = true;
  23682. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  23683. var keepAsset = keepAssets_1[_a];
  23684. if (asset === keepAsset) {
  23685. move = false;
  23686. break;
  23687. }
  23688. }
  23689. if (move) {
  23690. targetAssets.push(asset);
  23691. }
  23692. }
  23693. };
  23694. /**
  23695. * Removes all the assets contained in the scene and adds them to the container.
  23696. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  23697. */
  23698. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  23699. if (keepAssets === undefined) {
  23700. keepAssets = new KeepAssets();
  23701. }
  23702. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  23703. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  23704. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  23705. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  23706. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  23707. Array.prototype.push.apply(this.animations, this.scene.animations);
  23708. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  23709. Array.prototype.push.apply(this.lights, this.scene.lights);
  23710. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  23711. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  23712. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  23713. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  23714. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  23715. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  23716. this.removeAllFromScene();
  23717. };
  23718. return AssetContainer;
  23719. }());
  23720. BABYLON.AssetContainer = AssetContainer;
  23721. })(BABYLON || (BABYLON = {}));
  23722. //# sourceMappingURL=babylon.assetContainer.js.map
  23723. var BABYLON;
  23724. (function (BABYLON) {
  23725. var Buffer = /** @class */ (function () {
  23726. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23727. if (instanced === void 0) { instanced = false; }
  23728. if (engine instanceof BABYLON.Mesh) {
  23729. this._engine = engine.getScene().getEngine();
  23730. }
  23731. else {
  23732. this._engine = engine;
  23733. }
  23734. this._updatable = updatable;
  23735. this._data = data;
  23736. this._strideSize = stride;
  23737. if (!postponeInternalCreation) {
  23738. this.create();
  23739. }
  23740. this._instanced = instanced;
  23741. this._instanceDivisor = instanced ? 1 : 0;
  23742. }
  23743. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23744. // a lot of these parameters are ignored as they are overriden by the buffer
  23745. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23746. };
  23747. // Properties
  23748. Buffer.prototype.isUpdatable = function () {
  23749. return this._updatable;
  23750. };
  23751. Buffer.prototype.getData = function () {
  23752. return this._data;
  23753. };
  23754. Buffer.prototype.getBuffer = function () {
  23755. return this._buffer;
  23756. };
  23757. Buffer.prototype.getStrideSize = function () {
  23758. return this._strideSize;
  23759. };
  23760. Buffer.prototype.getIsInstanced = function () {
  23761. return this._instanced;
  23762. };
  23763. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23764. get: function () {
  23765. return this._instanceDivisor;
  23766. },
  23767. set: function (value) {
  23768. this._instanceDivisor = value;
  23769. if (value == 0) {
  23770. this._instanced = false;
  23771. }
  23772. else {
  23773. this._instanced = true;
  23774. }
  23775. },
  23776. enumerable: true,
  23777. configurable: true
  23778. });
  23779. // Methods
  23780. Buffer.prototype.create = function (data) {
  23781. if (data === void 0) { data = null; }
  23782. if (!data && this._buffer) {
  23783. return; // nothing to do
  23784. }
  23785. data = data || this._data;
  23786. if (!data) {
  23787. return;
  23788. }
  23789. if (!this._buffer) {
  23790. if (this._updatable) {
  23791. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23792. this._data = data;
  23793. }
  23794. else {
  23795. this._buffer = this._engine.createVertexBuffer(data);
  23796. }
  23797. }
  23798. else if (this._updatable) {
  23799. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23800. this._data = data;
  23801. }
  23802. };
  23803. Buffer.prototype._rebuild = function () {
  23804. this._buffer = null;
  23805. this.create(this._data);
  23806. };
  23807. Buffer.prototype.update = function (data) {
  23808. this.create(data);
  23809. };
  23810. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23811. if (!this._buffer) {
  23812. return;
  23813. }
  23814. if (this._updatable) {
  23815. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23816. this._data = null;
  23817. }
  23818. };
  23819. Buffer.prototype.dispose = function () {
  23820. if (!this._buffer) {
  23821. return;
  23822. }
  23823. if (this._engine._releaseBuffer(this._buffer)) {
  23824. this._buffer = null;
  23825. }
  23826. };
  23827. return Buffer;
  23828. }());
  23829. BABYLON.Buffer = Buffer;
  23830. })(BABYLON || (BABYLON = {}));
  23831. //# sourceMappingURL=babylon.buffer.js.map
  23832. var BABYLON;
  23833. (function (BABYLON) {
  23834. var VertexBuffer = /** @class */ (function () {
  23835. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23836. if (!stride) {
  23837. // Deduce stride from kind
  23838. switch (kind) {
  23839. case VertexBuffer.PositionKind:
  23840. stride = 3;
  23841. break;
  23842. case VertexBuffer.NormalKind:
  23843. stride = 3;
  23844. break;
  23845. case VertexBuffer.UVKind:
  23846. case VertexBuffer.UV2Kind:
  23847. case VertexBuffer.UV3Kind:
  23848. case VertexBuffer.UV4Kind:
  23849. case VertexBuffer.UV5Kind:
  23850. case VertexBuffer.UV6Kind:
  23851. stride = 2;
  23852. break;
  23853. case VertexBuffer.TangentKind:
  23854. case VertexBuffer.ColorKind:
  23855. stride = 4;
  23856. break;
  23857. case VertexBuffer.MatricesIndicesKind:
  23858. case VertexBuffer.MatricesIndicesExtraKind:
  23859. stride = 4;
  23860. break;
  23861. case VertexBuffer.MatricesWeightsKind:
  23862. case VertexBuffer.MatricesWeightsExtraKind:
  23863. default:
  23864. stride = 4;
  23865. break;
  23866. }
  23867. }
  23868. if (data instanceof BABYLON.Buffer) {
  23869. if (!stride) {
  23870. stride = data.getStrideSize();
  23871. }
  23872. this._buffer = data;
  23873. this._ownsBuffer = false;
  23874. }
  23875. else {
  23876. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23877. this._ownsBuffer = true;
  23878. }
  23879. this._stride = stride;
  23880. this._offset = offset ? offset : 0;
  23881. this._size = size ? size : stride;
  23882. this._kind = kind;
  23883. }
  23884. VertexBuffer.prototype._rebuild = function () {
  23885. if (!this._buffer) {
  23886. return;
  23887. }
  23888. this._buffer._rebuild();
  23889. };
  23890. /**
  23891. * Returns the kind of the VertexBuffer (string).
  23892. */
  23893. VertexBuffer.prototype.getKind = function () {
  23894. return this._kind;
  23895. };
  23896. // Properties
  23897. /**
  23898. * Boolean : is the VertexBuffer updatable ?
  23899. */
  23900. VertexBuffer.prototype.isUpdatable = function () {
  23901. return this._buffer.isUpdatable();
  23902. };
  23903. /**
  23904. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23905. */
  23906. VertexBuffer.prototype.getData = function () {
  23907. return this._buffer.getData();
  23908. };
  23909. /**
  23910. * Returns the WebGLBuffer associated to the VertexBuffer.
  23911. */
  23912. VertexBuffer.prototype.getBuffer = function () {
  23913. return this._buffer.getBuffer();
  23914. };
  23915. /**
  23916. * Returns the stride of the VertexBuffer (integer).
  23917. */
  23918. VertexBuffer.prototype.getStrideSize = function () {
  23919. return this._stride;
  23920. };
  23921. /**
  23922. * Returns the offset (integer).
  23923. */
  23924. VertexBuffer.prototype.getOffset = function () {
  23925. return this._offset;
  23926. };
  23927. /**
  23928. * Returns the VertexBuffer total size (integer).
  23929. */
  23930. VertexBuffer.prototype.getSize = function () {
  23931. return this._size;
  23932. };
  23933. /**
  23934. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23935. */
  23936. VertexBuffer.prototype.getIsInstanced = function () {
  23937. return this._buffer.getIsInstanced();
  23938. };
  23939. /**
  23940. * Returns the instancing divisor, zero for non-instanced (integer).
  23941. */
  23942. VertexBuffer.prototype.getInstanceDivisor = function () {
  23943. return this._buffer.instanceDivisor;
  23944. };
  23945. // Methods
  23946. /**
  23947. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23948. * Returns the created WebGLBuffer.
  23949. */
  23950. VertexBuffer.prototype.create = function (data) {
  23951. return this._buffer.create(data);
  23952. };
  23953. /**
  23954. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23955. * This function will create a new buffer if the current one is not updatable
  23956. * Returns the updated WebGLBuffer.
  23957. */
  23958. VertexBuffer.prototype.update = function (data) {
  23959. return this._buffer.update(data);
  23960. };
  23961. /**
  23962. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23963. * Returns the directly updated WebGLBuffer.
  23964. */
  23965. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23966. return this._buffer.updateDirectly(data, offset);
  23967. };
  23968. /**
  23969. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23970. */
  23971. VertexBuffer.prototype.dispose = function () {
  23972. if (this._ownsBuffer) {
  23973. this._buffer.dispose();
  23974. }
  23975. };
  23976. Object.defineProperty(VertexBuffer, "PositionKind", {
  23977. get: function () {
  23978. return VertexBuffer._PositionKind;
  23979. },
  23980. enumerable: true,
  23981. configurable: true
  23982. });
  23983. Object.defineProperty(VertexBuffer, "NormalKind", {
  23984. get: function () {
  23985. return VertexBuffer._NormalKind;
  23986. },
  23987. enumerable: true,
  23988. configurable: true
  23989. });
  23990. Object.defineProperty(VertexBuffer, "TangentKind", {
  23991. get: function () {
  23992. return VertexBuffer._TangentKind;
  23993. },
  23994. enumerable: true,
  23995. configurable: true
  23996. });
  23997. Object.defineProperty(VertexBuffer, "UVKind", {
  23998. get: function () {
  23999. return VertexBuffer._UVKind;
  24000. },
  24001. enumerable: true,
  24002. configurable: true
  24003. });
  24004. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24005. get: function () {
  24006. return VertexBuffer._UV2Kind;
  24007. },
  24008. enumerable: true,
  24009. configurable: true
  24010. });
  24011. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24012. get: function () {
  24013. return VertexBuffer._UV3Kind;
  24014. },
  24015. enumerable: true,
  24016. configurable: true
  24017. });
  24018. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24019. get: function () {
  24020. return VertexBuffer._UV4Kind;
  24021. },
  24022. enumerable: true,
  24023. configurable: true
  24024. });
  24025. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24026. get: function () {
  24027. return VertexBuffer._UV5Kind;
  24028. },
  24029. enumerable: true,
  24030. configurable: true
  24031. });
  24032. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24033. get: function () {
  24034. return VertexBuffer._UV6Kind;
  24035. },
  24036. enumerable: true,
  24037. configurable: true
  24038. });
  24039. Object.defineProperty(VertexBuffer, "ColorKind", {
  24040. get: function () {
  24041. return VertexBuffer._ColorKind;
  24042. },
  24043. enumerable: true,
  24044. configurable: true
  24045. });
  24046. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24047. get: function () {
  24048. return VertexBuffer._MatricesIndicesKind;
  24049. },
  24050. enumerable: true,
  24051. configurable: true
  24052. });
  24053. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24054. get: function () {
  24055. return VertexBuffer._MatricesWeightsKind;
  24056. },
  24057. enumerable: true,
  24058. configurable: true
  24059. });
  24060. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24061. get: function () {
  24062. return VertexBuffer._MatricesIndicesExtraKind;
  24063. },
  24064. enumerable: true,
  24065. configurable: true
  24066. });
  24067. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24068. get: function () {
  24069. return VertexBuffer._MatricesWeightsExtraKind;
  24070. },
  24071. enumerable: true,
  24072. configurable: true
  24073. });
  24074. // Enums
  24075. VertexBuffer._PositionKind = "position";
  24076. VertexBuffer._NormalKind = "normal";
  24077. VertexBuffer._TangentKind = "tangent";
  24078. VertexBuffer._UVKind = "uv";
  24079. VertexBuffer._UV2Kind = "uv2";
  24080. VertexBuffer._UV3Kind = "uv3";
  24081. VertexBuffer._UV4Kind = "uv4";
  24082. VertexBuffer._UV5Kind = "uv5";
  24083. VertexBuffer._UV6Kind = "uv6";
  24084. VertexBuffer._ColorKind = "color";
  24085. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24086. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24087. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24088. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24089. return VertexBuffer;
  24090. }());
  24091. BABYLON.VertexBuffer = VertexBuffer;
  24092. })(BABYLON || (BABYLON = {}));
  24093. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24094. var BABYLON;
  24095. (function (BABYLON) {
  24096. /**
  24097. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24098. */
  24099. var DummyInternalTextureTracker = /** @class */ (function () {
  24100. function DummyInternalTextureTracker() {
  24101. /**
  24102. * Gets or set the previous tracker in the list
  24103. */
  24104. this.previous = null;
  24105. /**
  24106. * Gets or set the next tracker in the list
  24107. */
  24108. this.next = null;
  24109. }
  24110. return DummyInternalTextureTracker;
  24111. }());
  24112. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24113. })(BABYLON || (BABYLON = {}));
  24114. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24115. var BABYLON;
  24116. (function (BABYLON) {
  24117. /**
  24118. * Class used to store data associated with WebGL texture data for the engine
  24119. * This class should not be used directly
  24120. */
  24121. var InternalTexture = /** @class */ (function () {
  24122. /**
  24123. * Creates a new InternalTexture
  24124. * @param engine defines the engine to use
  24125. * @param dataSource defines the type of data that will be used
  24126. */
  24127. function InternalTexture(engine, dataSource) {
  24128. /**
  24129. * Observable called when the texture is loaded
  24130. */
  24131. this.onLoadedObservable = new BABYLON.Observable();
  24132. /**
  24133. * Gets or set the previous tracker in the list
  24134. */
  24135. this.previous = null;
  24136. /**
  24137. * Gets or set the next tracker in the list
  24138. */
  24139. this.next = null;
  24140. // Private
  24141. /** @ignore */
  24142. this._initialSlot = -1;
  24143. /** @ignore */
  24144. this._designatedSlot = -1;
  24145. /** @ignore */
  24146. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24147. /** @ignore */
  24148. this._references = 1;
  24149. this._engine = engine;
  24150. this._dataSource = dataSource;
  24151. this._webGLTexture = engine._createTexture();
  24152. }
  24153. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24154. /**
  24155. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24156. */
  24157. get: function () {
  24158. return this._dataSource;
  24159. },
  24160. enumerable: true,
  24161. configurable: true
  24162. });
  24163. /**
  24164. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24165. */
  24166. InternalTexture.prototype.incrementReferences = function () {
  24167. this._references++;
  24168. };
  24169. /**
  24170. * Change the size of the texture (not the size of the content)
  24171. * @param width defines the new width
  24172. * @param height defines the new height
  24173. * @param depth defines the new depth (1 by default)
  24174. */
  24175. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24176. if (depth === void 0) { depth = 1; }
  24177. this.width = width;
  24178. this.height = height;
  24179. this.depth = depth;
  24180. this.baseWidth = width;
  24181. this.baseHeight = height;
  24182. this.baseDepth = depth;
  24183. this._size = width * height * depth;
  24184. };
  24185. /** @ignore */
  24186. InternalTexture.prototype._rebuild = function () {
  24187. var _this = this;
  24188. var proxy;
  24189. this.isReady = false;
  24190. this._cachedCoordinatesMode = null;
  24191. this._cachedWrapU = null;
  24192. this._cachedWrapV = null;
  24193. this._cachedAnisotropicFilteringLevel = null;
  24194. switch (this._dataSource) {
  24195. case InternalTexture.DATASOURCE_TEMP:
  24196. return;
  24197. case InternalTexture.DATASOURCE_URL:
  24198. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24199. _this.isReady = true;
  24200. }, null, this._buffer, undefined, this.format);
  24201. proxy._swapAndDie(this);
  24202. return;
  24203. case InternalTexture.DATASOURCE_RAW:
  24204. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24205. proxy._swapAndDie(this);
  24206. this.isReady = true;
  24207. return;
  24208. case InternalTexture.DATASOURCE_RAW3D:
  24209. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24210. proxy._swapAndDie(this);
  24211. this.isReady = true;
  24212. return;
  24213. case InternalTexture.DATASOURCE_DYNAMIC:
  24214. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24215. proxy._swapAndDie(this);
  24216. // The engine will make sure to update content so no need to flag it as isReady = true
  24217. return;
  24218. case InternalTexture.DATASOURCE_RENDERTARGET:
  24219. var options = new BABYLON.RenderTargetCreationOptions();
  24220. options.generateDepthBuffer = this._generateDepthBuffer;
  24221. options.generateMipMaps = this.generateMipMaps;
  24222. options.generateStencilBuffer = this._generateStencilBuffer;
  24223. options.samplingMode = this.samplingMode;
  24224. options.type = this.type;
  24225. if (this.isCube) {
  24226. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24227. }
  24228. else {
  24229. var size = {
  24230. width: this.width,
  24231. height: this.height
  24232. };
  24233. proxy = this._engine.createRenderTargetTexture(size, options);
  24234. }
  24235. proxy._swapAndDie(this);
  24236. this.isReady = true;
  24237. return;
  24238. case InternalTexture.DATASOURCE_CUBE:
  24239. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24240. _this.isReady = true;
  24241. }, null, this.format, this._extension);
  24242. proxy._swapAndDie(this);
  24243. return;
  24244. case InternalTexture.DATASOURCE_CUBERAW:
  24245. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24246. proxy._swapAndDie(this);
  24247. this.isReady = true;
  24248. return;
  24249. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24250. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24251. if (proxy) {
  24252. proxy._swapAndDie(_this);
  24253. }
  24254. _this.isReady = true;
  24255. }, null, this.format, this._extension);
  24256. return;
  24257. }
  24258. };
  24259. InternalTexture.prototype._swapAndDie = function (target) {
  24260. target._webGLTexture = this._webGLTexture;
  24261. if (this._framebuffer) {
  24262. target._framebuffer = this._framebuffer;
  24263. }
  24264. if (this._depthStencilBuffer) {
  24265. target._depthStencilBuffer = this._depthStencilBuffer;
  24266. }
  24267. if (this._lodTextureHigh) {
  24268. if (target._lodTextureHigh) {
  24269. target._lodTextureHigh.dispose();
  24270. }
  24271. target._lodTextureHigh = this._lodTextureHigh;
  24272. }
  24273. if (this._lodTextureMid) {
  24274. if (target._lodTextureMid) {
  24275. target._lodTextureMid.dispose();
  24276. }
  24277. target._lodTextureMid = this._lodTextureMid;
  24278. }
  24279. if (this._lodTextureLow) {
  24280. if (target._lodTextureLow) {
  24281. target._lodTextureLow.dispose();
  24282. }
  24283. target._lodTextureLow = this._lodTextureLow;
  24284. }
  24285. var cache = this._engine.getLoadedTexturesCache();
  24286. var index = cache.indexOf(this);
  24287. if (index !== -1) {
  24288. cache.splice(index, 1);
  24289. }
  24290. };
  24291. /**
  24292. * Dispose the current allocated resources
  24293. */
  24294. InternalTexture.prototype.dispose = function () {
  24295. if (!this._webGLTexture) {
  24296. return;
  24297. }
  24298. this._references--;
  24299. if (this._references === 0) {
  24300. this._engine._releaseTexture(this);
  24301. this._webGLTexture = null;
  24302. this.previous = null;
  24303. this.next = null;
  24304. }
  24305. };
  24306. /**
  24307. * The source of the texture data is unknown
  24308. */
  24309. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24310. /**
  24311. * Texture data comes from an URL
  24312. */
  24313. InternalTexture.DATASOURCE_URL = 1;
  24314. /**
  24315. * Texture data is only used for temporary storage
  24316. */
  24317. InternalTexture.DATASOURCE_TEMP = 2;
  24318. /**
  24319. * Texture data comes from raw data (ArrayBuffer)
  24320. */
  24321. InternalTexture.DATASOURCE_RAW = 3;
  24322. /**
  24323. * Texture content is dynamic (video or dynamic texture)
  24324. */
  24325. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24326. /**
  24327. * Texture content is generated by rendering to it
  24328. */
  24329. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24330. /**
  24331. * Texture content is part of a multi render target process
  24332. */
  24333. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24334. /**
  24335. * Texture data comes from a cube data file
  24336. */
  24337. InternalTexture.DATASOURCE_CUBE = 7;
  24338. /**
  24339. * Texture data comes from a raw cube data
  24340. */
  24341. InternalTexture.DATASOURCE_CUBERAW = 8;
  24342. /**
  24343. * Texture data come from a prefiltered cube data file
  24344. */
  24345. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24346. /**
  24347. * Texture content is raw 3D data
  24348. */
  24349. InternalTexture.DATASOURCE_RAW3D = 10;
  24350. return InternalTexture;
  24351. }());
  24352. BABYLON.InternalTexture = InternalTexture;
  24353. })(BABYLON || (BABYLON = {}));
  24354. //# sourceMappingURL=babylon.internalTexture.js.map
  24355. var BABYLON;
  24356. (function (BABYLON) {
  24357. var BaseTexture = /** @class */ (function () {
  24358. function BaseTexture(scene) {
  24359. this._hasAlpha = false;
  24360. this.getAlphaFromRGB = false;
  24361. this.level = 1;
  24362. this.coordinatesIndex = 0;
  24363. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24364. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24365. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24366. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24367. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24368. this.isCube = false;
  24369. this.is3D = false;
  24370. this.gammaSpace = true;
  24371. this.invertZ = false;
  24372. this.lodLevelInAlpha = false;
  24373. this.lodGenerationOffset = 0.0;
  24374. this.lodGenerationScale = 0.8;
  24375. this.isRenderTarget = false;
  24376. this.animations = new Array();
  24377. /**
  24378. * An event triggered when the texture is disposed.
  24379. * @type {BABYLON.Observable}
  24380. */
  24381. this.onDisposeObservable = new BABYLON.Observable();
  24382. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24383. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24384. if (this._scene) {
  24385. this._scene.textures.push(this);
  24386. }
  24387. this._uid = null;
  24388. }
  24389. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24390. get: function () {
  24391. return this._hasAlpha;
  24392. },
  24393. set: function (value) {
  24394. if (this._hasAlpha === value) {
  24395. return;
  24396. }
  24397. this._hasAlpha = value;
  24398. if (this._scene) {
  24399. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24400. }
  24401. },
  24402. enumerable: true,
  24403. configurable: true
  24404. });
  24405. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24406. get: function () {
  24407. return this._coordinatesMode;
  24408. },
  24409. set: function (value) {
  24410. if (this._coordinatesMode === value) {
  24411. return;
  24412. }
  24413. this._coordinatesMode = value;
  24414. if (this._scene) {
  24415. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24416. }
  24417. },
  24418. enumerable: true,
  24419. configurable: true
  24420. });
  24421. Object.defineProperty(BaseTexture.prototype, "uid", {
  24422. get: function () {
  24423. if (!this._uid) {
  24424. this._uid = BABYLON.Tools.RandomId();
  24425. }
  24426. return this._uid;
  24427. },
  24428. enumerable: true,
  24429. configurable: true
  24430. });
  24431. BaseTexture.prototype.toString = function () {
  24432. return this.name;
  24433. };
  24434. BaseTexture.prototype.getClassName = function () {
  24435. return "BaseTexture";
  24436. };
  24437. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24438. set: function (callback) {
  24439. if (this._onDisposeObserver) {
  24440. this.onDisposeObservable.remove(this._onDisposeObserver);
  24441. }
  24442. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24448. get: function () {
  24449. return true;
  24450. },
  24451. enumerable: true,
  24452. configurable: true
  24453. });
  24454. BaseTexture.prototype.getScene = function () {
  24455. return this._scene;
  24456. };
  24457. BaseTexture.prototype.getTextureMatrix = function () {
  24458. return BABYLON.Matrix.IdentityReadOnly;
  24459. };
  24460. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24461. return BABYLON.Matrix.IdentityReadOnly;
  24462. };
  24463. BaseTexture.prototype.getInternalTexture = function () {
  24464. return this._texture;
  24465. };
  24466. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24467. return !this.isBlocking || this.isReady();
  24468. };
  24469. BaseTexture.prototype.isReady = function () {
  24470. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24471. this.delayLoad();
  24472. return false;
  24473. }
  24474. if (this._texture) {
  24475. return this._texture.isReady;
  24476. }
  24477. return false;
  24478. };
  24479. BaseTexture.prototype.getSize = function () {
  24480. if (this._texture && this._texture.width) {
  24481. return new BABYLON.Size(this._texture.width, this._texture.height);
  24482. }
  24483. if (this._texture && this._texture._size) {
  24484. return new BABYLON.Size(this._texture._size, this._texture._size);
  24485. }
  24486. return BABYLON.Size.Zero();
  24487. };
  24488. BaseTexture.prototype.getBaseSize = function () {
  24489. if (!this.isReady() || !this._texture)
  24490. return BABYLON.Size.Zero();
  24491. if (this._texture._size) {
  24492. return new BABYLON.Size(this._texture._size, this._texture._size);
  24493. }
  24494. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24495. };
  24496. BaseTexture.prototype.scale = function (ratio) {
  24497. };
  24498. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24499. get: function () {
  24500. return false;
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24506. if (!this._scene) {
  24507. return null;
  24508. }
  24509. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24510. for (var index = 0; index < texturesCache.length; index++) {
  24511. var texturesCacheEntry = texturesCache[index];
  24512. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24513. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24514. texturesCacheEntry.incrementReferences();
  24515. return texturesCacheEntry;
  24516. }
  24517. }
  24518. }
  24519. return null;
  24520. };
  24521. BaseTexture.prototype._rebuild = function () {
  24522. };
  24523. BaseTexture.prototype.delayLoad = function () {
  24524. };
  24525. BaseTexture.prototype.clone = function () {
  24526. return null;
  24527. };
  24528. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24529. get: function () {
  24530. if (!this._texture) {
  24531. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24532. }
  24533. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24534. },
  24535. enumerable: true,
  24536. configurable: true
  24537. });
  24538. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24539. get: function () {
  24540. if (!this._texture) {
  24541. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24542. }
  24543. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24544. },
  24545. enumerable: true,
  24546. configurable: true
  24547. });
  24548. BaseTexture.prototype.readPixels = function (faceIndex) {
  24549. if (faceIndex === void 0) { faceIndex = 0; }
  24550. if (!this._texture) {
  24551. return null;
  24552. }
  24553. var size = this.getSize();
  24554. var scene = this.getScene();
  24555. if (!scene) {
  24556. return null;
  24557. }
  24558. var engine = scene.getEngine();
  24559. if (this._texture.isCube) {
  24560. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24561. }
  24562. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24563. };
  24564. BaseTexture.prototype.releaseInternalTexture = function () {
  24565. if (this._texture) {
  24566. this._texture.dispose();
  24567. this._texture = null;
  24568. }
  24569. };
  24570. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24571. get: function () {
  24572. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24573. return null;
  24574. }
  24575. if (!this._texture._sphericalPolynomial) {
  24576. this._texture._sphericalPolynomial =
  24577. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24578. }
  24579. return this._texture._sphericalPolynomial;
  24580. },
  24581. set: function (value) {
  24582. if (this._texture) {
  24583. this._texture._sphericalPolynomial = value;
  24584. }
  24585. },
  24586. enumerable: true,
  24587. configurable: true
  24588. });
  24589. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24590. get: function () {
  24591. if (this._texture) {
  24592. return this._texture._lodTextureHigh;
  24593. }
  24594. return null;
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24600. get: function () {
  24601. if (this._texture) {
  24602. return this._texture._lodTextureMid;
  24603. }
  24604. return null;
  24605. },
  24606. enumerable: true,
  24607. configurable: true
  24608. });
  24609. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24610. get: function () {
  24611. if (this._texture) {
  24612. return this._texture._lodTextureLow;
  24613. }
  24614. return null;
  24615. },
  24616. enumerable: true,
  24617. configurable: true
  24618. });
  24619. BaseTexture.prototype.dispose = function () {
  24620. if (!this._scene) {
  24621. return;
  24622. }
  24623. // Animations
  24624. this._scene.stopAnimation(this);
  24625. // Remove from scene
  24626. this._scene._removePendingData(this);
  24627. var index = this._scene.textures.indexOf(this);
  24628. if (index >= 0) {
  24629. this._scene.textures.splice(index, 1);
  24630. }
  24631. if (this._texture === undefined) {
  24632. return;
  24633. }
  24634. // Release
  24635. this.releaseInternalTexture();
  24636. // Callback
  24637. this.onDisposeObservable.notifyObservers(this);
  24638. this.onDisposeObservable.clear();
  24639. };
  24640. BaseTexture.prototype.serialize = function () {
  24641. if (!this.name) {
  24642. return null;
  24643. }
  24644. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24645. // Animations
  24646. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24647. return serializationObject;
  24648. };
  24649. BaseTexture.WhenAllReady = function (textures, callback) {
  24650. var numRemaining = textures.length;
  24651. if (numRemaining === 0) {
  24652. callback();
  24653. return;
  24654. }
  24655. var _loop_1 = function () {
  24656. texture = textures[i];
  24657. if (texture.isReady()) {
  24658. if (--numRemaining === 0) {
  24659. callback();
  24660. }
  24661. }
  24662. else {
  24663. onLoadObservable = texture.onLoadObservable;
  24664. var onLoadCallback_1 = function () {
  24665. onLoadObservable.removeCallback(onLoadCallback_1);
  24666. if (--numRemaining === 0) {
  24667. callback();
  24668. }
  24669. };
  24670. onLoadObservable.add(onLoadCallback_1);
  24671. }
  24672. };
  24673. var texture, onLoadObservable;
  24674. for (var i = 0; i < textures.length; i++) {
  24675. _loop_1();
  24676. }
  24677. };
  24678. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24679. __decorate([
  24680. BABYLON.serialize()
  24681. ], BaseTexture.prototype, "name", void 0);
  24682. __decorate([
  24683. BABYLON.serialize("hasAlpha")
  24684. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24685. __decorate([
  24686. BABYLON.serialize()
  24687. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24688. __decorate([
  24689. BABYLON.serialize()
  24690. ], BaseTexture.prototype, "level", void 0);
  24691. __decorate([
  24692. BABYLON.serialize()
  24693. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24694. __decorate([
  24695. BABYLON.serialize("coordinatesMode")
  24696. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24697. __decorate([
  24698. BABYLON.serialize()
  24699. ], BaseTexture.prototype, "wrapU", void 0);
  24700. __decorate([
  24701. BABYLON.serialize()
  24702. ], BaseTexture.prototype, "wrapV", void 0);
  24703. __decorate([
  24704. BABYLON.serialize()
  24705. ], BaseTexture.prototype, "wrapR", void 0);
  24706. __decorate([
  24707. BABYLON.serialize()
  24708. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24709. __decorate([
  24710. BABYLON.serialize()
  24711. ], BaseTexture.prototype, "isCube", void 0);
  24712. __decorate([
  24713. BABYLON.serialize()
  24714. ], BaseTexture.prototype, "is3D", void 0);
  24715. __decorate([
  24716. BABYLON.serialize()
  24717. ], BaseTexture.prototype, "gammaSpace", void 0);
  24718. __decorate([
  24719. BABYLON.serialize()
  24720. ], BaseTexture.prototype, "invertZ", void 0);
  24721. __decorate([
  24722. BABYLON.serialize()
  24723. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24724. __decorate([
  24725. BABYLON.serialize()
  24726. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24727. __decorate([
  24728. BABYLON.serialize()
  24729. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24730. __decorate([
  24731. BABYLON.serialize()
  24732. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24733. return BaseTexture;
  24734. }());
  24735. BABYLON.BaseTexture = BaseTexture;
  24736. })(BABYLON || (BABYLON = {}));
  24737. //# sourceMappingURL=babylon.baseTexture.js.map
  24738. var BABYLON;
  24739. (function (BABYLON) {
  24740. var Texture = /** @class */ (function (_super) {
  24741. __extends(Texture, _super);
  24742. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24743. if (noMipmap === void 0) { noMipmap = false; }
  24744. if (invertY === void 0) { invertY = true; }
  24745. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24746. if (onLoad === void 0) { onLoad = null; }
  24747. if (onError === void 0) { onError = null; }
  24748. if (buffer === void 0) { buffer = null; }
  24749. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24750. var _this = _super.call(this, scene) || this;
  24751. _this.uOffset = 0;
  24752. _this.vOffset = 0;
  24753. _this.uScale = 1.0;
  24754. _this.vScale = 1.0;
  24755. _this.uAng = 0;
  24756. _this.vAng = 0;
  24757. _this.wAng = 0;
  24758. _this._isBlocking = true;
  24759. _this.name = url || "";
  24760. _this.url = url;
  24761. _this._noMipmap = noMipmap;
  24762. _this._invertY = invertY;
  24763. _this._samplingMode = samplingMode;
  24764. _this._buffer = buffer;
  24765. _this._deleteBuffer = deleteBuffer;
  24766. if (format) {
  24767. _this._format = format;
  24768. }
  24769. scene = _this.getScene();
  24770. if (!scene) {
  24771. return _this;
  24772. }
  24773. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24774. var load = function () {
  24775. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24776. _this.onLoadObservable.notifyObservers(_this);
  24777. }
  24778. if (onLoad) {
  24779. onLoad();
  24780. }
  24781. if (!_this.isBlocking && scene) {
  24782. scene.resetCachedMaterial();
  24783. }
  24784. };
  24785. if (!_this.url) {
  24786. _this._delayedOnLoad = load;
  24787. _this._delayedOnError = onError;
  24788. return _this;
  24789. }
  24790. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24791. if (!_this._texture) {
  24792. if (!scene.useDelayedTextureLoading) {
  24793. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24794. if (deleteBuffer) {
  24795. delete _this._buffer;
  24796. }
  24797. }
  24798. else {
  24799. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24800. _this._delayedOnLoad = load;
  24801. _this._delayedOnError = onError;
  24802. }
  24803. }
  24804. else {
  24805. if (_this._texture.isReady) {
  24806. BABYLON.Tools.SetImmediate(function () { return load(); });
  24807. }
  24808. else {
  24809. _this._texture.onLoadedObservable.add(load);
  24810. }
  24811. }
  24812. return _this;
  24813. }
  24814. Object.defineProperty(Texture.prototype, "noMipmap", {
  24815. get: function () {
  24816. return this._noMipmap;
  24817. },
  24818. enumerable: true,
  24819. configurable: true
  24820. });
  24821. Object.defineProperty(Texture.prototype, "isBlocking", {
  24822. get: function () {
  24823. return this._isBlocking;
  24824. },
  24825. set: function (value) {
  24826. this._isBlocking = value;
  24827. },
  24828. enumerable: true,
  24829. configurable: true
  24830. });
  24831. Object.defineProperty(Texture.prototype, "samplingMode", {
  24832. get: function () {
  24833. return this._samplingMode;
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. Texture.prototype.updateURL = function (url) {
  24839. this.url = url;
  24840. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24841. this.delayLoad();
  24842. };
  24843. Texture.prototype.delayLoad = function () {
  24844. var _this = this;
  24845. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24846. return;
  24847. }
  24848. var scene = this.getScene();
  24849. if (!scene) {
  24850. return;
  24851. }
  24852. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24853. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24854. if (!this._texture) {
  24855. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24856. if (this._deleteBuffer) {
  24857. delete this._buffer;
  24858. }
  24859. }
  24860. else {
  24861. if (this._texture.isReady) {
  24862. BABYLON.Tools.SetImmediate(function () {
  24863. if (!_this._delayedOnLoad) {
  24864. return;
  24865. }
  24866. _this._delayedOnLoad();
  24867. });
  24868. }
  24869. else {
  24870. if (this._delayedOnLoad) {
  24871. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24872. }
  24873. }
  24874. }
  24875. };
  24876. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24877. if (!this._texture) {
  24878. return;
  24879. }
  24880. var scene = this.getScene();
  24881. if (!scene) {
  24882. return;
  24883. }
  24884. this._samplingMode = samplingMode;
  24885. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24886. };
  24887. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24888. x *= this.uScale;
  24889. y *= this.vScale;
  24890. x -= 0.5 * this.uScale;
  24891. y -= 0.5 * this.vScale;
  24892. z -= 0.5;
  24893. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24894. t.x += 0.5 * this.uScale + this.uOffset;
  24895. t.y += 0.5 * this.vScale + this.vOffset;
  24896. t.z += 0.5;
  24897. };
  24898. Texture.prototype.getTextureMatrix = function () {
  24899. var _this = this;
  24900. if (this.uOffset === this._cachedUOffset &&
  24901. this.vOffset === this._cachedVOffset &&
  24902. this.uScale === this._cachedUScale &&
  24903. this.vScale === this._cachedVScale &&
  24904. this.uAng === this._cachedUAng &&
  24905. this.vAng === this._cachedVAng &&
  24906. this.wAng === this._cachedWAng) {
  24907. return this._cachedTextureMatrix;
  24908. }
  24909. this._cachedUOffset = this.uOffset;
  24910. this._cachedVOffset = this.vOffset;
  24911. this._cachedUScale = this.uScale;
  24912. this._cachedVScale = this.vScale;
  24913. this._cachedUAng = this.uAng;
  24914. this._cachedVAng = this.vAng;
  24915. this._cachedWAng = this.wAng;
  24916. if (!this._cachedTextureMatrix) {
  24917. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24918. this._rowGenerationMatrix = new BABYLON.Matrix();
  24919. this._t0 = BABYLON.Vector3.Zero();
  24920. this._t1 = BABYLON.Vector3.Zero();
  24921. this._t2 = BABYLON.Vector3.Zero();
  24922. }
  24923. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24924. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24925. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24926. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24927. this._t1.subtractInPlace(this._t0);
  24928. this._t2.subtractInPlace(this._t0);
  24929. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24930. this._cachedTextureMatrix.m[0] = this._t1.x;
  24931. this._cachedTextureMatrix.m[1] = this._t1.y;
  24932. this._cachedTextureMatrix.m[2] = this._t1.z;
  24933. this._cachedTextureMatrix.m[4] = this._t2.x;
  24934. this._cachedTextureMatrix.m[5] = this._t2.y;
  24935. this._cachedTextureMatrix.m[6] = this._t2.z;
  24936. this._cachedTextureMatrix.m[8] = this._t0.x;
  24937. this._cachedTextureMatrix.m[9] = this._t0.y;
  24938. this._cachedTextureMatrix.m[10] = this._t0.z;
  24939. var scene = this.getScene();
  24940. if (!scene) {
  24941. return this._cachedTextureMatrix;
  24942. }
  24943. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24944. return mat.hasTexture(_this);
  24945. });
  24946. return this._cachedTextureMatrix;
  24947. };
  24948. Texture.prototype.getReflectionTextureMatrix = function () {
  24949. var _this = this;
  24950. var scene = this.getScene();
  24951. if (!scene) {
  24952. return this._cachedTextureMatrix;
  24953. }
  24954. if (this.uOffset === this._cachedUOffset &&
  24955. this.vOffset === this._cachedVOffset &&
  24956. this.uScale === this._cachedUScale &&
  24957. this.vScale === this._cachedVScale &&
  24958. this.coordinatesMode === this._cachedCoordinatesMode) {
  24959. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24960. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24961. return this._cachedTextureMatrix;
  24962. }
  24963. }
  24964. else {
  24965. return this._cachedTextureMatrix;
  24966. }
  24967. }
  24968. if (!this._cachedTextureMatrix) {
  24969. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24970. }
  24971. if (!this._projectionModeMatrix) {
  24972. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24973. }
  24974. this._cachedUOffset = this.uOffset;
  24975. this._cachedVOffset = this.vOffset;
  24976. this._cachedUScale = this.uScale;
  24977. this._cachedVScale = this.vScale;
  24978. this._cachedCoordinatesMode = this.coordinatesMode;
  24979. switch (this.coordinatesMode) {
  24980. case Texture.PLANAR_MODE:
  24981. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24982. this._cachedTextureMatrix[0] = this.uScale;
  24983. this._cachedTextureMatrix[5] = this.vScale;
  24984. this._cachedTextureMatrix[12] = this.uOffset;
  24985. this._cachedTextureMatrix[13] = this.vOffset;
  24986. break;
  24987. case Texture.PROJECTION_MODE:
  24988. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24989. this._projectionModeMatrix.m[0] = 0.5;
  24990. this._projectionModeMatrix.m[5] = -0.5;
  24991. this._projectionModeMatrix.m[10] = 0.0;
  24992. this._projectionModeMatrix.m[12] = 0.5;
  24993. this._projectionModeMatrix.m[13] = 0.5;
  24994. this._projectionModeMatrix.m[14] = 1.0;
  24995. this._projectionModeMatrix.m[15] = 1.0;
  24996. var projectionMatrix = scene.getProjectionMatrix();
  24997. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24998. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24999. break;
  25000. default:
  25001. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25002. break;
  25003. }
  25004. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25005. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25006. });
  25007. return this._cachedTextureMatrix;
  25008. };
  25009. Texture.prototype.clone = function () {
  25010. var _this = this;
  25011. return BABYLON.SerializationHelper.Clone(function () {
  25012. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25013. }, this);
  25014. };
  25015. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25016. get: function () {
  25017. if (!this._onLoadObservable) {
  25018. this._onLoadObservable = new BABYLON.Observable();
  25019. }
  25020. return this._onLoadObservable;
  25021. },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. Texture.prototype.serialize = function () {
  25026. var serializationObject = _super.prototype.serialize.call(this);
  25027. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25028. serializationObject.base64String = this._buffer;
  25029. serializationObject.name = serializationObject.name.replace("data:", "");
  25030. }
  25031. return serializationObject;
  25032. };
  25033. Texture.prototype.getClassName = function () {
  25034. return "Texture";
  25035. };
  25036. Texture.prototype.dispose = function () {
  25037. _super.prototype.dispose.call(this);
  25038. if (this.onLoadObservable) {
  25039. this.onLoadObservable.clear();
  25040. this._onLoadObservable = null;
  25041. }
  25042. this._delayedOnLoad = null;
  25043. this._delayedOnError = null;
  25044. };
  25045. // Statics
  25046. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25047. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25048. if (onLoad === void 0) { onLoad = null; }
  25049. if (onError === void 0) { onError = null; }
  25050. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25051. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25052. };
  25053. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25054. if (parsedTexture.customType) {
  25055. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25056. // Update Sampling Mode
  25057. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25058. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25059. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25060. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25061. }
  25062. }
  25063. return parsedCustomTexture;
  25064. }
  25065. if (parsedTexture.isCube) {
  25066. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25067. }
  25068. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25069. return null;
  25070. }
  25071. var texture = BABYLON.SerializationHelper.Parse(function () {
  25072. var generateMipMaps = true;
  25073. if (parsedTexture.noMipmap) {
  25074. generateMipMaps = false;
  25075. }
  25076. if (parsedTexture.mirrorPlane) {
  25077. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25078. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25079. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25080. return mirrorTexture;
  25081. }
  25082. else if (parsedTexture.isRenderTarget) {
  25083. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25084. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25085. return renderTargetTexture;
  25086. }
  25087. else {
  25088. var texture;
  25089. if (parsedTexture.base64String) {
  25090. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25091. }
  25092. else {
  25093. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25094. }
  25095. return texture;
  25096. }
  25097. }, parsedTexture, scene);
  25098. // Update Sampling Mode
  25099. if (parsedTexture.samplingMode) {
  25100. var sampling = parsedTexture.samplingMode;
  25101. if (texture._samplingMode !== sampling) {
  25102. texture.updateSamplingMode(sampling);
  25103. }
  25104. }
  25105. // Animations
  25106. if (parsedTexture.animations) {
  25107. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25108. var parsedAnimation = parsedTexture.animations[animationIndex];
  25109. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25110. }
  25111. }
  25112. return texture;
  25113. };
  25114. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25115. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25116. if (noMipmap === void 0) { noMipmap = false; }
  25117. if (invertY === void 0) { invertY = true; }
  25118. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25119. if (onLoad === void 0) { onLoad = null; }
  25120. if (onError === void 0) { onError = null; }
  25121. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25122. if (name.substr(0, 5) !== "data:") {
  25123. name = "data:" + name;
  25124. }
  25125. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25126. };
  25127. // Constants
  25128. Texture.NEAREST_SAMPLINGMODE = 1;
  25129. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25130. Texture.BILINEAR_SAMPLINGMODE = 2;
  25131. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25132. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25133. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25134. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25135. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25136. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25137. Texture.NEAREST_LINEAR = 7;
  25138. Texture.NEAREST_NEAREST = 8;
  25139. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25140. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25141. Texture.LINEAR_LINEAR = 11;
  25142. Texture.LINEAR_NEAREST = 12;
  25143. Texture.EXPLICIT_MODE = 0;
  25144. Texture.SPHERICAL_MODE = 1;
  25145. Texture.PLANAR_MODE = 2;
  25146. Texture.CUBIC_MODE = 3;
  25147. Texture.PROJECTION_MODE = 4;
  25148. Texture.SKYBOX_MODE = 5;
  25149. Texture.INVCUBIC_MODE = 6;
  25150. Texture.EQUIRECTANGULAR_MODE = 7;
  25151. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25152. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25153. Texture.CLAMP_ADDRESSMODE = 0;
  25154. Texture.WRAP_ADDRESSMODE = 1;
  25155. Texture.MIRROR_ADDRESSMODE = 2;
  25156. __decorate([
  25157. BABYLON.serialize()
  25158. ], Texture.prototype, "url", void 0);
  25159. __decorate([
  25160. BABYLON.serialize()
  25161. ], Texture.prototype, "uOffset", void 0);
  25162. __decorate([
  25163. BABYLON.serialize()
  25164. ], Texture.prototype, "vOffset", void 0);
  25165. __decorate([
  25166. BABYLON.serialize()
  25167. ], Texture.prototype, "uScale", void 0);
  25168. __decorate([
  25169. BABYLON.serialize()
  25170. ], Texture.prototype, "vScale", void 0);
  25171. __decorate([
  25172. BABYLON.serialize()
  25173. ], Texture.prototype, "uAng", void 0);
  25174. __decorate([
  25175. BABYLON.serialize()
  25176. ], Texture.prototype, "vAng", void 0);
  25177. __decorate([
  25178. BABYLON.serialize()
  25179. ], Texture.prototype, "wAng", void 0);
  25180. __decorate([
  25181. BABYLON.serialize()
  25182. ], Texture.prototype, "isBlocking", null);
  25183. return Texture;
  25184. }(BABYLON.BaseTexture));
  25185. BABYLON.Texture = Texture;
  25186. })(BABYLON || (BABYLON = {}));
  25187. //# sourceMappingURL=babylon.texture.js.map
  25188. var BABYLON;
  25189. (function (BABYLON) {
  25190. var _InstancesBatch = /** @class */ (function () {
  25191. function _InstancesBatch() {
  25192. this.mustReturn = false;
  25193. this.visibleInstances = new Array();
  25194. this.renderSelf = new Array();
  25195. }
  25196. return _InstancesBatch;
  25197. }());
  25198. BABYLON._InstancesBatch = _InstancesBatch;
  25199. var Mesh = /** @class */ (function (_super) {
  25200. __extends(Mesh, _super);
  25201. /**
  25202. * @constructor
  25203. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25204. * @param {Scene} scene The scene to add this mesh to.
  25205. * @param {Node} parent The parent of this mesh, if it has one
  25206. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25207. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25208. * When false, achieved by calling a clone(), also passing False.
  25209. * This will make creation of children, recursive.
  25210. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25211. */
  25212. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25213. if (scene === void 0) { scene = null; }
  25214. if (parent === void 0) { parent = null; }
  25215. if (source === void 0) { source = null; }
  25216. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25217. var _this = _super.call(this, name, scene) || this;
  25218. // Events
  25219. /**
  25220. * An event triggered before rendering the mesh
  25221. * @type {BABYLON.Observable}
  25222. */
  25223. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25224. /**
  25225. * An event triggered after rendering the mesh
  25226. * @type {BABYLON.Observable}
  25227. */
  25228. _this.onAfterRenderObservable = new BABYLON.Observable();
  25229. /**
  25230. * An event triggered before drawing the mesh
  25231. * @type {BABYLON.Observable}
  25232. */
  25233. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25234. // Members
  25235. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25236. _this.instances = new Array();
  25237. _this._LODLevels = new Array();
  25238. _this._visibleInstances = {};
  25239. _this._renderIdForInstances = new Array();
  25240. _this._batchCache = new _InstancesBatch();
  25241. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25242. // Use by builder only to know what orientation were the mesh build in.
  25243. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25244. _this.overrideMaterialSideOrientation = null;
  25245. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25246. // Will be used to save a source mesh reference, If any
  25247. _this._source = null;
  25248. scene = _this.getScene();
  25249. if (source) {
  25250. // Source mesh
  25251. _this._source = source;
  25252. // Geometry
  25253. if (source._geometry) {
  25254. source._geometry.applyToMesh(_this);
  25255. }
  25256. // Deep copy
  25257. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25258. // Metadata
  25259. if (source.metadata && source.metadata.clone) {
  25260. _this.metadata = source.metadata.clone();
  25261. }
  25262. else {
  25263. _this.metadata = source.metadata;
  25264. }
  25265. // Tags
  25266. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25267. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25268. }
  25269. // Parent
  25270. _this.parent = source.parent;
  25271. // Pivot
  25272. _this.setPivotMatrix(source.getPivotMatrix());
  25273. _this.id = name + "." + source.id;
  25274. // Material
  25275. _this.material = source.material;
  25276. var index;
  25277. if (!doNotCloneChildren) {
  25278. // Children
  25279. var directDescendants = source.getDescendants(true);
  25280. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25281. var child = directDescendants[index_1];
  25282. if (child.clone) {
  25283. child.clone(name + "." + child.name, _this);
  25284. }
  25285. }
  25286. }
  25287. // Physics clone
  25288. var physicsEngine = _this.getScene().getPhysicsEngine();
  25289. if (clonePhysicsImpostor && physicsEngine) {
  25290. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25291. if (impostor) {
  25292. _this.physicsImpostor = impostor.clone(_this);
  25293. }
  25294. }
  25295. // Particles
  25296. for (index = 0; index < scene.particleSystems.length; index++) {
  25297. var system = scene.particleSystems[index];
  25298. if (system.emitter === source) {
  25299. system.clone(system.name, _this);
  25300. }
  25301. }
  25302. _this.computeWorldMatrix(true);
  25303. }
  25304. // Parent
  25305. if (parent !== null) {
  25306. _this.parent = parent;
  25307. }
  25308. return _this;
  25309. }
  25310. Object.defineProperty(Mesh, "FRONTSIDE", {
  25311. /**
  25312. * Mesh side orientation : usually the external or front surface
  25313. */
  25314. get: function () {
  25315. return Mesh._FRONTSIDE;
  25316. },
  25317. enumerable: true,
  25318. configurable: true
  25319. });
  25320. Object.defineProperty(Mesh, "BACKSIDE", {
  25321. /**
  25322. * Mesh side orientation : usually the internal or back surface
  25323. */
  25324. get: function () {
  25325. return Mesh._BACKSIDE;
  25326. },
  25327. enumerable: true,
  25328. configurable: true
  25329. });
  25330. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25331. /**
  25332. * Mesh side orientation : both internal and external or front and back surfaces
  25333. */
  25334. get: function () {
  25335. return Mesh._DOUBLESIDE;
  25336. },
  25337. enumerable: true,
  25338. configurable: true
  25339. });
  25340. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25341. /**
  25342. * Mesh side orientation : by default, `FRONTSIDE`
  25343. */
  25344. get: function () {
  25345. return Mesh._DEFAULTSIDE;
  25346. },
  25347. enumerable: true,
  25348. configurable: true
  25349. });
  25350. Object.defineProperty(Mesh, "NO_CAP", {
  25351. /**
  25352. * Mesh cap setting : no cap
  25353. */
  25354. get: function () {
  25355. return Mesh._NO_CAP;
  25356. },
  25357. enumerable: true,
  25358. configurable: true
  25359. });
  25360. Object.defineProperty(Mesh, "CAP_START", {
  25361. /**
  25362. * Mesh cap setting : one cap at the beginning of the mesh
  25363. */
  25364. get: function () {
  25365. return Mesh._CAP_START;
  25366. },
  25367. enumerable: true,
  25368. configurable: true
  25369. });
  25370. Object.defineProperty(Mesh, "CAP_END", {
  25371. /**
  25372. * Mesh cap setting : one cap at the end of the mesh
  25373. */
  25374. get: function () {
  25375. return Mesh._CAP_END;
  25376. },
  25377. enumerable: true,
  25378. configurable: true
  25379. });
  25380. Object.defineProperty(Mesh, "CAP_ALL", {
  25381. /**
  25382. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25383. */
  25384. get: function () {
  25385. return Mesh._CAP_ALL;
  25386. },
  25387. enumerable: true,
  25388. configurable: true
  25389. });
  25390. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25391. set: function (callback) {
  25392. if (this._onBeforeDrawObserver) {
  25393. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25394. }
  25395. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25396. },
  25397. enumerable: true,
  25398. configurable: true
  25399. });
  25400. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25401. get: function () {
  25402. return this._morphTargetManager;
  25403. },
  25404. set: function (value) {
  25405. if (this._morphTargetManager === value) {
  25406. return;
  25407. }
  25408. this._morphTargetManager = value;
  25409. this._syncGeometryWithMorphTargetManager();
  25410. },
  25411. enumerable: true,
  25412. configurable: true
  25413. });
  25414. Object.defineProperty(Mesh.prototype, "source", {
  25415. get: function () {
  25416. return this._source;
  25417. },
  25418. enumerable: true,
  25419. configurable: true
  25420. });
  25421. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25422. get: function () {
  25423. return this._unIndexed;
  25424. },
  25425. set: function (value) {
  25426. if (this._unIndexed !== value) {
  25427. this._unIndexed = value;
  25428. this._markSubMeshesAsAttributesDirty();
  25429. }
  25430. },
  25431. enumerable: true,
  25432. configurable: true
  25433. });
  25434. // Methods
  25435. /**
  25436. * Returns the string "Mesh".
  25437. */
  25438. Mesh.prototype.getClassName = function () {
  25439. return "Mesh";
  25440. };
  25441. /**
  25442. * Returns a string.
  25443. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25444. */
  25445. Mesh.prototype.toString = function (fullDetails) {
  25446. var ret = _super.prototype.toString.call(this, fullDetails);
  25447. ret += ", n vertices: " + this.getTotalVertices();
  25448. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25449. if (this.animations) {
  25450. for (var i = 0; i < this.animations.length; i++) {
  25451. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25452. }
  25453. }
  25454. if (fullDetails) {
  25455. if (this._geometry) {
  25456. var ib = this.getIndices();
  25457. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25458. if (vb && ib) {
  25459. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25460. }
  25461. }
  25462. else {
  25463. ret += ", flat shading: UNKNOWN";
  25464. }
  25465. }
  25466. return ret;
  25467. };
  25468. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25469. /**
  25470. * True if the mesh has some Levels Of Details (LOD).
  25471. * Returns a boolean.
  25472. */
  25473. get: function () {
  25474. return this._LODLevels.length > 0;
  25475. },
  25476. enumerable: true,
  25477. configurable: true
  25478. });
  25479. /**
  25480. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  25481. * @returns an array of {BABYLON.MeshLODLevel}
  25482. */
  25483. Mesh.prototype.getLODLevels = function () {
  25484. return this._LODLevels;
  25485. };
  25486. Mesh.prototype._sortLODLevels = function () {
  25487. this._LODLevels.sort(function (a, b) {
  25488. if (a.distance < b.distance) {
  25489. return 1;
  25490. }
  25491. if (a.distance > b.distance) {
  25492. return -1;
  25493. }
  25494. return 0;
  25495. });
  25496. };
  25497. /**
  25498. * Add a mesh as LOD level triggered at the given distance.
  25499. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25500. * @param {number} distance The distance from the center of the object to show this level
  25501. * @param {Mesh} mesh The mesh to be added as LOD level
  25502. * @return {Mesh} This mesh (for chaining)
  25503. */
  25504. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25505. if (mesh && mesh._masterMesh) {
  25506. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25507. return this;
  25508. }
  25509. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25510. this._LODLevels.push(level);
  25511. if (mesh) {
  25512. mesh._masterMesh = this;
  25513. }
  25514. this._sortLODLevels();
  25515. return this;
  25516. };
  25517. /**
  25518. * Returns the LOD level mesh at the passed distance or null if not found.
  25519. * It is related to the method `addLODLevel(distance, mesh)`.
  25520. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25521. * Returns an object Mesh or `null`.
  25522. */
  25523. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25524. for (var index = 0; index < this._LODLevels.length; index++) {
  25525. var level = this._LODLevels[index];
  25526. if (level.distance === distance) {
  25527. return level.mesh;
  25528. }
  25529. }
  25530. return null;
  25531. };
  25532. /**
  25533. * Remove a mesh from the LOD array
  25534. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25535. * @param {Mesh} mesh The mesh to be removed.
  25536. * @return {Mesh} This mesh (for chaining)
  25537. */
  25538. Mesh.prototype.removeLODLevel = function (mesh) {
  25539. for (var index = 0; index < this._LODLevels.length; index++) {
  25540. if (this._LODLevels[index].mesh === mesh) {
  25541. this._LODLevels.splice(index, 1);
  25542. if (mesh) {
  25543. mesh._masterMesh = null;
  25544. }
  25545. }
  25546. }
  25547. this._sortLODLevels();
  25548. return this;
  25549. };
  25550. /**
  25551. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25552. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25553. */
  25554. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25555. if (!this._LODLevels || this._LODLevels.length === 0) {
  25556. return this;
  25557. }
  25558. var bSphere;
  25559. if (boundingSphere) {
  25560. bSphere = boundingSphere;
  25561. }
  25562. else {
  25563. var boundingInfo = this.getBoundingInfo();
  25564. bSphere = boundingInfo.boundingSphere;
  25565. }
  25566. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25567. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25568. if (this.onLODLevelSelection) {
  25569. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25570. }
  25571. return this;
  25572. }
  25573. for (var index = 0; index < this._LODLevels.length; index++) {
  25574. var level = this._LODLevels[index];
  25575. if (level.distance < distanceToCamera) {
  25576. if (level.mesh) {
  25577. level.mesh._preActivate();
  25578. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25579. }
  25580. if (this.onLODLevelSelection) {
  25581. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25582. }
  25583. return level.mesh;
  25584. }
  25585. }
  25586. if (this.onLODLevelSelection) {
  25587. this.onLODLevelSelection(distanceToCamera, this, this);
  25588. }
  25589. return this;
  25590. };
  25591. Object.defineProperty(Mesh.prototype, "geometry", {
  25592. /**
  25593. * Returns the mesh internal Geometry object.
  25594. */
  25595. get: function () {
  25596. return this._geometry;
  25597. },
  25598. enumerable: true,
  25599. configurable: true
  25600. });
  25601. /**
  25602. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25603. */
  25604. Mesh.prototype.getTotalVertices = function () {
  25605. if (this._geometry === null || this._geometry === undefined) {
  25606. return 0;
  25607. }
  25608. return this._geometry.getTotalVertices();
  25609. };
  25610. /**
  25611. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25612. * 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.
  25613. * You can force the copy with forceCopy === true
  25614. * Returns null if the mesh has no geometry or no vertex buffer.
  25615. * Possible `kind` values :
  25616. * - BABYLON.VertexBuffer.PositionKind
  25617. * - BABYLON.VertexBuffer.UVKind
  25618. * - BABYLON.VertexBuffer.UV2Kind
  25619. * - BABYLON.VertexBuffer.UV3Kind
  25620. * - BABYLON.VertexBuffer.UV4Kind
  25621. * - BABYLON.VertexBuffer.UV5Kind
  25622. * - BABYLON.VertexBuffer.UV6Kind
  25623. * - BABYLON.VertexBuffer.ColorKind
  25624. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25625. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25626. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25627. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25628. */
  25629. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25630. if (!this._geometry) {
  25631. return null;
  25632. }
  25633. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25634. };
  25635. /**
  25636. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25637. * Returns `null` if the mesh has no geometry.
  25638. * Possible `kind` values :
  25639. * - BABYLON.VertexBuffer.PositionKind
  25640. * - BABYLON.VertexBuffer.UVKind
  25641. * - BABYLON.VertexBuffer.UV2Kind
  25642. * - BABYLON.VertexBuffer.UV3Kind
  25643. * - BABYLON.VertexBuffer.UV4Kind
  25644. * - BABYLON.VertexBuffer.UV5Kind
  25645. * - BABYLON.VertexBuffer.UV6Kind
  25646. * - BABYLON.VertexBuffer.ColorKind
  25647. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25648. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25649. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25650. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25651. */
  25652. Mesh.prototype.getVertexBuffer = function (kind) {
  25653. if (!this._geometry) {
  25654. return null;
  25655. }
  25656. return this._geometry.getVertexBuffer(kind);
  25657. };
  25658. /**
  25659. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25660. * Possible `kind` values :
  25661. * - BABYLON.VertexBuffer.PositionKind
  25662. * - BABYLON.VertexBuffer.UVKind
  25663. * - BABYLON.VertexBuffer.UV2Kind
  25664. * - BABYLON.VertexBuffer.UV3Kind
  25665. * - BABYLON.VertexBuffer.UV4Kind
  25666. * - BABYLON.VertexBuffer.UV5Kind
  25667. * - BABYLON.VertexBuffer.UV6Kind
  25668. * - BABYLON.VertexBuffer.ColorKind
  25669. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25670. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25671. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25672. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25673. */
  25674. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25675. if (!this._geometry) {
  25676. if (this._delayInfo) {
  25677. return this._delayInfo.indexOf(kind) !== -1;
  25678. }
  25679. return false;
  25680. }
  25681. return this._geometry.isVerticesDataPresent(kind);
  25682. };
  25683. /**
  25684. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25685. * Possible `kind` values :
  25686. * - BABYLON.VertexBuffer.PositionKind
  25687. * - BABYLON.VertexBuffer.UVKind
  25688. * - BABYLON.VertexBuffer.UV2Kind
  25689. * - BABYLON.VertexBuffer.UV3Kind
  25690. * - BABYLON.VertexBuffer.UV4Kind
  25691. * - BABYLON.VertexBuffer.UV5Kind
  25692. * - BABYLON.VertexBuffer.UV6Kind
  25693. * - BABYLON.VertexBuffer.ColorKind
  25694. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25695. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25696. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25697. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25698. */
  25699. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25700. if (!this._geometry) {
  25701. if (this._delayInfo) {
  25702. return this._delayInfo.indexOf(kind) !== -1;
  25703. }
  25704. return false;
  25705. }
  25706. return this._geometry.isVertexBufferUpdatable(kind);
  25707. };
  25708. /**
  25709. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25710. * Possible `kind` values :
  25711. * - BABYLON.VertexBuffer.PositionKind
  25712. * - BABYLON.VertexBuffer.UVKind
  25713. * - BABYLON.VertexBuffer.UV2Kind
  25714. * - BABYLON.VertexBuffer.UV3Kind
  25715. * - BABYLON.VertexBuffer.UV4Kind
  25716. * - BABYLON.VertexBuffer.UV5Kind
  25717. * - BABYLON.VertexBuffer.UV6Kind
  25718. * - BABYLON.VertexBuffer.ColorKind
  25719. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25720. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25721. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25722. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25723. */
  25724. Mesh.prototype.getVerticesDataKinds = function () {
  25725. if (!this._geometry) {
  25726. var result = new Array();
  25727. if (this._delayInfo) {
  25728. this._delayInfo.forEach(function (kind, index, array) {
  25729. result.push(kind);
  25730. });
  25731. }
  25732. return result;
  25733. }
  25734. return this._geometry.getVerticesDataKinds();
  25735. };
  25736. /**
  25737. * Returns a positive integer : the total number of indices in this mesh geometry.
  25738. * Returns zero if the mesh has no geometry.
  25739. */
  25740. Mesh.prototype.getTotalIndices = function () {
  25741. if (!this._geometry) {
  25742. return 0;
  25743. }
  25744. return this._geometry.getTotalIndices();
  25745. };
  25746. /**
  25747. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25748. * 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.
  25749. * Returns an empty array if the mesh has no geometry.
  25750. */
  25751. Mesh.prototype.getIndices = function (copyWhenShared) {
  25752. if (!this._geometry) {
  25753. return [];
  25754. }
  25755. return this._geometry.getIndices(copyWhenShared);
  25756. };
  25757. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25758. get: function () {
  25759. return this._masterMesh !== null && this._masterMesh !== undefined;
  25760. },
  25761. enumerable: true,
  25762. configurable: true
  25763. });
  25764. /**
  25765. * Determine if the current mesh is ready to be rendered
  25766. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25767. * @returns true if all associated assets are ready (material, textures, shaders)
  25768. */
  25769. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25770. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25771. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25772. return false;
  25773. }
  25774. if (!_super.prototype.isReady.call(this)) {
  25775. return false;
  25776. }
  25777. if (!this.subMeshes || this.subMeshes.length === 0) {
  25778. return true;
  25779. }
  25780. var engine = this.getEngine();
  25781. var scene = this.getScene();
  25782. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25783. this.computeWorldMatrix();
  25784. var mat = this.material || scene.defaultMaterial;
  25785. if (mat) {
  25786. if (mat.storeEffectOnSubMeshes) {
  25787. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25788. var subMesh = _a[_i];
  25789. var effectiveMaterial = subMesh.getMaterial();
  25790. if (effectiveMaterial) {
  25791. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25792. return false;
  25793. }
  25794. }
  25795. }
  25796. }
  25797. else {
  25798. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25799. return false;
  25800. }
  25801. }
  25802. }
  25803. // Shadows
  25804. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25805. var light = _c[_b];
  25806. var generator = light.getShadowGenerator();
  25807. if (generator) {
  25808. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25809. var subMesh = _e[_d];
  25810. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25811. return false;
  25812. }
  25813. }
  25814. }
  25815. }
  25816. // LOD
  25817. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25818. var lod = _g[_f];
  25819. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25820. return false;
  25821. }
  25822. }
  25823. return true;
  25824. };
  25825. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25826. /**
  25827. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25828. * This property is pertinent only for updatable parametric shapes.
  25829. */
  25830. get: function () {
  25831. return this._areNormalsFrozen;
  25832. },
  25833. enumerable: true,
  25834. configurable: true
  25835. });
  25836. /**
  25837. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25838. * It has no effect at all on other shapes.
  25839. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25840. * Returns the Mesh.
  25841. */
  25842. Mesh.prototype.freezeNormals = function () {
  25843. this._areNormalsFrozen = true;
  25844. return this;
  25845. };
  25846. /**
  25847. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25848. * It has no effect at all on other shapes.
  25849. * It reactivates the mesh normals computation if it was previously frozen.
  25850. * Returns the Mesh.
  25851. */
  25852. Mesh.prototype.unfreezeNormals = function () {
  25853. this._areNormalsFrozen = false;
  25854. return this;
  25855. };
  25856. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25857. /**
  25858. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25859. */
  25860. set: function (count) {
  25861. this._overridenInstanceCount = count;
  25862. },
  25863. enumerable: true,
  25864. configurable: true
  25865. });
  25866. // Methods
  25867. Mesh.prototype._preActivate = function () {
  25868. var sceneRenderId = this.getScene().getRenderId();
  25869. if (this._preActivateId === sceneRenderId) {
  25870. return this;
  25871. }
  25872. this._preActivateId = sceneRenderId;
  25873. this._visibleInstances = null;
  25874. return this;
  25875. };
  25876. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25877. if (this._visibleInstances) {
  25878. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25879. }
  25880. return this;
  25881. };
  25882. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25883. if (!this._visibleInstances) {
  25884. this._visibleInstances = {};
  25885. this._visibleInstances.defaultRenderId = renderId;
  25886. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25887. }
  25888. if (!this._visibleInstances[renderId]) {
  25889. this._visibleInstances[renderId] = new Array();
  25890. }
  25891. this._visibleInstances[renderId].push(instance);
  25892. return this;
  25893. };
  25894. /**
  25895. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25896. * This means the mesh underlying bounding box and sphere are recomputed.
  25897. * Returns the Mesh.
  25898. */
  25899. Mesh.prototype.refreshBoundingInfo = function () {
  25900. return this._refreshBoundingInfo(false);
  25901. };
  25902. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25903. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25904. return this;
  25905. }
  25906. var data = this._getPositionData(applySkeleton);
  25907. if (data) {
  25908. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25909. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25910. }
  25911. if (this.subMeshes) {
  25912. for (var index = 0; index < this.subMeshes.length; index++) {
  25913. this.subMeshes[index].refreshBoundingInfo();
  25914. }
  25915. }
  25916. this._updateBoundingInfo();
  25917. return this;
  25918. };
  25919. Mesh.prototype._getPositionData = function (applySkeleton) {
  25920. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25921. if (data && applySkeleton && this.skeleton) {
  25922. data = BABYLON.Tools.Slice(data);
  25923. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25924. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25925. if (matricesWeightsData && matricesIndicesData) {
  25926. var needExtras = this.numBoneInfluencers > 4;
  25927. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25928. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25929. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25930. var tempVector = BABYLON.Tmp.Vector3[0];
  25931. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25932. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25933. var matWeightIdx = 0;
  25934. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25935. finalMatrix.reset();
  25936. var inf;
  25937. var weight;
  25938. for (inf = 0; inf < 4; inf++) {
  25939. weight = matricesWeightsData[matWeightIdx + inf];
  25940. if (weight <= 0)
  25941. break;
  25942. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25943. finalMatrix.addToSelf(tempMatrix);
  25944. }
  25945. if (needExtras) {
  25946. for (inf = 0; inf < 4; inf++) {
  25947. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25948. if (weight <= 0)
  25949. break;
  25950. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25951. finalMatrix.addToSelf(tempMatrix);
  25952. }
  25953. }
  25954. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25955. tempVector.toArray(data, index);
  25956. }
  25957. }
  25958. }
  25959. return data;
  25960. };
  25961. Mesh.prototype._createGlobalSubMesh = function (force) {
  25962. var totalVertices = this.getTotalVertices();
  25963. if (!totalVertices || !this.getIndices()) {
  25964. return null;
  25965. }
  25966. // Check if we need to recreate the submeshes
  25967. if (this.subMeshes && this.subMeshes.length > 0) {
  25968. var ib = this.getIndices();
  25969. if (!ib) {
  25970. return null;
  25971. }
  25972. var totalIndices = ib.length;
  25973. var needToRecreate = false;
  25974. if (force) {
  25975. needToRecreate = true;
  25976. }
  25977. else {
  25978. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25979. var submesh = _a[_i];
  25980. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25981. needToRecreate = true;
  25982. break;
  25983. }
  25984. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25985. needToRecreate = true;
  25986. break;
  25987. }
  25988. }
  25989. }
  25990. if (!needToRecreate) {
  25991. return this.subMeshes[0];
  25992. }
  25993. }
  25994. this.releaseSubMeshes();
  25995. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25996. };
  25997. Mesh.prototype.subdivide = function (count) {
  25998. if (count < 1) {
  25999. return;
  26000. }
  26001. var totalIndices = this.getTotalIndices();
  26002. var subdivisionSize = (totalIndices / count) | 0;
  26003. var offset = 0;
  26004. // Ensure that subdivisionSize is a multiple of 3
  26005. while (subdivisionSize % 3 !== 0) {
  26006. subdivisionSize++;
  26007. }
  26008. this.releaseSubMeshes();
  26009. for (var index = 0; index < count; index++) {
  26010. if (offset >= totalIndices) {
  26011. break;
  26012. }
  26013. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26014. offset += subdivisionSize;
  26015. }
  26016. this.synchronizeInstances();
  26017. };
  26018. /**
  26019. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26020. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26021. * The `data` are either a numeric array either a Float32Array.
  26022. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26023. * 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).
  26024. * Note that a new underlying VertexBuffer object is created each call.
  26025. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26026. *
  26027. * Possible `kind` values :
  26028. * - BABYLON.VertexBuffer.PositionKind
  26029. * - BABYLON.VertexBuffer.UVKind
  26030. * - BABYLON.VertexBuffer.UV2Kind
  26031. * - BABYLON.VertexBuffer.UV3Kind
  26032. * - BABYLON.VertexBuffer.UV4Kind
  26033. * - BABYLON.VertexBuffer.UV5Kind
  26034. * - BABYLON.VertexBuffer.UV6Kind
  26035. * - BABYLON.VertexBuffer.ColorKind
  26036. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26037. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26038. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26039. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26040. *
  26041. * Returns the Mesh.
  26042. */
  26043. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26044. if (updatable === void 0) { updatable = false; }
  26045. if (!this._geometry) {
  26046. var vertexData = new BABYLON.VertexData();
  26047. vertexData.set(data, kind);
  26048. var scene = this.getScene();
  26049. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26050. }
  26051. else {
  26052. this._geometry.setVerticesData(kind, data, updatable, stride);
  26053. }
  26054. return this;
  26055. };
  26056. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26057. if (updatable === void 0) { updatable = true; }
  26058. var vb = this.getVertexBuffer(kind);
  26059. if (!vb || vb.isUpdatable() === updatable) {
  26060. return;
  26061. }
  26062. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26063. };
  26064. /**
  26065. * Sets the mesh VertexBuffer.
  26066. * Returns the Mesh.
  26067. */
  26068. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26069. if (!this._geometry) {
  26070. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26071. }
  26072. this._geometry.setVerticesBuffer(buffer);
  26073. return this;
  26074. };
  26075. /**
  26076. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26077. * If the mesh has no geometry, it is simply returned as it is.
  26078. * The `data` are either a numeric array either a Float32Array.
  26079. * No new underlying VertexBuffer object is created.
  26080. * 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.
  26081. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26082. *
  26083. * Possible `kind` values :
  26084. * - BABYLON.VertexBuffer.PositionKind
  26085. * - BABYLON.VertexBuffer.UVKind
  26086. * - BABYLON.VertexBuffer.UV2Kind
  26087. * - BABYLON.VertexBuffer.UV3Kind
  26088. * - BABYLON.VertexBuffer.UV4Kind
  26089. * - BABYLON.VertexBuffer.UV5Kind
  26090. * - BABYLON.VertexBuffer.UV6Kind
  26091. * - BABYLON.VertexBuffer.ColorKind
  26092. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26093. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26094. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26095. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26096. *
  26097. * Returns the Mesh.
  26098. */
  26099. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26100. if (!this._geometry) {
  26101. return this;
  26102. }
  26103. if (!makeItUnique) {
  26104. this._geometry.updateVerticesData(kind, data, updateExtends);
  26105. }
  26106. else {
  26107. this.makeGeometryUnique();
  26108. this.updateVerticesData(kind, data, updateExtends, false);
  26109. }
  26110. return this;
  26111. };
  26112. /**
  26113. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26114. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26115. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26116. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26117. * Returns the Mesh.
  26118. */
  26119. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26120. if (computeNormals === void 0) { computeNormals = true; }
  26121. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26122. if (!positions) {
  26123. return this;
  26124. }
  26125. positionFunction(positions);
  26126. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26127. if (computeNormals) {
  26128. var indices = this.getIndices();
  26129. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26130. if (!normals) {
  26131. return this;
  26132. }
  26133. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26134. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26135. }
  26136. return this;
  26137. };
  26138. /**
  26139. * Creates a un-shared specific occurence of the geometry for the mesh.
  26140. * Returns the Mesh.
  26141. */
  26142. Mesh.prototype.makeGeometryUnique = function () {
  26143. if (!this._geometry) {
  26144. return this;
  26145. }
  26146. var oldGeometry = this._geometry;
  26147. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26148. oldGeometry.releaseForMesh(this, true);
  26149. geometry.applyToMesh(this);
  26150. return this;
  26151. };
  26152. /**
  26153. * Sets the mesh indices.
  26154. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26155. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26156. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26157. * This method creates a new index buffer each call.
  26158. * Returns the Mesh.
  26159. */
  26160. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26161. if (totalVertices === void 0) { totalVertices = null; }
  26162. if (updatable === void 0) { updatable = false; }
  26163. if (!this._geometry) {
  26164. var vertexData = new BABYLON.VertexData();
  26165. vertexData.indices = indices;
  26166. var scene = this.getScene();
  26167. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26168. }
  26169. else {
  26170. this._geometry.setIndices(indices, totalVertices, updatable);
  26171. }
  26172. return this;
  26173. };
  26174. /**
  26175. * Update the current index buffer
  26176. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26177. * Returns the Mesh.
  26178. */
  26179. Mesh.prototype.updateIndices = function (indices, offset) {
  26180. if (!this._geometry) {
  26181. return this;
  26182. }
  26183. this._geometry.updateIndices(indices, offset);
  26184. return this;
  26185. };
  26186. /**
  26187. * Invert the geometry to move from a right handed system to a left handed one.
  26188. * Returns the Mesh.
  26189. */
  26190. Mesh.prototype.toLeftHanded = function () {
  26191. if (!this._geometry) {
  26192. return this;
  26193. }
  26194. this._geometry.toLeftHanded();
  26195. return this;
  26196. };
  26197. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26198. if (!this._geometry) {
  26199. return this;
  26200. }
  26201. var engine = this.getScene().getEngine();
  26202. // Wireframe
  26203. var indexToBind;
  26204. if (this._unIndexed) {
  26205. indexToBind = null;
  26206. }
  26207. else {
  26208. switch (fillMode) {
  26209. case BABYLON.Material.PointFillMode:
  26210. indexToBind = null;
  26211. break;
  26212. case BABYLON.Material.WireFrameFillMode:
  26213. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26214. break;
  26215. default:
  26216. case BABYLON.Material.TriangleFillMode:
  26217. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26218. break;
  26219. }
  26220. }
  26221. // VBOs
  26222. this._geometry._bind(effect, indexToBind);
  26223. return this;
  26224. };
  26225. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26226. if (alternate === void 0) { alternate = false; }
  26227. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26228. return this;
  26229. }
  26230. this.onBeforeDrawObservable.notifyObservers(this);
  26231. var scene = this.getScene();
  26232. var engine = scene.getEngine();
  26233. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26234. // or triangles as points
  26235. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26236. }
  26237. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26238. // Triangles as wireframe
  26239. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26240. }
  26241. else {
  26242. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26243. }
  26244. if (scene._isAlternateRenderingEnabled && !alternate) {
  26245. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26246. if (!effect || !scene.activeCamera) {
  26247. return this;
  26248. }
  26249. scene._switchToAlternateCameraConfiguration(true);
  26250. this._effectiveMaterial.bindView(effect);
  26251. this._effectiveMaterial.bindViewProjection(effect);
  26252. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26253. this._draw(subMesh, fillMode, instancesCount, true);
  26254. engine.setViewport(scene.activeCamera.viewport);
  26255. scene._switchToAlternateCameraConfiguration(false);
  26256. this._effectiveMaterial.bindView(effect);
  26257. this._effectiveMaterial.bindViewProjection(effect);
  26258. }
  26259. return this;
  26260. };
  26261. /**
  26262. * Registers for this mesh a javascript function called just before the rendering process.
  26263. * This function is passed the current mesh.
  26264. * Return the Mesh.
  26265. */
  26266. Mesh.prototype.registerBeforeRender = function (func) {
  26267. this.onBeforeRenderObservable.add(func);
  26268. return this;
  26269. };
  26270. /**
  26271. * Disposes a previously registered javascript function called before the rendering.
  26272. * This function is passed the current mesh.
  26273. * Returns the Mesh.
  26274. */
  26275. Mesh.prototype.unregisterBeforeRender = function (func) {
  26276. this.onBeforeRenderObservable.removeCallback(func);
  26277. return this;
  26278. };
  26279. /**
  26280. * Registers for this mesh a javascript function called just after the rendering is complete.
  26281. * This function is passed the current mesh.
  26282. * Returns the Mesh.
  26283. */
  26284. Mesh.prototype.registerAfterRender = function (func) {
  26285. this.onAfterRenderObservable.add(func);
  26286. return this;
  26287. };
  26288. /**
  26289. * Disposes a previously registered javascript function called after the rendering.
  26290. * This function is passed the current mesh.
  26291. * Return the Mesh.
  26292. */
  26293. Mesh.prototype.unregisterAfterRender = function (func) {
  26294. this.onAfterRenderObservable.removeCallback(func);
  26295. return this;
  26296. };
  26297. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26298. var scene = this.getScene();
  26299. this._batchCache.mustReturn = false;
  26300. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26301. this._batchCache.visibleInstances[subMeshId] = null;
  26302. if (this._visibleInstances) {
  26303. var currentRenderId = scene.getRenderId();
  26304. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26305. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26306. var selfRenderId = this._renderId;
  26307. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26308. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26309. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26310. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26311. }
  26312. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26313. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26314. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26315. this._batchCache.mustReturn = true;
  26316. return this._batchCache;
  26317. }
  26318. if (currentRenderId !== selfRenderId) {
  26319. this._batchCache.renderSelf[subMeshId] = false;
  26320. }
  26321. }
  26322. this._renderIdForInstances[subMeshId] = currentRenderId;
  26323. }
  26324. return this._batchCache;
  26325. };
  26326. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26327. var visibleInstances = batch.visibleInstances[subMesh._id];
  26328. if (!visibleInstances) {
  26329. return this;
  26330. }
  26331. var matricesCount = visibleInstances.length + 1;
  26332. var bufferSize = matricesCount * 16 * 4;
  26333. var currentInstancesBufferSize = this._instancesBufferSize;
  26334. var instancesBuffer = this._instancesBuffer;
  26335. while (this._instancesBufferSize < bufferSize) {
  26336. this._instancesBufferSize *= 2;
  26337. }
  26338. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26339. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26340. }
  26341. var offset = 0;
  26342. var instancesCount = 0;
  26343. var world = this.getWorldMatrix();
  26344. if (batch.renderSelf[subMesh._id]) {
  26345. world.copyToArray(this._instancesData, offset);
  26346. offset += 16;
  26347. instancesCount++;
  26348. }
  26349. if (visibleInstances) {
  26350. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26351. var instance = visibleInstances[instanceIndex];
  26352. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26353. offset += 16;
  26354. instancesCount++;
  26355. }
  26356. }
  26357. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26358. if (instancesBuffer) {
  26359. instancesBuffer.dispose();
  26360. }
  26361. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26362. this._instancesBuffer = instancesBuffer;
  26363. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26364. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26365. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26366. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26367. }
  26368. else {
  26369. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26370. }
  26371. this._bind(subMesh, effect, fillMode);
  26372. this._draw(subMesh, fillMode, instancesCount);
  26373. engine.unbindInstanceAttributes();
  26374. return this;
  26375. };
  26376. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26377. var scene = this.getScene();
  26378. var engine = scene.getEngine();
  26379. if (hardwareInstancedRendering) {
  26380. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26381. }
  26382. else {
  26383. if (batch.renderSelf[subMesh._id]) {
  26384. // Draw
  26385. if (onBeforeDraw) {
  26386. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26387. }
  26388. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26389. }
  26390. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26391. if (visibleInstancesForSubMesh) {
  26392. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26393. var instance = visibleInstancesForSubMesh[instanceIndex];
  26394. // World
  26395. var world = instance.getWorldMatrix();
  26396. if (onBeforeDraw) {
  26397. onBeforeDraw(true, world, effectiveMaterial);
  26398. }
  26399. // Draw
  26400. this._draw(subMesh, fillMode);
  26401. }
  26402. }
  26403. }
  26404. return this;
  26405. };
  26406. /**
  26407. * Triggers the draw call for the mesh.
  26408. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26409. * Returns the Mesh.
  26410. */
  26411. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26412. this.checkOcclusionQuery();
  26413. if (this._isOccluded) {
  26414. return this;
  26415. }
  26416. var scene = this.getScene();
  26417. // Managing instances
  26418. var batch = this._getInstancesRenderList(subMesh._id);
  26419. if (batch.mustReturn) {
  26420. return this;
  26421. }
  26422. // Checking geometry state
  26423. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26424. return this;
  26425. }
  26426. this.onBeforeRenderObservable.notifyObservers(this);
  26427. var engine = scene.getEngine();
  26428. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26429. // Material
  26430. var material = subMesh.getMaterial();
  26431. if (!material) {
  26432. return this;
  26433. }
  26434. this._effectiveMaterial = material;
  26435. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26436. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26437. return this;
  26438. }
  26439. }
  26440. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26441. return this;
  26442. }
  26443. // Alpha mode
  26444. if (enableAlphaMode) {
  26445. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26446. }
  26447. // Outline - step 1
  26448. var savedDepthWrite = engine.getDepthWrite();
  26449. if (this.renderOutline) {
  26450. engine.setDepthWrite(false);
  26451. scene.getOutlineRenderer().render(subMesh, batch);
  26452. engine.setDepthWrite(savedDepthWrite);
  26453. }
  26454. var effect;
  26455. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26456. effect = subMesh.effect;
  26457. }
  26458. else {
  26459. effect = this._effectiveMaterial.getEffect();
  26460. }
  26461. if (!effect) {
  26462. return this;
  26463. }
  26464. var sideOrientation = this.overrideMaterialSideOrientation;
  26465. if (sideOrientation == null) {
  26466. sideOrientation = this._effectiveMaterial.sideOrientation;
  26467. if (this._getWorldMatrixDeterminant() < 0) {
  26468. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26469. }
  26470. }
  26471. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26472. if (this._effectiveMaterial.forceDepthWrite) {
  26473. engine.setDepthWrite(true);
  26474. }
  26475. // Bind
  26476. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26477. if (!hardwareInstancedRendering) {
  26478. this._bind(subMesh, effect, fillMode);
  26479. }
  26480. var world = this.getWorldMatrix();
  26481. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26482. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26483. }
  26484. else {
  26485. this._effectiveMaterial.bind(world, this);
  26486. }
  26487. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26488. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26489. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26490. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26491. }
  26492. // Draw
  26493. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26494. // Unbind
  26495. this._effectiveMaterial.unbind();
  26496. // Outline - step 2
  26497. if (this.renderOutline && savedDepthWrite) {
  26498. engine.setDepthWrite(true);
  26499. engine.setColorWrite(false);
  26500. scene.getOutlineRenderer().render(subMesh, batch);
  26501. engine.setColorWrite(true);
  26502. }
  26503. // Overlay
  26504. if (this.renderOverlay) {
  26505. var currentMode = engine.getAlphaMode();
  26506. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26507. scene.getOutlineRenderer().render(subMesh, batch, true);
  26508. engine.setAlphaMode(currentMode);
  26509. }
  26510. this.onAfterRenderObservable.notifyObservers(this);
  26511. return this;
  26512. };
  26513. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26514. if (isInstance && effectiveMaterial) {
  26515. effectiveMaterial.bindOnlyWorldMatrix(world);
  26516. }
  26517. };
  26518. /**
  26519. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26520. */
  26521. Mesh.prototype.getEmittedParticleSystems = function () {
  26522. var results = new Array();
  26523. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26524. var particleSystem = this.getScene().particleSystems[index];
  26525. if (particleSystem.emitter === this) {
  26526. results.push(particleSystem);
  26527. }
  26528. }
  26529. return results;
  26530. };
  26531. /**
  26532. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26533. */
  26534. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26535. var results = new Array();
  26536. var descendants = this.getDescendants();
  26537. descendants.push(this);
  26538. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26539. var particleSystem = this.getScene().particleSystems[index];
  26540. var emitter = particleSystem.emitter;
  26541. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26542. results.push(particleSystem);
  26543. }
  26544. }
  26545. return results;
  26546. };
  26547. Mesh.prototype._checkDelayState = function () {
  26548. var scene = this.getScene();
  26549. if (this._geometry) {
  26550. this._geometry.load(scene);
  26551. }
  26552. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26553. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26554. this._queueLoad(scene);
  26555. }
  26556. return this;
  26557. };
  26558. Mesh.prototype._queueLoad = function (scene) {
  26559. var _this = this;
  26560. scene._addPendingData(this);
  26561. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26562. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26563. if (data instanceof ArrayBuffer) {
  26564. _this._delayLoadingFunction(data, _this);
  26565. }
  26566. else {
  26567. _this._delayLoadingFunction(JSON.parse(data), _this);
  26568. }
  26569. _this.instances.forEach(function (instance) {
  26570. instance._syncSubMeshes();
  26571. });
  26572. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26573. scene._removePendingData(_this);
  26574. }, function () { }, scene.database, getBinaryData);
  26575. return this;
  26576. };
  26577. /**
  26578. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26579. */
  26580. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26581. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26582. return false;
  26583. }
  26584. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26585. return false;
  26586. }
  26587. this._checkDelayState();
  26588. return true;
  26589. };
  26590. /**
  26591. * Sets the mesh material by the material or multiMaterial `id` property.
  26592. * The material `id` is a string identifying the material or the multiMaterial.
  26593. * This method returns the Mesh.
  26594. */
  26595. Mesh.prototype.setMaterialByID = function (id) {
  26596. var materials = this.getScene().materials;
  26597. var index;
  26598. for (index = materials.length - 1; index > -1; index--) {
  26599. if (materials[index].id === id) {
  26600. this.material = materials[index];
  26601. return this;
  26602. }
  26603. }
  26604. // Multi
  26605. var multiMaterials = this.getScene().multiMaterials;
  26606. for (index = multiMaterials.length - 1; index > -1; index--) {
  26607. if (multiMaterials[index].id === id) {
  26608. this.material = multiMaterials[index];
  26609. return this;
  26610. }
  26611. }
  26612. return this;
  26613. };
  26614. /**
  26615. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26616. */
  26617. Mesh.prototype.getAnimatables = function () {
  26618. var results = new Array();
  26619. if (this.material) {
  26620. results.push(this.material);
  26621. }
  26622. if (this.skeleton) {
  26623. results.push(this.skeleton);
  26624. }
  26625. return results;
  26626. };
  26627. /**
  26628. * Modifies the mesh geometry according to the passed transformation matrix.
  26629. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26630. * The mesh normals are modified accordingly the same transformation.
  26631. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26632. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26633. * Returns the Mesh.
  26634. */
  26635. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26636. // Position
  26637. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26638. return this;
  26639. }
  26640. var submeshes = this.subMeshes.splice(0);
  26641. this._resetPointsArrayCache();
  26642. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26643. var temp = new Array();
  26644. var index;
  26645. for (index = 0; index < data.length; index += 3) {
  26646. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26647. }
  26648. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26649. // Normals
  26650. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26651. return this;
  26652. }
  26653. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26654. temp = [];
  26655. for (index = 0; index < data.length; index += 3) {
  26656. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26657. }
  26658. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26659. // flip faces?
  26660. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26661. this.flipFaces();
  26662. }
  26663. // Restore submeshes
  26664. this.releaseSubMeshes();
  26665. this.subMeshes = submeshes;
  26666. return this;
  26667. };
  26668. /**
  26669. * Modifies the mesh geometry according to its own current World Matrix.
  26670. * The mesh World Matrix is then reset.
  26671. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26672. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26673. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26674. * Returns the Mesh.
  26675. */
  26676. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26677. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26678. this.scaling.copyFromFloats(1, 1, 1);
  26679. this.position.copyFromFloats(0, 0, 0);
  26680. this.rotation.copyFromFloats(0, 0, 0);
  26681. //only if quaternion is already set
  26682. if (this.rotationQuaternion) {
  26683. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26684. }
  26685. this._worldMatrix = BABYLON.Matrix.Identity();
  26686. return this;
  26687. };
  26688. Object.defineProperty(Mesh.prototype, "_positions", {
  26689. // Cache
  26690. get: function () {
  26691. if (this._geometry) {
  26692. return this._geometry._positions;
  26693. }
  26694. return null;
  26695. },
  26696. enumerable: true,
  26697. configurable: true
  26698. });
  26699. Mesh.prototype._resetPointsArrayCache = function () {
  26700. if (this._geometry) {
  26701. this._geometry._resetPointsArrayCache();
  26702. }
  26703. return this;
  26704. };
  26705. Mesh.prototype._generatePointsArray = function () {
  26706. if (this._geometry) {
  26707. return this._geometry._generatePointsArray();
  26708. }
  26709. return false;
  26710. };
  26711. /**
  26712. * Returns a new Mesh object generated from the current mesh properties.
  26713. * This method must not get confused with createInstance().
  26714. * The parameter `name` is a string, the name given to the new mesh.
  26715. * The optional parameter `newParent` can be any Node object (default `null`).
  26716. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26717. * 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.
  26718. */
  26719. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26720. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26721. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26722. };
  26723. /**
  26724. * Disposes the Mesh.
  26725. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26726. * Returns nothing.
  26727. */
  26728. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26729. var _this = this;
  26730. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26731. this.morphTargetManager = null;
  26732. if (this._geometry) {
  26733. this._geometry.releaseForMesh(this, true);
  26734. }
  26735. // Sources
  26736. var meshes = this.getScene().meshes;
  26737. meshes.forEach(function (abstractMesh) {
  26738. var mesh = abstractMesh;
  26739. if (mesh._source && mesh._source === _this) {
  26740. mesh._source = null;
  26741. }
  26742. });
  26743. this._source = null;
  26744. // Instances
  26745. if (this._instancesBuffer) {
  26746. this._instancesBuffer.dispose();
  26747. this._instancesBuffer = null;
  26748. }
  26749. while (this.instances.length) {
  26750. this.instances[0].dispose();
  26751. }
  26752. // Highlight layers.
  26753. var highlightLayers = this.getScene().highlightLayers;
  26754. for (var i = 0; i < highlightLayers.length; i++) {
  26755. var highlightLayer = highlightLayers[i];
  26756. if (highlightLayer) {
  26757. highlightLayer.removeMesh(this);
  26758. highlightLayer.removeExcludedMesh(this);
  26759. }
  26760. }
  26761. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26762. };
  26763. /**
  26764. * Modifies the mesh geometry according to a displacement map.
  26765. * 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.
  26766. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26767. * This method returns nothing.
  26768. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26769. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26770. * 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.
  26771. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26772. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26773. *
  26774. * Returns the Mesh.
  26775. */
  26776. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26777. var _this = this;
  26778. var scene = this.getScene();
  26779. var onload = function (img) {
  26780. // Getting height map data
  26781. var canvas = document.createElement("canvas");
  26782. var context = canvas.getContext("2d");
  26783. var heightMapWidth = img.width;
  26784. var heightMapHeight = img.height;
  26785. canvas.width = heightMapWidth;
  26786. canvas.height = heightMapHeight;
  26787. context.drawImage(img, 0, 0);
  26788. // Create VertexData from map data
  26789. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26790. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26791. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26792. //execute success callback, if set
  26793. if (onSuccess) {
  26794. onSuccess(_this);
  26795. }
  26796. };
  26797. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26798. return this;
  26799. };
  26800. /**
  26801. * Modifies the mesh geometry according to a displacementMap buffer.
  26802. * 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.
  26803. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26804. * This method returns nothing.
  26805. * 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.
  26806. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26807. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26808. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26809. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26810. *
  26811. * Returns the Mesh.
  26812. */
  26813. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26814. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26815. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26816. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26817. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26818. return this;
  26819. }
  26820. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26821. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26822. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26823. var position = BABYLON.Vector3.Zero();
  26824. var normal = BABYLON.Vector3.Zero();
  26825. var uv = BABYLON.Vector2.Zero();
  26826. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26827. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26828. for (var index = 0; index < positions.length; index += 3) {
  26829. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26830. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26831. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26832. // Compute height
  26833. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26834. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26835. var pos = (u + v * heightMapWidth) * 4;
  26836. var r = buffer[pos] / 255.0;
  26837. var g = buffer[pos + 1] / 255.0;
  26838. var b = buffer[pos + 2] / 255.0;
  26839. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26840. normal.normalize();
  26841. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26842. position = position.add(normal);
  26843. position.toArray(positions, index);
  26844. }
  26845. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26846. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26847. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26848. return this;
  26849. };
  26850. /**
  26851. * Modify the mesh to get a flat shading rendering.
  26852. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26853. * This method returns the Mesh.
  26854. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26855. */
  26856. Mesh.prototype.convertToFlatShadedMesh = function () {
  26857. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26858. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26859. var kinds = this.getVerticesDataKinds();
  26860. var vbs = {};
  26861. var data = {};
  26862. var newdata = {};
  26863. var updatableNormals = false;
  26864. var kindIndex;
  26865. var kind;
  26866. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26867. kind = kinds[kindIndex];
  26868. var vertexBuffer = this.getVertexBuffer(kind);
  26869. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26870. updatableNormals = vertexBuffer.isUpdatable();
  26871. kinds.splice(kindIndex, 1);
  26872. kindIndex--;
  26873. continue;
  26874. }
  26875. vbs[kind] = vertexBuffer;
  26876. data[kind] = vbs[kind].getData();
  26877. newdata[kind] = [];
  26878. }
  26879. // Save previous submeshes
  26880. var previousSubmeshes = this.subMeshes.slice(0);
  26881. var indices = this.getIndices();
  26882. var totalIndices = this.getTotalIndices();
  26883. // Generating unique vertices per face
  26884. var index;
  26885. for (index = 0; index < totalIndices; index++) {
  26886. var vertexIndex = indices[index];
  26887. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26888. kind = kinds[kindIndex];
  26889. var stride = vbs[kind].getStrideSize();
  26890. for (var offset = 0; offset < stride; offset++) {
  26891. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26892. }
  26893. }
  26894. }
  26895. // Updating faces & normal
  26896. var normals = [];
  26897. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26898. for (index = 0; index < totalIndices; index += 3) {
  26899. indices[index] = index;
  26900. indices[index + 1] = index + 1;
  26901. indices[index + 2] = index + 2;
  26902. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26903. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26904. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26905. var p1p2 = p1.subtract(p2);
  26906. var p3p2 = p3.subtract(p2);
  26907. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26908. // Store same normals for every vertex
  26909. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26910. normals.push(normal.x);
  26911. normals.push(normal.y);
  26912. normals.push(normal.z);
  26913. }
  26914. }
  26915. this.setIndices(indices);
  26916. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26917. // Updating vertex buffers
  26918. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26919. kind = kinds[kindIndex];
  26920. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26921. }
  26922. // Updating submeshes
  26923. this.releaseSubMeshes();
  26924. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26925. var previousOne = previousSubmeshes[submeshIndex];
  26926. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26927. }
  26928. this.synchronizeInstances();
  26929. return this;
  26930. };
  26931. /**
  26932. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26933. * In other words, more vertices, no more indices and a single bigger VBO.
  26934. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26935. * Returns the Mesh.
  26936. */
  26937. Mesh.prototype.convertToUnIndexedMesh = function () {
  26938. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26939. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26940. var kinds = this.getVerticesDataKinds();
  26941. var vbs = {};
  26942. var data = {};
  26943. var newdata = {};
  26944. var kindIndex;
  26945. var kind;
  26946. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26947. kind = kinds[kindIndex];
  26948. var vertexBuffer = this.getVertexBuffer(kind);
  26949. vbs[kind] = vertexBuffer;
  26950. data[kind] = vbs[kind].getData();
  26951. newdata[kind] = [];
  26952. }
  26953. // Save previous submeshes
  26954. var previousSubmeshes = this.subMeshes.slice(0);
  26955. var indices = this.getIndices();
  26956. var totalIndices = this.getTotalIndices();
  26957. // Generating unique vertices per face
  26958. var index;
  26959. for (index = 0; index < totalIndices; index++) {
  26960. var vertexIndex = indices[index];
  26961. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26962. kind = kinds[kindIndex];
  26963. var stride = vbs[kind].getStrideSize();
  26964. for (var offset = 0; offset < stride; offset++) {
  26965. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26966. }
  26967. }
  26968. }
  26969. // Updating indices
  26970. for (index = 0; index < totalIndices; index += 3) {
  26971. indices[index] = index;
  26972. indices[index + 1] = index + 1;
  26973. indices[index + 2] = index + 2;
  26974. }
  26975. this.setIndices(indices);
  26976. // Updating vertex buffers
  26977. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26978. kind = kinds[kindIndex];
  26979. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26980. }
  26981. // Updating submeshes
  26982. this.releaseSubMeshes();
  26983. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26984. var previousOne = previousSubmeshes[submeshIndex];
  26985. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26986. }
  26987. this._unIndexed = true;
  26988. this.synchronizeInstances();
  26989. return this;
  26990. };
  26991. /**
  26992. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26993. * This method returns the Mesh.
  26994. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26995. */
  26996. Mesh.prototype.flipFaces = function (flipNormals) {
  26997. if (flipNormals === void 0) { flipNormals = false; }
  26998. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26999. var i;
  27000. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27001. for (i = 0; i < vertex_data.normals.length; i++) {
  27002. vertex_data.normals[i] *= -1;
  27003. }
  27004. }
  27005. if (vertex_data.indices) {
  27006. var temp;
  27007. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27008. // reassign indices
  27009. temp = vertex_data.indices[i + 1];
  27010. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27011. vertex_data.indices[i + 2] = temp;
  27012. }
  27013. }
  27014. vertex_data.applyToMesh(this);
  27015. return this;
  27016. };
  27017. // Instances
  27018. /**
  27019. * Creates a new InstancedMesh object from the mesh model.
  27020. * An instance shares the same properties and the same material than its model.
  27021. * Only these properties of each instance can then be set individually :
  27022. * - position
  27023. * - rotation
  27024. * - rotationQuaternion
  27025. * - setPivotMatrix
  27026. * - scaling
  27027. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27028. * Warning : this method is not supported for Line mesh and LineSystem
  27029. */
  27030. Mesh.prototype.createInstance = function (name) {
  27031. return new BABYLON.InstancedMesh(name, this);
  27032. };
  27033. /**
  27034. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27035. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27036. * This method returns the Mesh.
  27037. */
  27038. Mesh.prototype.synchronizeInstances = function () {
  27039. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27040. var instance = this.instances[instanceIndex];
  27041. instance._syncSubMeshes();
  27042. }
  27043. return this;
  27044. };
  27045. /**
  27046. * Simplify the mesh according to the given array of settings.
  27047. * Function will return immediately and will simplify async. It returns the Mesh.
  27048. * @param settings a collection of simplification settings.
  27049. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27050. * @param type the type of simplification to run.
  27051. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27052. */
  27053. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27054. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27055. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27056. this.getScene().simplificationQueue.addTask({
  27057. settings: settings,
  27058. parallelProcessing: parallelProcessing,
  27059. mesh: this,
  27060. simplificationType: simplificationType,
  27061. successCallback: successCallback
  27062. });
  27063. return this;
  27064. };
  27065. /**
  27066. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27067. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27068. * This should be used together with the simplification to avoid disappearing triangles.
  27069. * Returns the Mesh.
  27070. * @param successCallback an optional success callback to be called after the optimization finished.
  27071. */
  27072. Mesh.prototype.optimizeIndices = function (successCallback) {
  27073. var _this = this;
  27074. var indices = this.getIndices();
  27075. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27076. if (!positions || !indices) {
  27077. return this;
  27078. }
  27079. var vectorPositions = new Array();
  27080. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27081. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27082. }
  27083. var dupes = new Array();
  27084. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27085. var realPos = vectorPositions.length - 1 - iteration;
  27086. var testedPosition = vectorPositions[realPos];
  27087. for (var j = 0; j < realPos; ++j) {
  27088. var againstPosition = vectorPositions[j];
  27089. if (testedPosition.equals(againstPosition)) {
  27090. dupes[realPos] = j;
  27091. break;
  27092. }
  27093. }
  27094. }, function () {
  27095. for (var i = 0; i < indices.length; ++i) {
  27096. indices[i] = dupes[indices[i]] || indices[i];
  27097. }
  27098. //indices are now reordered
  27099. var originalSubMeshes = _this.subMeshes.slice(0);
  27100. _this.setIndices(indices);
  27101. _this.subMeshes = originalSubMeshes;
  27102. if (successCallback) {
  27103. successCallback(_this);
  27104. }
  27105. });
  27106. return this;
  27107. };
  27108. Mesh.prototype.serialize = function (serializationObject) {
  27109. serializationObject.name = this.name;
  27110. serializationObject.id = this.id;
  27111. serializationObject.type = this.getClassName();
  27112. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27113. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27114. }
  27115. serializationObject.position = this.position.asArray();
  27116. if (this.rotationQuaternion) {
  27117. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27118. }
  27119. else if (this.rotation) {
  27120. serializationObject.rotation = this.rotation.asArray();
  27121. }
  27122. serializationObject.scaling = this.scaling.asArray();
  27123. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27124. serializationObject.isEnabled = this.isEnabled(false);
  27125. serializationObject.isVisible = this.isVisible;
  27126. serializationObject.infiniteDistance = this.infiniteDistance;
  27127. serializationObject.pickable = this.isPickable;
  27128. serializationObject.receiveShadows = this.receiveShadows;
  27129. serializationObject.billboardMode = this.billboardMode;
  27130. serializationObject.visibility = this.visibility;
  27131. serializationObject.checkCollisions = this.checkCollisions;
  27132. serializationObject.isBlocker = this.isBlocker;
  27133. // Parent
  27134. if (this.parent) {
  27135. serializationObject.parentId = this.parent.id;
  27136. }
  27137. // Geometry
  27138. serializationObject.isUnIndexed = this.isUnIndexed;
  27139. var geometry = this._geometry;
  27140. if (geometry) {
  27141. var geometryId = geometry.id;
  27142. serializationObject.geometryId = geometryId;
  27143. // SubMeshes
  27144. serializationObject.subMeshes = [];
  27145. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27146. var subMesh = this.subMeshes[subIndex];
  27147. serializationObject.subMeshes.push({
  27148. materialIndex: subMesh.materialIndex,
  27149. verticesStart: subMesh.verticesStart,
  27150. verticesCount: subMesh.verticesCount,
  27151. indexStart: subMesh.indexStart,
  27152. indexCount: subMesh.indexCount
  27153. });
  27154. }
  27155. }
  27156. // Material
  27157. if (this.material) {
  27158. serializationObject.materialId = this.material.id;
  27159. }
  27160. else {
  27161. this.material = null;
  27162. }
  27163. // Morph targets
  27164. if (this.morphTargetManager) {
  27165. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27166. }
  27167. // Skeleton
  27168. if (this.skeleton) {
  27169. serializationObject.skeletonId = this.skeleton.id;
  27170. }
  27171. // Physics
  27172. //TODO implement correct serialization for physics impostors.
  27173. var impostor = this.getPhysicsImpostor();
  27174. if (impostor) {
  27175. serializationObject.physicsMass = impostor.getParam("mass");
  27176. serializationObject.physicsFriction = impostor.getParam("friction");
  27177. serializationObject.physicsRestitution = impostor.getParam("mass");
  27178. serializationObject.physicsImpostor = impostor.type;
  27179. }
  27180. // Metadata
  27181. if (this.metadata) {
  27182. serializationObject.metadata = this.metadata;
  27183. }
  27184. // Instances
  27185. serializationObject.instances = [];
  27186. for (var index = 0; index < this.instances.length; index++) {
  27187. var instance = this.instances[index];
  27188. var serializationInstance = {
  27189. name: instance.name,
  27190. id: instance.id,
  27191. position: instance.position.asArray(),
  27192. scaling: instance.scaling.asArray()
  27193. };
  27194. if (instance.rotationQuaternion) {
  27195. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27196. }
  27197. else if (instance.rotation) {
  27198. serializationInstance.rotation = instance.rotation.asArray();
  27199. }
  27200. serializationObject.instances.push(serializationInstance);
  27201. // Animations
  27202. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27203. serializationInstance.ranges = instance.serializeAnimationRanges();
  27204. }
  27205. //
  27206. // Animations
  27207. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27208. serializationObject.ranges = this.serializeAnimationRanges();
  27209. // Layer mask
  27210. serializationObject.layerMask = this.layerMask;
  27211. // Alpha
  27212. serializationObject.alphaIndex = this.alphaIndex;
  27213. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27214. // Overlay
  27215. serializationObject.overlayAlpha = this.overlayAlpha;
  27216. serializationObject.overlayColor = this.overlayColor.asArray();
  27217. serializationObject.renderOverlay = this.renderOverlay;
  27218. // Fog
  27219. serializationObject.applyFog = this.applyFog;
  27220. // Action Manager
  27221. if (this.actionManager) {
  27222. serializationObject.actions = this.actionManager.serialize(this.name);
  27223. }
  27224. };
  27225. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27226. if (!this.geometry) {
  27227. return;
  27228. }
  27229. this._markSubMeshesAsAttributesDirty();
  27230. var morphTargetManager = this._morphTargetManager;
  27231. if (morphTargetManager && morphTargetManager.vertexCount) {
  27232. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27233. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27234. this.morphTargetManager = null;
  27235. return;
  27236. }
  27237. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27238. var morphTarget = morphTargetManager.getActiveTarget(index);
  27239. var positions = morphTarget.getPositions();
  27240. if (!positions) {
  27241. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27242. return;
  27243. }
  27244. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27245. var normals = morphTarget.getNormals();
  27246. if (normals) {
  27247. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27248. }
  27249. var tangents = morphTarget.getTangents();
  27250. if (tangents) {
  27251. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27252. }
  27253. }
  27254. }
  27255. else {
  27256. var index = 0;
  27257. // Positions
  27258. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27259. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27260. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27261. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27262. }
  27263. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27264. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27265. }
  27266. index++;
  27267. }
  27268. }
  27269. };
  27270. // Statics
  27271. /**
  27272. * Returns a new Mesh object parsed from the source provided.
  27273. * The parameter `parsedMesh` is the source.
  27274. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27275. */
  27276. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27277. var mesh;
  27278. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27279. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27280. }
  27281. else {
  27282. mesh = new Mesh(parsedMesh.name, scene);
  27283. }
  27284. mesh.id = parsedMesh.id;
  27285. if (BABYLON.Tags) {
  27286. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27287. }
  27288. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27289. if (parsedMesh.metadata !== undefined) {
  27290. mesh.metadata = parsedMesh.metadata;
  27291. }
  27292. if (parsedMesh.rotationQuaternion) {
  27293. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27294. }
  27295. else if (parsedMesh.rotation) {
  27296. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27297. }
  27298. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27299. if (parsedMesh.localMatrix) {
  27300. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27301. }
  27302. else if (parsedMesh.pivotMatrix) {
  27303. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27304. }
  27305. mesh.setEnabled(parsedMesh.isEnabled);
  27306. mesh.isVisible = parsedMesh.isVisible;
  27307. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27308. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27309. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27310. if (parsedMesh.applyFog !== undefined) {
  27311. mesh.applyFog = parsedMesh.applyFog;
  27312. }
  27313. if (parsedMesh.pickable !== undefined) {
  27314. mesh.isPickable = parsedMesh.pickable;
  27315. }
  27316. if (parsedMesh.alphaIndex !== undefined) {
  27317. mesh.alphaIndex = parsedMesh.alphaIndex;
  27318. }
  27319. mesh.receiveShadows = parsedMesh.receiveShadows;
  27320. mesh.billboardMode = parsedMesh.billboardMode;
  27321. if (parsedMesh.visibility !== undefined) {
  27322. mesh.visibility = parsedMesh.visibility;
  27323. }
  27324. mesh.checkCollisions = parsedMesh.checkCollisions;
  27325. if (parsedMesh.isBlocker !== undefined) {
  27326. mesh.isBlocker = parsedMesh.isBlocker;
  27327. }
  27328. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27329. // freezeWorldMatrix
  27330. if (parsedMesh.freezeWorldMatrix) {
  27331. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27332. }
  27333. // Parent
  27334. if (parsedMesh.parentId) {
  27335. mesh._waitingParentId = parsedMesh.parentId;
  27336. }
  27337. // Actions
  27338. if (parsedMesh.actions !== undefined) {
  27339. mesh._waitingActions = parsedMesh.actions;
  27340. }
  27341. // Overlay
  27342. if (parsedMesh.overlayAlpha !== undefined) {
  27343. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27344. }
  27345. if (parsedMesh.overlayColor !== undefined) {
  27346. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27347. }
  27348. if (parsedMesh.renderOverlay !== undefined) {
  27349. mesh.renderOverlay = parsedMesh.renderOverlay;
  27350. }
  27351. // Geometry
  27352. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27353. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27354. if (parsedMesh.delayLoadingFile) {
  27355. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27356. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27357. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27358. if (parsedMesh._binaryInfo) {
  27359. mesh._binaryInfo = parsedMesh._binaryInfo;
  27360. }
  27361. mesh._delayInfo = [];
  27362. if (parsedMesh.hasUVs) {
  27363. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27364. }
  27365. if (parsedMesh.hasUVs2) {
  27366. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27367. }
  27368. if (parsedMesh.hasUVs3) {
  27369. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27370. }
  27371. if (parsedMesh.hasUVs4) {
  27372. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27373. }
  27374. if (parsedMesh.hasUVs5) {
  27375. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27376. }
  27377. if (parsedMesh.hasUVs6) {
  27378. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27379. }
  27380. if (parsedMesh.hasColors) {
  27381. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27382. }
  27383. if (parsedMesh.hasMatricesIndices) {
  27384. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27385. }
  27386. if (parsedMesh.hasMatricesWeights) {
  27387. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27388. }
  27389. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27390. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27391. mesh._checkDelayState();
  27392. }
  27393. }
  27394. else {
  27395. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27396. }
  27397. // Material
  27398. if (parsedMesh.materialId) {
  27399. mesh.setMaterialByID(parsedMesh.materialId);
  27400. }
  27401. else {
  27402. mesh.material = null;
  27403. }
  27404. // Morph targets
  27405. if (parsedMesh.morphTargetManagerId > -1) {
  27406. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27407. }
  27408. // Skeleton
  27409. if (parsedMesh.skeletonId > -1) {
  27410. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27411. if (parsedMesh.numBoneInfluencers) {
  27412. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27413. }
  27414. }
  27415. // Animations
  27416. if (parsedMesh.animations) {
  27417. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27418. var parsedAnimation = parsedMesh.animations[animationIndex];
  27419. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27420. }
  27421. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27422. }
  27423. if (parsedMesh.autoAnimate) {
  27424. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27425. }
  27426. // Layer Mask
  27427. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27428. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27429. }
  27430. else {
  27431. mesh.layerMask = 0x0FFFFFFF;
  27432. }
  27433. // Physics
  27434. if (parsedMesh.physicsImpostor) {
  27435. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27436. mass: parsedMesh.physicsMass,
  27437. friction: parsedMesh.physicsFriction,
  27438. restitution: parsedMesh.physicsRestitution
  27439. }, scene);
  27440. }
  27441. // Instances
  27442. if (parsedMesh.instances) {
  27443. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27444. var parsedInstance = parsedMesh.instances[index];
  27445. var instance = mesh.createInstance(parsedInstance.name);
  27446. if (parsedInstance.id) {
  27447. instance.id = parsedInstance.id;
  27448. }
  27449. if (BABYLON.Tags) {
  27450. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27451. }
  27452. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27453. if (parsedInstance.parentId) {
  27454. instance._waitingParentId = parsedInstance.parentId;
  27455. }
  27456. if (parsedInstance.rotationQuaternion) {
  27457. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27458. }
  27459. else if (parsedInstance.rotation) {
  27460. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27461. }
  27462. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27463. instance.checkCollisions = mesh.checkCollisions;
  27464. if (parsedMesh.animations) {
  27465. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27466. parsedAnimation = parsedMesh.animations[animationIndex];
  27467. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27468. }
  27469. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27470. }
  27471. }
  27472. }
  27473. return mesh;
  27474. };
  27475. /**
  27476. * Creates a ribbon mesh.
  27477. * Please consider using the same method from the MeshBuilder class instead.
  27478. * 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.
  27479. *
  27480. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27481. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27482. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27483. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27484. * 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.
  27485. * 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.
  27486. * 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
  27487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27490. */
  27491. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27492. if (closeArray === void 0) { closeArray = false; }
  27493. if (updatable === void 0) { updatable = false; }
  27494. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27495. pathArray: pathArray,
  27496. closeArray: closeArray,
  27497. closePath: closePath,
  27498. offset: offset,
  27499. updatable: updatable,
  27500. sideOrientation: sideOrientation,
  27501. instance: instance
  27502. }, scene);
  27503. };
  27504. /**
  27505. * Creates a plane polygonal mesh. By default, this is a disc.
  27506. * Please consider using the same method from the MeshBuilder class instead.
  27507. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27508. * 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.
  27509. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27510. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27512. */
  27513. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27514. if (scene === void 0) { scene = null; }
  27515. var options = {
  27516. radius: radius,
  27517. tessellation: tessellation,
  27518. sideOrientation: sideOrientation,
  27519. updatable: updatable
  27520. };
  27521. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27522. };
  27523. /**
  27524. * Creates a box mesh.
  27525. * Please consider using the same method from the MeshBuilder class instead.
  27526. * The parameter `size` sets the size (float) of each box side (default 1).
  27527. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27528. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27529. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27530. */
  27531. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27532. if (scene === void 0) { scene = null; }
  27533. var options = {
  27534. size: size,
  27535. sideOrientation: sideOrientation,
  27536. updatable: updatable
  27537. };
  27538. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27539. };
  27540. /**
  27541. * Creates a sphere mesh.
  27542. * Please consider using the same method from the MeshBuilder class instead.
  27543. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27544. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27545. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27546. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27548. */
  27549. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27550. var options = {
  27551. segments: segments,
  27552. diameterX: diameter,
  27553. diameterY: diameter,
  27554. diameterZ: diameter,
  27555. sideOrientation: sideOrientation,
  27556. updatable: updatable
  27557. };
  27558. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27559. };
  27560. /**
  27561. * Creates a cylinder or a cone mesh.
  27562. * Please consider using the same method from the MeshBuilder class instead.
  27563. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27564. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27565. * 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.
  27566. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27567. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27568. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27571. */
  27572. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27573. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27574. if (scene !== undefined) {
  27575. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27576. updatable = scene;
  27577. }
  27578. scene = subdivisions;
  27579. subdivisions = 1;
  27580. }
  27581. var options = {
  27582. height: height,
  27583. diameterTop: diameterTop,
  27584. diameterBottom: diameterBottom,
  27585. tessellation: tessellation,
  27586. subdivisions: subdivisions,
  27587. sideOrientation: sideOrientation,
  27588. updatable: updatable
  27589. };
  27590. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27591. };
  27592. // Torus (Code from SharpDX.org)
  27593. /**
  27594. * Creates a torus mesh.
  27595. * Please consider using the same method from the MeshBuilder class instead.
  27596. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27597. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27598. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27599. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27600. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27601. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27602. */
  27603. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27604. var options = {
  27605. diameter: diameter,
  27606. thickness: thickness,
  27607. tessellation: tessellation,
  27608. sideOrientation: sideOrientation,
  27609. updatable: updatable
  27610. };
  27611. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27612. };
  27613. /**
  27614. * Creates a torus knot mesh.
  27615. * Please consider using the same method from the MeshBuilder class instead.
  27616. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27617. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27618. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27619. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27621. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27623. */
  27624. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27625. var options = {
  27626. radius: radius,
  27627. tube: tube,
  27628. radialSegments: radialSegments,
  27629. tubularSegments: tubularSegments,
  27630. p: p,
  27631. q: q,
  27632. sideOrientation: sideOrientation,
  27633. updatable: updatable
  27634. };
  27635. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27636. };
  27637. /**
  27638. * Creates a line mesh.
  27639. * Please consider using the same method from the MeshBuilder class instead.
  27640. * 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.
  27641. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27642. * The parameter `points` is an array successive Vector3.
  27643. * 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
  27644. * When updating an instance, remember that only point positions can change, not the number of points.
  27645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27646. */
  27647. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27648. if (scene === void 0) { scene = null; }
  27649. if (updatable === void 0) { updatable = false; }
  27650. if (instance === void 0) { instance = null; }
  27651. var options = {
  27652. points: points,
  27653. updatable: updatable,
  27654. instance: instance
  27655. };
  27656. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27657. };
  27658. /**
  27659. * Creates a dashed line mesh.
  27660. * Please consider using the same method from the MeshBuilder class instead.
  27661. * 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.
  27662. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27663. * The parameter `points` is an array successive Vector3.
  27664. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27665. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27666. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27667. * 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
  27668. * When updating an instance, remember that only point positions can change, not the number of points.
  27669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27670. */
  27671. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27672. if (scene === void 0) { scene = null; }
  27673. var options = {
  27674. points: points,
  27675. dashSize: dashSize,
  27676. gapSize: gapSize,
  27677. dashNb: dashNb,
  27678. updatable: updatable,
  27679. instance: instance
  27680. };
  27681. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27682. };
  27683. /**
  27684. * Creates a polygon mesh.
  27685. * Please consider using the same method from the MeshBuilder class instead.
  27686. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27687. * 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.
  27688. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27690. * Remember you can only change the shape positions, not their number when updating a polygon.
  27691. */
  27692. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27693. var options = {
  27694. shape: shape,
  27695. holes: holes,
  27696. updatable: updatable,
  27697. sideOrientation: sideOrientation
  27698. };
  27699. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27700. };
  27701. /**
  27702. * Creates an extruded polygon mesh, with depth in the Y direction.
  27703. * Please consider using the same method from the MeshBuilder class instead.
  27704. */
  27705. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27706. var options = {
  27707. shape: shape,
  27708. holes: holes,
  27709. depth: depth,
  27710. updatable: updatable,
  27711. sideOrientation: sideOrientation
  27712. };
  27713. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27714. };
  27715. /**
  27716. * Creates an extruded shape mesh.
  27717. * 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.
  27718. * Please consider using the same method from the MeshBuilder class instead.
  27719. *
  27720. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27721. * 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
  27722. * extruded along the Z axis.
  27723. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27724. * 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.
  27725. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27726. * 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
  27727. * 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
  27728. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27729. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27730. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27732. */
  27733. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27734. if (scene === void 0) { scene = null; }
  27735. var options = {
  27736. shape: shape,
  27737. path: path,
  27738. scale: scale,
  27739. rotation: rotation,
  27740. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27741. sideOrientation: sideOrientation,
  27742. instance: instance,
  27743. updatable: updatable
  27744. };
  27745. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27746. };
  27747. /**
  27748. * Creates an custom extruded shape mesh.
  27749. * 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.
  27750. * Please consider using the same method from the MeshBuilder class instead.
  27751. *
  27752. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27753. * 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
  27754. * extruded along the Z axis.
  27755. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27756. * 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
  27757. * and the distance of this point from the begining of the path :
  27758. * ```javascript
  27759. * var rotationFunction = function(i, distance) {
  27760. * // do things
  27761. * return rotationValue; }
  27762. * ```
  27763. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27764. * 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
  27765. * and the distance of this point from the begining of the path :
  27766. * ```javascript
  27767. * var scaleFunction = function(i, distance) {
  27768. * // do things
  27769. * return scaleValue;}
  27770. * ```
  27771. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27772. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27773. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27774. * 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
  27775. * 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
  27776. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27777. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27780. */
  27781. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27782. var options = {
  27783. shape: shape,
  27784. path: path,
  27785. scaleFunction: scaleFunction,
  27786. rotationFunction: rotationFunction,
  27787. ribbonCloseArray: ribbonCloseArray,
  27788. ribbonClosePath: ribbonClosePath,
  27789. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27790. sideOrientation: sideOrientation,
  27791. instance: instance,
  27792. updatable: updatable
  27793. };
  27794. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27795. };
  27796. /**
  27797. * Creates lathe mesh.
  27798. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27799. * Please consider using the same method from the MeshBuilder class instead.
  27800. * 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
  27801. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27802. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27803. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27804. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27805. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27806. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27807. */
  27808. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27809. var options = {
  27810. shape: shape,
  27811. radius: radius,
  27812. tessellation: tessellation,
  27813. sideOrientation: sideOrientation,
  27814. updatable: updatable
  27815. };
  27816. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27817. };
  27818. /**
  27819. * Creates a plane mesh.
  27820. * Please consider using the same method from the MeshBuilder class instead.
  27821. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27822. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27823. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27825. */
  27826. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27827. var options = {
  27828. size: size,
  27829. width: size,
  27830. height: size,
  27831. sideOrientation: sideOrientation,
  27832. updatable: updatable
  27833. };
  27834. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27835. };
  27836. /**
  27837. * Creates a ground mesh.
  27838. * Please consider using the same method from the MeshBuilder class instead.
  27839. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27840. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27842. */
  27843. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27844. var options = {
  27845. width: width,
  27846. height: height,
  27847. subdivisions: subdivisions,
  27848. updatable: updatable
  27849. };
  27850. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27851. };
  27852. /**
  27853. * Creates a tiled ground mesh.
  27854. * Please consider using the same method from the MeshBuilder class instead.
  27855. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27856. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27857. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27858. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27859. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27860. * numbers of subdivisions on the ground width and height of each tile.
  27861. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27862. */
  27863. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27864. var options = {
  27865. xmin: xmin,
  27866. zmin: zmin,
  27867. xmax: xmax,
  27868. zmax: zmax,
  27869. subdivisions: subdivisions,
  27870. precision: precision,
  27871. updatable: updatable
  27872. };
  27873. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27874. };
  27875. /**
  27876. * Creates a ground mesh from a height map.
  27877. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27878. * Please consider using the same method from the MeshBuilder class instead.
  27879. * The parameter `url` sets the URL of the height map image resource.
  27880. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27881. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27882. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27883. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27884. * 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).
  27885. * This function is passed the newly built mesh :
  27886. * ```javascript
  27887. * function(mesh) { // do things
  27888. * return; }
  27889. * ```
  27890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27891. */
  27892. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27893. var options = {
  27894. width: width,
  27895. height: height,
  27896. subdivisions: subdivisions,
  27897. minHeight: minHeight,
  27898. maxHeight: maxHeight,
  27899. updatable: updatable,
  27900. onReady: onReady
  27901. };
  27902. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27903. };
  27904. /**
  27905. * Creates a tube mesh.
  27906. * 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.
  27907. * Please consider using the same method from the MeshBuilder class instead.
  27908. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27909. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27910. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27911. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27912. * 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.
  27913. * It must return a radius value (positive float) :
  27914. * ```javascript
  27915. * var radiusFunction = function(i, distance) {
  27916. * // do things
  27917. * return radius; }
  27918. * ```
  27919. * 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
  27920. * 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
  27921. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27922. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27924. */
  27925. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27926. var options = {
  27927. path: path,
  27928. radius: radius,
  27929. tessellation: tessellation,
  27930. radiusFunction: radiusFunction,
  27931. arc: 1,
  27932. cap: cap,
  27933. updatable: updatable,
  27934. sideOrientation: sideOrientation,
  27935. instance: instance
  27936. };
  27937. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27938. };
  27939. /**
  27940. * Creates a polyhedron mesh.
  27941. * Please consider using the same method from the MeshBuilder class instead.
  27942. * 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
  27943. * to choose the wanted type.
  27944. * The parameter `size` (positive float, default 1) sets the polygon size.
  27945. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27946. * 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`.
  27947. * 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
  27948. * 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)`).
  27949. * 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
  27950. * 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.
  27951. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27952. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27953. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27954. */
  27955. Mesh.CreatePolyhedron = function (name, options, scene) {
  27956. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27957. };
  27958. /**
  27959. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27960. * Please consider using the same method from the MeshBuilder class instead.
  27961. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27962. * 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`).
  27963. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27964. * 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.
  27965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27966. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27968. */
  27969. Mesh.CreateIcoSphere = function (name, options, scene) {
  27970. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27971. };
  27972. /**
  27973. * Creates a decal mesh.
  27974. * Please consider using the same method from the MeshBuilder class instead.
  27975. * 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.
  27976. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27977. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27978. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27979. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27980. */
  27981. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27982. var options = {
  27983. position: position,
  27984. normal: normal,
  27985. size: size,
  27986. angle: angle
  27987. };
  27988. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27989. };
  27990. // Skeletons
  27991. /**
  27992. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27993. */
  27994. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27995. if (!this._sourcePositions) {
  27996. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27997. if (!source) {
  27998. return this._sourcePositions;
  27999. }
  28000. this._sourcePositions = new Float32Array(source);
  28001. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28002. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28003. }
  28004. }
  28005. return this._sourcePositions;
  28006. };
  28007. /**
  28008. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28009. */
  28010. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28011. if (!this._sourceNormals) {
  28012. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28013. if (!source) {
  28014. return this._sourceNormals;
  28015. }
  28016. this._sourceNormals = new Float32Array(source);
  28017. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28018. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28019. }
  28020. }
  28021. return this._sourceNormals;
  28022. };
  28023. /**
  28024. * Updates the vertex buffer by applying transformation from the bones.
  28025. * Returns the Mesh.
  28026. *
  28027. * @param {skeleton} skeleton to apply
  28028. */
  28029. Mesh.prototype.applySkeleton = function (skeleton) {
  28030. if (!this.geometry) {
  28031. return this;
  28032. }
  28033. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28034. return this;
  28035. }
  28036. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28037. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28038. return this;
  28039. }
  28040. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28041. return this;
  28042. }
  28043. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28044. return this;
  28045. }
  28046. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28047. return this;
  28048. }
  28049. if (!this._sourcePositions) {
  28050. var submeshes = this.subMeshes.slice();
  28051. this.setPositionsForCPUSkinning();
  28052. this.subMeshes = submeshes;
  28053. }
  28054. if (!this._sourceNormals) {
  28055. this.setNormalsForCPUSkinning();
  28056. }
  28057. // positionsData checks for not being Float32Array will only pass at most once
  28058. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28059. if (!positionsData) {
  28060. return this;
  28061. }
  28062. if (!(positionsData instanceof Float32Array)) {
  28063. positionsData = new Float32Array(positionsData);
  28064. }
  28065. // normalsData checks for not being Float32Array will only pass at most once
  28066. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28067. if (!normalsData) {
  28068. return this;
  28069. }
  28070. if (!(normalsData instanceof Float32Array)) {
  28071. normalsData = new Float32Array(normalsData);
  28072. }
  28073. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28074. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28075. if (!matricesWeightsData || !matricesIndicesData) {
  28076. return this;
  28077. }
  28078. var needExtras = this.numBoneInfluencers > 4;
  28079. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28080. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28081. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28082. var tempVector3 = BABYLON.Vector3.Zero();
  28083. var finalMatrix = new BABYLON.Matrix();
  28084. var tempMatrix = new BABYLON.Matrix();
  28085. var matWeightIdx = 0;
  28086. var inf;
  28087. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28088. var weight;
  28089. for (inf = 0; inf < 4; inf++) {
  28090. weight = matricesWeightsData[matWeightIdx + inf];
  28091. if (weight > 0) {
  28092. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28093. finalMatrix.addToSelf(tempMatrix);
  28094. }
  28095. else
  28096. break;
  28097. }
  28098. if (needExtras) {
  28099. for (inf = 0; inf < 4; inf++) {
  28100. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28101. if (weight > 0) {
  28102. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28103. finalMatrix.addToSelf(tempMatrix);
  28104. }
  28105. else
  28106. break;
  28107. }
  28108. }
  28109. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28110. tempVector3.toArray(positionsData, index);
  28111. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28112. tempVector3.toArray(normalsData, index);
  28113. finalMatrix.reset();
  28114. }
  28115. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28116. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28117. return this;
  28118. };
  28119. // Tools
  28120. /**
  28121. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28122. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28123. */
  28124. Mesh.MinMax = function (meshes) {
  28125. var minVector = null;
  28126. var maxVector = null;
  28127. meshes.forEach(function (mesh, index, array) {
  28128. var boundingInfo = mesh.getBoundingInfo();
  28129. var boundingBox = boundingInfo.boundingBox;
  28130. if (!minVector || !maxVector) {
  28131. minVector = boundingBox.minimumWorld;
  28132. maxVector = boundingBox.maximumWorld;
  28133. }
  28134. else {
  28135. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28136. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28137. }
  28138. });
  28139. if (!minVector || !maxVector) {
  28140. return {
  28141. min: BABYLON.Vector3.Zero(),
  28142. max: BABYLON.Vector3.Zero()
  28143. };
  28144. }
  28145. return {
  28146. min: minVector,
  28147. max: maxVector
  28148. };
  28149. };
  28150. /**
  28151. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28152. */
  28153. Mesh.Center = function (meshesOrMinMaxVector) {
  28154. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28155. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28156. };
  28157. /**
  28158. * Merge the array of meshes into a single mesh for performance reasons.
  28159. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28160. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28161. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28162. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28163. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28164. */
  28165. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28166. if (disposeSource === void 0) { disposeSource = true; }
  28167. var index;
  28168. if (!allow32BitsIndices) {
  28169. var totalVertices = 0;
  28170. // Counting vertices
  28171. for (index = 0; index < meshes.length; index++) {
  28172. if (meshes[index]) {
  28173. totalVertices += meshes[index].getTotalVertices();
  28174. if (totalVertices > 65536) {
  28175. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28176. return null;
  28177. }
  28178. }
  28179. }
  28180. }
  28181. // Merge
  28182. var vertexData = null;
  28183. var otherVertexData;
  28184. var indiceArray = new Array();
  28185. var source = null;
  28186. for (index = 0; index < meshes.length; index++) {
  28187. if (meshes[index]) {
  28188. meshes[index].computeWorldMatrix(true);
  28189. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28190. otherVertexData.transform(meshes[index].getWorldMatrix());
  28191. if (vertexData) {
  28192. vertexData.merge(otherVertexData);
  28193. }
  28194. else {
  28195. vertexData = otherVertexData;
  28196. source = meshes[index];
  28197. }
  28198. if (subdivideWithSubMeshes) {
  28199. indiceArray.push(meshes[index].getTotalIndices());
  28200. }
  28201. }
  28202. }
  28203. source = source;
  28204. if (!meshSubclass) {
  28205. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28206. }
  28207. vertexData.applyToMesh(meshSubclass);
  28208. // Setting properties
  28209. meshSubclass.material = source.material;
  28210. meshSubclass.checkCollisions = source.checkCollisions;
  28211. // Cleaning
  28212. if (disposeSource) {
  28213. for (index = 0; index < meshes.length; index++) {
  28214. if (meshes[index]) {
  28215. meshes[index].dispose();
  28216. }
  28217. }
  28218. }
  28219. // Subdivide
  28220. if (subdivideWithSubMeshes) {
  28221. //-- Suppresions du submesh global
  28222. meshSubclass.releaseSubMeshes();
  28223. index = 0;
  28224. var offset = 0;
  28225. //-- aplique la subdivision en fonction du tableau d'indices
  28226. while (index < indiceArray.length) {
  28227. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28228. offset += indiceArray[index];
  28229. index++;
  28230. }
  28231. }
  28232. return meshSubclass;
  28233. };
  28234. // Consts
  28235. Mesh._FRONTSIDE = 0;
  28236. Mesh._BACKSIDE = 1;
  28237. Mesh._DOUBLESIDE = 2;
  28238. Mesh._DEFAULTSIDE = 0;
  28239. Mesh._NO_CAP = 0;
  28240. Mesh._CAP_START = 1;
  28241. Mesh._CAP_END = 2;
  28242. Mesh._CAP_ALL = 3;
  28243. return Mesh;
  28244. }(BABYLON.AbstractMesh));
  28245. BABYLON.Mesh = Mesh;
  28246. })(BABYLON || (BABYLON = {}));
  28247. //# sourceMappingURL=babylon.mesh.js.map
  28248. var BABYLON;
  28249. (function (BABYLON) {
  28250. var BaseSubMesh = /** @class */ (function () {
  28251. function BaseSubMesh() {
  28252. }
  28253. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28254. get: function () {
  28255. return this._materialEffect;
  28256. },
  28257. enumerable: true,
  28258. configurable: true
  28259. });
  28260. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28261. if (defines === void 0) { defines = null; }
  28262. if (this._materialEffect === effect) {
  28263. if (!effect) {
  28264. this._materialDefines = null;
  28265. }
  28266. return;
  28267. }
  28268. this._materialDefines = defines;
  28269. this._materialEffect = effect;
  28270. };
  28271. return BaseSubMesh;
  28272. }());
  28273. BABYLON.BaseSubMesh = BaseSubMesh;
  28274. var SubMesh = /** @class */ (function (_super) {
  28275. __extends(SubMesh, _super);
  28276. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28277. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28278. var _this = _super.call(this) || this;
  28279. _this.materialIndex = materialIndex;
  28280. _this.verticesStart = verticesStart;
  28281. _this.verticesCount = verticesCount;
  28282. _this.indexStart = indexStart;
  28283. _this.indexCount = indexCount;
  28284. _this._renderId = 0;
  28285. _this._mesh = mesh;
  28286. _this._renderingMesh = renderingMesh || mesh;
  28287. mesh.subMeshes.push(_this);
  28288. _this._trianglePlanes = [];
  28289. _this._id = mesh.subMeshes.length - 1;
  28290. if (createBoundingBox) {
  28291. _this.refreshBoundingInfo();
  28292. mesh.computeWorldMatrix(true);
  28293. }
  28294. return _this;
  28295. }
  28296. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28297. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28298. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28299. };
  28300. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28301. get: function () {
  28302. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28303. },
  28304. enumerable: true,
  28305. configurable: true
  28306. });
  28307. /**
  28308. * Returns the submesh BoudingInfo object.
  28309. */
  28310. SubMesh.prototype.getBoundingInfo = function () {
  28311. if (this.IsGlobal) {
  28312. return this._mesh.getBoundingInfo();
  28313. }
  28314. return this._boundingInfo;
  28315. };
  28316. /**
  28317. * Sets the submesh BoundingInfo.
  28318. * Return the SubMesh.
  28319. */
  28320. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28321. this._boundingInfo = boundingInfo;
  28322. return this;
  28323. };
  28324. /**
  28325. * Returns the mesh of the current submesh.
  28326. */
  28327. SubMesh.prototype.getMesh = function () {
  28328. return this._mesh;
  28329. };
  28330. /**
  28331. * Returns the rendering mesh of the submesh.
  28332. */
  28333. SubMesh.prototype.getRenderingMesh = function () {
  28334. return this._renderingMesh;
  28335. };
  28336. /**
  28337. * Returns the submesh material.
  28338. */
  28339. SubMesh.prototype.getMaterial = function () {
  28340. var rootMaterial = this._renderingMesh.material;
  28341. if (rootMaterial === null || rootMaterial === undefined) {
  28342. return this._mesh.getScene().defaultMaterial;
  28343. }
  28344. else if (rootMaterial.getSubMaterial) {
  28345. var multiMaterial = rootMaterial;
  28346. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28347. if (this._currentMaterial !== effectiveMaterial) {
  28348. this._currentMaterial = effectiveMaterial;
  28349. this._materialDefines = null;
  28350. }
  28351. return effectiveMaterial;
  28352. }
  28353. return rootMaterial;
  28354. };
  28355. // Methods
  28356. /**
  28357. * Sets a new updated BoundingInfo object to the submesh.
  28358. * Returns the SubMesh.
  28359. */
  28360. SubMesh.prototype.refreshBoundingInfo = function () {
  28361. this._lastColliderWorldVertices = null;
  28362. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28363. return this;
  28364. }
  28365. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28366. if (!data) {
  28367. this._boundingInfo = this._mesh.getBoundingInfo();
  28368. return this;
  28369. }
  28370. var indices = this._renderingMesh.getIndices();
  28371. var extend;
  28372. //is this the only submesh?
  28373. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28374. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28375. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28376. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28377. }
  28378. else {
  28379. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28380. }
  28381. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28382. return this;
  28383. };
  28384. SubMesh.prototype._checkCollision = function (collider) {
  28385. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28386. return boundingInfo._checkCollision(collider);
  28387. };
  28388. /**
  28389. * Updates the submesh BoundingInfo.
  28390. * Returns the Submesh.
  28391. */
  28392. SubMesh.prototype.updateBoundingInfo = function (world) {
  28393. var boundingInfo = this.getBoundingInfo();
  28394. if (!boundingInfo) {
  28395. this.refreshBoundingInfo();
  28396. boundingInfo = this.getBoundingInfo();
  28397. }
  28398. boundingInfo.update(world);
  28399. return this;
  28400. };
  28401. /**
  28402. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28403. * Boolean returned.
  28404. */
  28405. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28406. var boundingInfo = this.getBoundingInfo();
  28407. if (!boundingInfo) {
  28408. return false;
  28409. }
  28410. return boundingInfo.isInFrustum(frustumPlanes);
  28411. };
  28412. /**
  28413. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28414. * Boolean returned.
  28415. */
  28416. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28417. var boundingInfo = this.getBoundingInfo();
  28418. if (!boundingInfo) {
  28419. return false;
  28420. }
  28421. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28422. };
  28423. /**
  28424. * Renders the submesh.
  28425. * Returns it.
  28426. */
  28427. SubMesh.prototype.render = function (enableAlphaMode) {
  28428. this._renderingMesh.render(this, enableAlphaMode);
  28429. return this;
  28430. };
  28431. /**
  28432. * Returns a new Index Buffer.
  28433. * Type returned : WebGLBuffer.
  28434. */
  28435. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28436. if (!this._linesIndexBuffer) {
  28437. var linesIndices = [];
  28438. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28439. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28440. }
  28441. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28442. this.linesIndexCount = linesIndices.length;
  28443. }
  28444. return this._linesIndexBuffer;
  28445. };
  28446. /**
  28447. * True is the passed Ray intersects the submesh bounding box.
  28448. * Boolean returned.
  28449. */
  28450. SubMesh.prototype.canIntersects = function (ray) {
  28451. var boundingInfo = this.getBoundingInfo();
  28452. if (!boundingInfo) {
  28453. return false;
  28454. }
  28455. return ray.intersectsBox(boundingInfo.boundingBox);
  28456. };
  28457. /**
  28458. * Returns an object IntersectionInfo.
  28459. */
  28460. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28461. var intersectInfo = null;
  28462. // LineMesh first as it's also a Mesh...
  28463. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28464. var lineMesh = this._mesh;
  28465. // Line test
  28466. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28467. var p0 = positions[indices[index]];
  28468. var p1 = positions[indices[index + 1]];
  28469. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28470. if (length < 0) {
  28471. continue;
  28472. }
  28473. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28474. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28475. if (fastCheck) {
  28476. break;
  28477. }
  28478. }
  28479. }
  28480. }
  28481. else {
  28482. // Triangles test
  28483. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28484. var p0 = positions[indices[index]];
  28485. var p1 = positions[indices[index + 1]];
  28486. var p2 = positions[indices[index + 2]];
  28487. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28488. if (currentIntersectInfo) {
  28489. if (currentIntersectInfo.distance < 0) {
  28490. continue;
  28491. }
  28492. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28493. intersectInfo = currentIntersectInfo;
  28494. intersectInfo.faceId = index / 3;
  28495. if (fastCheck) {
  28496. break;
  28497. }
  28498. }
  28499. }
  28500. }
  28501. }
  28502. return intersectInfo;
  28503. };
  28504. SubMesh.prototype._rebuild = function () {
  28505. if (this._linesIndexBuffer) {
  28506. this._linesIndexBuffer = null;
  28507. }
  28508. };
  28509. // Clone
  28510. /**
  28511. * Creates a new Submesh from the passed Mesh.
  28512. */
  28513. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28514. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28515. if (!this.IsGlobal) {
  28516. var boundingInfo = this.getBoundingInfo();
  28517. if (!boundingInfo) {
  28518. return result;
  28519. }
  28520. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28521. }
  28522. return result;
  28523. };
  28524. // Dispose
  28525. /**
  28526. * Disposes the Submesh.
  28527. * Returns nothing.
  28528. */
  28529. SubMesh.prototype.dispose = function () {
  28530. if (this._linesIndexBuffer) {
  28531. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28532. this._linesIndexBuffer = null;
  28533. }
  28534. // Remove from mesh
  28535. var index = this._mesh.subMeshes.indexOf(this);
  28536. this._mesh.subMeshes.splice(index, 1);
  28537. };
  28538. // Statics
  28539. /**
  28540. * Creates a new Submesh from the passed parameters :
  28541. * - materialIndex (integer) : the index of the main mesh material.
  28542. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28543. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28544. * - mesh (Mesh) : the main mesh to create the submesh from.
  28545. * - renderingMesh (optional Mesh) : rendering mesh.
  28546. */
  28547. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28548. var minVertexIndex = Number.MAX_VALUE;
  28549. var maxVertexIndex = -Number.MAX_VALUE;
  28550. renderingMesh = (renderingMesh || mesh);
  28551. var indices = renderingMesh.getIndices();
  28552. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28553. var vertexIndex = indices[index];
  28554. if (vertexIndex < minVertexIndex)
  28555. minVertexIndex = vertexIndex;
  28556. if (vertexIndex > maxVertexIndex)
  28557. maxVertexIndex = vertexIndex;
  28558. }
  28559. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28560. };
  28561. return SubMesh;
  28562. }(BaseSubMesh));
  28563. BABYLON.SubMesh = SubMesh;
  28564. })(BABYLON || (BABYLON = {}));
  28565. //# sourceMappingURL=babylon.subMesh.js.map
  28566. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28567. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28568. s = arguments[i];
  28569. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28570. t[p] = s[p];
  28571. }
  28572. return t;
  28573. };
  28574. var BABYLON;
  28575. (function (BABYLON) {
  28576. var MaterialDefines = /** @class */ (function () {
  28577. function MaterialDefines() {
  28578. this._isDirty = true;
  28579. this._areLightsDirty = true;
  28580. this._areAttributesDirty = true;
  28581. this._areTexturesDirty = true;
  28582. this._areFresnelDirty = true;
  28583. this._areMiscDirty = true;
  28584. this._areImageProcessingDirty = true;
  28585. this._normals = false;
  28586. this._uvs = false;
  28587. this._needNormals = false;
  28588. this._needUVs = false;
  28589. }
  28590. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28591. get: function () {
  28592. return this._isDirty;
  28593. },
  28594. enumerable: true,
  28595. configurable: true
  28596. });
  28597. MaterialDefines.prototype.markAsProcessed = function () {
  28598. this._isDirty = false;
  28599. this._areAttributesDirty = false;
  28600. this._areTexturesDirty = false;
  28601. this._areFresnelDirty = false;
  28602. this._areLightsDirty = false;
  28603. this._areMiscDirty = false;
  28604. this._areImageProcessingDirty = false;
  28605. };
  28606. MaterialDefines.prototype.markAsUnprocessed = function () {
  28607. this._isDirty = true;
  28608. };
  28609. MaterialDefines.prototype.markAllAsDirty = function () {
  28610. this._areTexturesDirty = true;
  28611. this._areAttributesDirty = true;
  28612. this._areLightsDirty = true;
  28613. this._areFresnelDirty = true;
  28614. this._areMiscDirty = true;
  28615. this._areImageProcessingDirty = true;
  28616. this._isDirty = true;
  28617. };
  28618. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28619. this._areImageProcessingDirty = true;
  28620. this._isDirty = true;
  28621. };
  28622. MaterialDefines.prototype.markAsLightDirty = function () {
  28623. this._areLightsDirty = true;
  28624. this._isDirty = true;
  28625. };
  28626. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28627. this._areAttributesDirty = true;
  28628. this._isDirty = true;
  28629. };
  28630. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28631. this._areTexturesDirty = true;
  28632. this._isDirty = true;
  28633. };
  28634. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28635. this._areFresnelDirty = true;
  28636. this._isDirty = true;
  28637. };
  28638. MaterialDefines.prototype.markAsMiscDirty = function () {
  28639. this._areMiscDirty = true;
  28640. this._isDirty = true;
  28641. };
  28642. MaterialDefines.prototype.rebuild = function () {
  28643. if (this._keys) {
  28644. delete this._keys;
  28645. }
  28646. this._keys = [];
  28647. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28648. var key = _a[_i];
  28649. if (key[0] === "_") {
  28650. continue;
  28651. }
  28652. this._keys.push(key);
  28653. }
  28654. };
  28655. MaterialDefines.prototype.isEqual = function (other) {
  28656. if (this._keys.length !== other._keys.length) {
  28657. return false;
  28658. }
  28659. for (var index = 0; index < this._keys.length; index++) {
  28660. var prop = this._keys[index];
  28661. if (this[prop] !== other[prop]) {
  28662. return false;
  28663. }
  28664. }
  28665. return true;
  28666. };
  28667. MaterialDefines.prototype.cloneTo = function (other) {
  28668. if (this._keys.length !== other._keys.length) {
  28669. other._keys = this._keys.slice(0);
  28670. }
  28671. for (var index = 0; index < this._keys.length; index++) {
  28672. var prop = this._keys[index];
  28673. other[prop] = this[prop];
  28674. }
  28675. };
  28676. MaterialDefines.prototype.reset = function () {
  28677. for (var index = 0; index < this._keys.length; index++) {
  28678. var prop = this._keys[index];
  28679. if (typeof (this[prop]) === "number") {
  28680. this[prop] = 0;
  28681. }
  28682. else {
  28683. this[prop] = false;
  28684. }
  28685. }
  28686. };
  28687. MaterialDefines.prototype.toString = function () {
  28688. var result = "";
  28689. for (var index = 0; index < this._keys.length; index++) {
  28690. var prop = this._keys[index];
  28691. var value = this[prop];
  28692. if (typeof (value) === "number") {
  28693. result += "#define " + prop + " " + this[prop] + "\n";
  28694. }
  28695. else if (value) {
  28696. result += "#define " + prop + "\n";
  28697. }
  28698. }
  28699. return result;
  28700. };
  28701. return MaterialDefines;
  28702. }());
  28703. BABYLON.MaterialDefines = MaterialDefines;
  28704. var Material = /** @class */ (function () {
  28705. function Material(name, scene, doNotAdd) {
  28706. this.checkReadyOnEveryCall = false;
  28707. this.checkReadyOnlyOnce = false;
  28708. this.state = "";
  28709. this.alpha = 1.0;
  28710. this._backFaceCulling = true;
  28711. this.doNotSerialize = false;
  28712. this.storeEffectOnSubMeshes = false;
  28713. /**
  28714. * An event triggered when the material is disposed.
  28715. * @type {BABYLON.Observable}
  28716. */
  28717. this.onDisposeObservable = new BABYLON.Observable();
  28718. /**
  28719. * An event triggered when the material is bound.
  28720. * @type {BABYLON.Observable}
  28721. */
  28722. this.onBindObservable = new BABYLON.Observable();
  28723. /**
  28724. * An event triggered when the material is unbound.
  28725. * @type {BABYLON.Observable}
  28726. */
  28727. this.onUnBindObservable = new BABYLON.Observable();
  28728. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28729. this._needDepthPrePass = false;
  28730. this.disableDepthWrite = false;
  28731. this.forceDepthWrite = false;
  28732. this.separateCullingPass = false;
  28733. this._fogEnabled = true;
  28734. this.pointSize = 1.0;
  28735. this.zOffset = 0;
  28736. this._wasPreviouslyReady = false;
  28737. this._fillMode = Material.TriangleFillMode;
  28738. this.name = name;
  28739. this.id = name || BABYLON.Tools.RandomId();
  28740. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28741. if (this._scene.useRightHandedSystem) {
  28742. this.sideOrientation = Material.ClockWiseSideOrientation;
  28743. }
  28744. else {
  28745. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28746. }
  28747. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28748. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28749. if (!doNotAdd) {
  28750. this._scene.materials.push(this);
  28751. }
  28752. }
  28753. Object.defineProperty(Material, "TriangleFillMode", {
  28754. get: function () {
  28755. return Material._TriangleFillMode;
  28756. },
  28757. enumerable: true,
  28758. configurable: true
  28759. });
  28760. Object.defineProperty(Material, "WireFrameFillMode", {
  28761. get: function () {
  28762. return Material._WireFrameFillMode;
  28763. },
  28764. enumerable: true,
  28765. configurable: true
  28766. });
  28767. Object.defineProperty(Material, "PointFillMode", {
  28768. get: function () {
  28769. return Material._PointFillMode;
  28770. },
  28771. enumerable: true,
  28772. configurable: true
  28773. });
  28774. Object.defineProperty(Material, "PointListDrawMode", {
  28775. get: function () {
  28776. return Material._PointListDrawMode;
  28777. },
  28778. enumerable: true,
  28779. configurable: true
  28780. });
  28781. Object.defineProperty(Material, "LineListDrawMode", {
  28782. get: function () {
  28783. return Material._LineListDrawMode;
  28784. },
  28785. enumerable: true,
  28786. configurable: true
  28787. });
  28788. Object.defineProperty(Material, "LineLoopDrawMode", {
  28789. get: function () {
  28790. return Material._LineLoopDrawMode;
  28791. },
  28792. enumerable: true,
  28793. configurable: true
  28794. });
  28795. Object.defineProperty(Material, "LineStripDrawMode", {
  28796. get: function () {
  28797. return Material._LineStripDrawMode;
  28798. },
  28799. enumerable: true,
  28800. configurable: true
  28801. });
  28802. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28803. get: function () {
  28804. return Material._TriangleStripDrawMode;
  28805. },
  28806. enumerable: true,
  28807. configurable: true
  28808. });
  28809. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28810. get: function () {
  28811. return Material._TriangleFanDrawMode;
  28812. },
  28813. enumerable: true,
  28814. configurable: true
  28815. });
  28816. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28817. get: function () {
  28818. return Material._ClockWiseSideOrientation;
  28819. },
  28820. enumerable: true,
  28821. configurable: true
  28822. });
  28823. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28824. get: function () {
  28825. return Material._CounterClockWiseSideOrientation;
  28826. },
  28827. enumerable: true,
  28828. configurable: true
  28829. });
  28830. Object.defineProperty(Material, "TextureDirtyFlag", {
  28831. get: function () {
  28832. return Material._TextureDirtyFlag;
  28833. },
  28834. enumerable: true,
  28835. configurable: true
  28836. });
  28837. Object.defineProperty(Material, "LightDirtyFlag", {
  28838. get: function () {
  28839. return Material._LightDirtyFlag;
  28840. },
  28841. enumerable: true,
  28842. configurable: true
  28843. });
  28844. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28845. get: function () {
  28846. return Material._FresnelDirtyFlag;
  28847. },
  28848. enumerable: true,
  28849. configurable: true
  28850. });
  28851. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28852. get: function () {
  28853. return Material._AttributesDirtyFlag;
  28854. },
  28855. enumerable: true,
  28856. configurable: true
  28857. });
  28858. Object.defineProperty(Material, "MiscDirtyFlag", {
  28859. get: function () {
  28860. return Material._MiscDirtyFlag;
  28861. },
  28862. enumerable: true,
  28863. configurable: true
  28864. });
  28865. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28866. get: function () {
  28867. return this._backFaceCulling;
  28868. },
  28869. set: function (value) {
  28870. if (this._backFaceCulling === value) {
  28871. return;
  28872. }
  28873. this._backFaceCulling = value;
  28874. this.markAsDirty(Material.TextureDirtyFlag);
  28875. },
  28876. enumerable: true,
  28877. configurable: true
  28878. });
  28879. Object.defineProperty(Material.prototype, "onDispose", {
  28880. set: function (callback) {
  28881. if (this._onDisposeObserver) {
  28882. this.onDisposeObservable.remove(this._onDisposeObserver);
  28883. }
  28884. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28885. },
  28886. enumerable: true,
  28887. configurable: true
  28888. });
  28889. Object.defineProperty(Material.prototype, "onBind", {
  28890. set: function (callback) {
  28891. if (this._onBindObserver) {
  28892. this.onBindObservable.remove(this._onBindObserver);
  28893. }
  28894. this._onBindObserver = this.onBindObservable.add(callback);
  28895. },
  28896. enumerable: true,
  28897. configurable: true
  28898. });
  28899. Object.defineProperty(Material.prototype, "alphaMode", {
  28900. get: function () {
  28901. return this._alphaMode;
  28902. },
  28903. set: function (value) {
  28904. if (this._alphaMode === value) {
  28905. return;
  28906. }
  28907. this._alphaMode = value;
  28908. this.markAsDirty(Material.TextureDirtyFlag);
  28909. },
  28910. enumerable: true,
  28911. configurable: true
  28912. });
  28913. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28914. get: function () {
  28915. return this._needDepthPrePass;
  28916. },
  28917. set: function (value) {
  28918. if (this._needDepthPrePass === value) {
  28919. return;
  28920. }
  28921. this._needDepthPrePass = value;
  28922. if (this._needDepthPrePass) {
  28923. this.checkReadyOnEveryCall = true;
  28924. }
  28925. },
  28926. enumerable: true,
  28927. configurable: true
  28928. });
  28929. Object.defineProperty(Material.prototype, "fogEnabled", {
  28930. get: function () {
  28931. return this._fogEnabled;
  28932. },
  28933. set: function (value) {
  28934. if (this._fogEnabled === value) {
  28935. return;
  28936. }
  28937. this._fogEnabled = value;
  28938. this.markAsDirty(Material.MiscDirtyFlag);
  28939. },
  28940. enumerable: true,
  28941. configurable: true
  28942. });
  28943. Object.defineProperty(Material.prototype, "wireframe", {
  28944. get: function () {
  28945. return this._fillMode === Material.WireFrameFillMode;
  28946. },
  28947. set: function (value) {
  28948. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28949. },
  28950. enumerable: true,
  28951. configurable: true
  28952. });
  28953. Object.defineProperty(Material.prototype, "pointsCloud", {
  28954. get: function () {
  28955. return this._fillMode === Material.PointFillMode;
  28956. },
  28957. set: function (value) {
  28958. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28959. },
  28960. enumerable: true,
  28961. configurable: true
  28962. });
  28963. Object.defineProperty(Material.prototype, "fillMode", {
  28964. get: function () {
  28965. return this._fillMode;
  28966. },
  28967. set: function (value) {
  28968. if (this._fillMode === value) {
  28969. return;
  28970. }
  28971. this._fillMode = value;
  28972. this.markAsDirty(Material.MiscDirtyFlag);
  28973. },
  28974. enumerable: true,
  28975. configurable: true
  28976. });
  28977. /**
  28978. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28979. * subclasses should override adding information pertainent to themselves
  28980. */
  28981. Material.prototype.toString = function (fullDetails) {
  28982. var ret = "Name: " + this.name;
  28983. if (fullDetails) {
  28984. }
  28985. return ret;
  28986. };
  28987. /**
  28988. * Child classes can use it to update shaders
  28989. */
  28990. Material.prototype.getClassName = function () {
  28991. return "Material";
  28992. };
  28993. Object.defineProperty(Material.prototype, "isFrozen", {
  28994. get: function () {
  28995. return this.checkReadyOnlyOnce;
  28996. },
  28997. enumerable: true,
  28998. configurable: true
  28999. });
  29000. Material.prototype.freeze = function () {
  29001. this.checkReadyOnlyOnce = true;
  29002. };
  29003. Material.prototype.unfreeze = function () {
  29004. this.checkReadyOnlyOnce = false;
  29005. };
  29006. Material.prototype.isReady = function (mesh, useInstances) {
  29007. return true;
  29008. };
  29009. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29010. return false;
  29011. };
  29012. Material.prototype.getEffect = function () {
  29013. return this._effect;
  29014. };
  29015. Material.prototype.getScene = function () {
  29016. return this._scene;
  29017. };
  29018. Material.prototype.needAlphaBlending = function () {
  29019. return (this.alpha < 1.0);
  29020. };
  29021. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29022. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29023. };
  29024. Material.prototype.needAlphaTesting = function () {
  29025. return false;
  29026. };
  29027. Material.prototype.getAlphaTestTexture = function () {
  29028. return null;
  29029. };
  29030. Material.prototype.markDirty = function () {
  29031. this._wasPreviouslyReady = false;
  29032. };
  29033. Material.prototype._preBind = function (effect, overrideOrientation) {
  29034. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29035. var engine = this._scene.getEngine();
  29036. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29037. var reverse = orientation === Material.ClockWiseSideOrientation;
  29038. engine.enableEffect(effect ? effect : this._effect);
  29039. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29040. return reverse;
  29041. };
  29042. Material.prototype.bind = function (world, mesh) {
  29043. };
  29044. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29045. };
  29046. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29047. };
  29048. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29049. sceneUbo.bindToEffect(effect, "Scene");
  29050. };
  29051. Material.prototype.bindView = function (effect) {
  29052. if (!this._useUBO) {
  29053. effect.setMatrix("view", this.getScene().getViewMatrix());
  29054. }
  29055. else {
  29056. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29057. }
  29058. };
  29059. Material.prototype.bindViewProjection = function (effect) {
  29060. if (!this._useUBO) {
  29061. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29062. }
  29063. else {
  29064. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29065. }
  29066. };
  29067. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29068. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29069. };
  29070. Material.prototype._afterBind = function (mesh) {
  29071. this._scene._cachedMaterial = this;
  29072. if (mesh) {
  29073. this._scene._cachedVisibility = mesh.visibility;
  29074. }
  29075. else {
  29076. this._scene._cachedVisibility = 1;
  29077. }
  29078. if (mesh) {
  29079. this.onBindObservable.notifyObservers(mesh);
  29080. }
  29081. if (this.disableDepthWrite) {
  29082. var engine = this._scene.getEngine();
  29083. this._cachedDepthWriteState = engine.getDepthWrite();
  29084. engine.setDepthWrite(false);
  29085. }
  29086. };
  29087. Material.prototype.unbind = function () {
  29088. this.onUnBindObservable.notifyObservers(this);
  29089. if (this.disableDepthWrite) {
  29090. var engine = this._scene.getEngine();
  29091. engine.setDepthWrite(this._cachedDepthWriteState);
  29092. }
  29093. };
  29094. Material.prototype.getActiveTextures = function () {
  29095. return [];
  29096. };
  29097. Material.prototype.hasTexture = function (texture) {
  29098. return false;
  29099. };
  29100. Material.prototype.clone = function (name) {
  29101. return null;
  29102. };
  29103. Material.prototype.getBindedMeshes = function () {
  29104. var result = new Array();
  29105. for (var index = 0; index < this._scene.meshes.length; index++) {
  29106. var mesh = this._scene.meshes[index];
  29107. if (mesh.material === this) {
  29108. result.push(mesh);
  29109. }
  29110. }
  29111. return result;
  29112. };
  29113. /**
  29114. * Force shader compilation including textures ready check
  29115. */
  29116. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29117. var _this = this;
  29118. var localOptions = __assign({ clipPlane: false }, options);
  29119. var subMesh = new BABYLON.BaseSubMesh();
  29120. var scene = this.getScene();
  29121. var checkReady = function () {
  29122. if (!_this._scene || !_this._scene.getEngine()) {
  29123. return;
  29124. }
  29125. if (subMesh._materialDefines) {
  29126. subMesh._materialDefines._renderId = -1;
  29127. }
  29128. var clipPlaneState = scene.clipPlane;
  29129. if (localOptions.clipPlane) {
  29130. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29131. }
  29132. if (_this.storeEffectOnSubMeshes) {
  29133. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29134. if (onCompiled) {
  29135. onCompiled(_this);
  29136. }
  29137. }
  29138. else {
  29139. setTimeout(checkReady, 16);
  29140. }
  29141. }
  29142. else {
  29143. if (_this.isReady(mesh)) {
  29144. if (onCompiled) {
  29145. onCompiled(_this);
  29146. }
  29147. }
  29148. else {
  29149. setTimeout(checkReady, 16);
  29150. }
  29151. }
  29152. if (options && options.clipPlane) {
  29153. scene.clipPlane = clipPlaneState;
  29154. }
  29155. };
  29156. checkReady();
  29157. };
  29158. Material.prototype.markAsDirty = function (flag) {
  29159. if (flag & Material.TextureDirtyFlag) {
  29160. this._markAllSubMeshesAsTexturesDirty();
  29161. }
  29162. if (flag & Material.LightDirtyFlag) {
  29163. this._markAllSubMeshesAsLightsDirty();
  29164. }
  29165. if (flag & Material.FresnelDirtyFlag) {
  29166. this._markAllSubMeshesAsFresnelDirty();
  29167. }
  29168. if (flag & Material.AttributesDirtyFlag) {
  29169. this._markAllSubMeshesAsAttributesDirty();
  29170. }
  29171. if (flag & Material.MiscDirtyFlag) {
  29172. this._markAllSubMeshesAsMiscDirty();
  29173. }
  29174. this.getScene().resetCachedMaterial();
  29175. };
  29176. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29177. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29178. var mesh = _a[_i];
  29179. if (!mesh.subMeshes) {
  29180. continue;
  29181. }
  29182. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29183. var subMesh = _c[_b];
  29184. if (subMesh.getMaterial() !== this) {
  29185. continue;
  29186. }
  29187. if (!subMesh._materialDefines) {
  29188. continue;
  29189. }
  29190. func(subMesh._materialDefines);
  29191. }
  29192. }
  29193. };
  29194. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29195. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29196. };
  29197. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29198. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29199. };
  29200. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29201. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29202. };
  29203. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29204. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29205. };
  29206. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29207. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29208. };
  29209. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29210. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29211. };
  29212. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29213. // Animations
  29214. this.getScene().stopAnimation(this);
  29215. // Remove from scene
  29216. var index = this._scene.materials.indexOf(this);
  29217. if (index >= 0) {
  29218. this._scene.materials.splice(index, 1);
  29219. }
  29220. // Remove from meshes
  29221. for (index = 0; index < this._scene.meshes.length; index++) {
  29222. var mesh = this._scene.meshes[index];
  29223. if (mesh.material === this) {
  29224. mesh.material = null;
  29225. if (mesh.geometry) {
  29226. var geometry = (mesh.geometry);
  29227. if (this.storeEffectOnSubMeshes) {
  29228. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29229. var subMesh = _a[_i];
  29230. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29231. if (forceDisposeEffect && subMesh._materialEffect) {
  29232. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29233. }
  29234. }
  29235. }
  29236. else {
  29237. geometry._releaseVertexArrayObject(this._effect);
  29238. }
  29239. }
  29240. }
  29241. }
  29242. this._uniformBuffer.dispose();
  29243. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29244. if (forceDisposeEffect && this._effect) {
  29245. if (!this.storeEffectOnSubMeshes) {
  29246. this._scene.getEngine()._releaseEffect(this._effect);
  29247. }
  29248. this._effect = null;
  29249. }
  29250. // Callback
  29251. this.onDisposeObservable.notifyObservers(this);
  29252. this.onDisposeObservable.clear();
  29253. this.onBindObservable.clear();
  29254. this.onUnBindObservable.clear();
  29255. };
  29256. Material.prototype.serialize = function () {
  29257. return BABYLON.SerializationHelper.Serialize(this);
  29258. };
  29259. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29260. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29261. multiMaterial.id = parsedMultiMaterial.id;
  29262. if (BABYLON.Tags) {
  29263. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29264. }
  29265. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29266. var subMatId = parsedMultiMaterial.materials[matIndex];
  29267. if (subMatId) {
  29268. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29269. }
  29270. else {
  29271. multiMaterial.subMaterials.push(null);
  29272. }
  29273. }
  29274. return multiMaterial;
  29275. };
  29276. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29277. if (!parsedMaterial.customType) {
  29278. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29279. }
  29280. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29281. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29282. if (!BABYLON.LegacyPBRMaterial) {
  29283. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29284. return;
  29285. }
  29286. }
  29287. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29288. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29289. ;
  29290. };
  29291. // Triangle views
  29292. Material._TriangleFillMode = 0;
  29293. Material._WireFrameFillMode = 1;
  29294. Material._PointFillMode = 2;
  29295. // Draw modes
  29296. Material._PointListDrawMode = 3;
  29297. Material._LineListDrawMode = 4;
  29298. Material._LineLoopDrawMode = 5;
  29299. Material._LineStripDrawMode = 6;
  29300. Material._TriangleStripDrawMode = 7;
  29301. Material._TriangleFanDrawMode = 8;
  29302. Material._ClockWiseSideOrientation = 0;
  29303. Material._CounterClockWiseSideOrientation = 1;
  29304. Material._TextureDirtyFlag = 1;
  29305. Material._LightDirtyFlag = 2;
  29306. Material._FresnelDirtyFlag = 4;
  29307. Material._AttributesDirtyFlag = 8;
  29308. Material._MiscDirtyFlag = 16;
  29309. __decorate([
  29310. BABYLON.serialize()
  29311. ], Material.prototype, "id", void 0);
  29312. __decorate([
  29313. BABYLON.serialize()
  29314. ], Material.prototype, "name", void 0);
  29315. __decorate([
  29316. BABYLON.serialize()
  29317. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29318. __decorate([
  29319. BABYLON.serialize()
  29320. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29321. __decorate([
  29322. BABYLON.serialize()
  29323. ], Material.prototype, "state", void 0);
  29324. __decorate([
  29325. BABYLON.serialize()
  29326. ], Material.prototype, "alpha", void 0);
  29327. __decorate([
  29328. BABYLON.serialize("backFaceCulling")
  29329. ], Material.prototype, "_backFaceCulling", void 0);
  29330. __decorate([
  29331. BABYLON.serialize()
  29332. ], Material.prototype, "sideOrientation", void 0);
  29333. __decorate([
  29334. BABYLON.serialize("alphaMode")
  29335. ], Material.prototype, "_alphaMode", void 0);
  29336. __decorate([
  29337. BABYLON.serialize()
  29338. ], Material.prototype, "_needDepthPrePass", void 0);
  29339. __decorate([
  29340. BABYLON.serialize()
  29341. ], Material.prototype, "disableDepthWrite", void 0);
  29342. __decorate([
  29343. BABYLON.serialize()
  29344. ], Material.prototype, "forceDepthWrite", void 0);
  29345. __decorate([
  29346. BABYLON.serialize()
  29347. ], Material.prototype, "separateCullingPass", void 0);
  29348. __decorate([
  29349. BABYLON.serialize("fogEnabled")
  29350. ], Material.prototype, "_fogEnabled", void 0);
  29351. __decorate([
  29352. BABYLON.serialize()
  29353. ], Material.prototype, "pointSize", void 0);
  29354. __decorate([
  29355. BABYLON.serialize()
  29356. ], Material.prototype, "zOffset", void 0);
  29357. __decorate([
  29358. BABYLON.serialize()
  29359. ], Material.prototype, "wireframe", null);
  29360. __decorate([
  29361. BABYLON.serialize()
  29362. ], Material.prototype, "pointsCloud", null);
  29363. __decorate([
  29364. BABYLON.serialize()
  29365. ], Material.prototype, "fillMode", null);
  29366. return Material;
  29367. }());
  29368. BABYLON.Material = Material;
  29369. })(BABYLON || (BABYLON = {}));
  29370. //# sourceMappingURL=babylon.material.js.map
  29371. var BABYLON;
  29372. (function (BABYLON) {
  29373. var UniformBuffer = /** @class */ (function () {
  29374. /**
  29375. * Uniform buffer objects.
  29376. *
  29377. * Handles blocks of uniform on the GPU.
  29378. *
  29379. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29380. *
  29381. * For more information, please refer to :
  29382. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29383. */
  29384. function UniformBuffer(engine, data, dynamic) {
  29385. this._engine = engine;
  29386. this._noUBO = !engine.supportsUniformBuffers;
  29387. this._dynamic = dynamic;
  29388. this._data = data || [];
  29389. this._uniformLocations = {};
  29390. this._uniformSizes = {};
  29391. this._uniformLocationPointer = 0;
  29392. this._needSync = false;
  29393. if (this._noUBO) {
  29394. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29395. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29396. this.updateFloat = this._updateFloatForEffect;
  29397. this.updateFloat2 = this._updateFloat2ForEffect;
  29398. this.updateFloat3 = this._updateFloat3ForEffect;
  29399. this.updateFloat4 = this._updateFloat4ForEffect;
  29400. this.updateMatrix = this._updateMatrixForEffect;
  29401. this.updateVector3 = this._updateVector3ForEffect;
  29402. this.updateVector4 = this._updateVector4ForEffect;
  29403. this.updateColor3 = this._updateColor3ForEffect;
  29404. this.updateColor4 = this._updateColor4ForEffect;
  29405. }
  29406. else {
  29407. this._engine._uniformBuffers.push(this);
  29408. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29409. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29410. this.updateFloat = this._updateFloatForUniform;
  29411. this.updateFloat2 = this._updateFloat2ForUniform;
  29412. this.updateFloat3 = this._updateFloat3ForUniform;
  29413. this.updateFloat4 = this._updateFloat4ForUniform;
  29414. this.updateMatrix = this._updateMatrixForUniform;
  29415. this.updateVector3 = this._updateVector3ForUniform;
  29416. this.updateVector4 = this._updateVector4ForUniform;
  29417. this.updateColor3 = this._updateColor3ForUniform;
  29418. this.updateColor4 = this._updateColor4ForUniform;
  29419. }
  29420. }
  29421. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29422. // Properties
  29423. /**
  29424. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29425. * or just falling back on setUniformXXX calls.
  29426. */
  29427. get: function () {
  29428. return !this._noUBO;
  29429. },
  29430. enumerable: true,
  29431. configurable: true
  29432. });
  29433. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29434. /**
  29435. * Indicates if the WebGL underlying uniform buffer is in sync
  29436. * with the javascript cache data.
  29437. */
  29438. get: function () {
  29439. return !this._needSync;
  29440. },
  29441. enumerable: true,
  29442. configurable: true
  29443. });
  29444. /**
  29445. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29446. * Also, a dynamic UniformBuffer will disable cache verification and always
  29447. * update the underlying WebGL uniform buffer to the GPU.
  29448. */
  29449. UniformBuffer.prototype.isDynamic = function () {
  29450. return this._dynamic !== undefined;
  29451. };
  29452. /**
  29453. * The data cache on JS side.
  29454. */
  29455. UniformBuffer.prototype.getData = function () {
  29456. return this._bufferData;
  29457. };
  29458. /**
  29459. * The underlying WebGL Uniform buffer.
  29460. */
  29461. UniformBuffer.prototype.getBuffer = function () {
  29462. return this._buffer;
  29463. };
  29464. /**
  29465. * std140 layout specifies how to align data within an UBO structure.
  29466. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29467. * for specs.
  29468. */
  29469. UniformBuffer.prototype._fillAlignment = function (size) {
  29470. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  29471. // and 4x4 matrices
  29472. // TODO : change if other types are used
  29473. var alignment;
  29474. if (size <= 2) {
  29475. alignment = size;
  29476. }
  29477. else {
  29478. alignment = 4;
  29479. }
  29480. if ((this._uniformLocationPointer % alignment) !== 0) {
  29481. var oldPointer = this._uniformLocationPointer;
  29482. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  29483. var diff = this._uniformLocationPointer - oldPointer;
  29484. for (var i = 0; i < diff; i++) {
  29485. this._data.push(0);
  29486. }
  29487. }
  29488. };
  29489. /**
  29490. * Adds an uniform in the buffer.
  29491. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  29492. * for the layout to be correct !
  29493. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29494. * @param {number|number[]} size Data size, or data directly.
  29495. */
  29496. UniformBuffer.prototype.addUniform = function (name, size) {
  29497. if (this._noUBO) {
  29498. return;
  29499. }
  29500. if (this._uniformLocations[name] !== undefined) {
  29501. // Already existing uniform
  29502. return;
  29503. }
  29504. // This function must be called in the order of the shader layout !
  29505. // size can be the size of the uniform, or data directly
  29506. var data;
  29507. if (size instanceof Array) {
  29508. data = size;
  29509. size = data.length;
  29510. }
  29511. else {
  29512. size = size;
  29513. data = [];
  29514. // Fill with zeros
  29515. for (var i = 0; i < size; i++) {
  29516. data.push(0);
  29517. }
  29518. }
  29519. this._fillAlignment(size);
  29520. this._uniformSizes[name] = size;
  29521. this._uniformLocations[name] = this._uniformLocationPointer;
  29522. this._uniformLocationPointer += size;
  29523. for (var i = 0; i < size; i++) {
  29524. this._data.push(data[i]);
  29525. }
  29526. this._needSync = true;
  29527. };
  29528. /**
  29529. * Wrapper for addUniform.
  29530. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29531. * @param {Matrix} mat A 4x4 matrix.
  29532. */
  29533. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29534. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29535. };
  29536. /**
  29537. * Wrapper for addUniform.
  29538. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29539. * @param {number} x
  29540. * @param {number} y
  29541. */
  29542. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29543. var temp = [x, y];
  29544. this.addUniform(name, temp);
  29545. };
  29546. /**
  29547. * Wrapper for addUniform.
  29548. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29549. * @param {number} x
  29550. * @param {number} y
  29551. * @param {number} z
  29552. */
  29553. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29554. var temp = [x, y, z];
  29555. this.addUniform(name, temp);
  29556. };
  29557. /**
  29558. * Wrapper for addUniform.
  29559. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29560. * @param {Color3} color
  29561. */
  29562. UniformBuffer.prototype.addColor3 = function (name, color) {
  29563. var temp = new Array();
  29564. color.toArray(temp);
  29565. this.addUniform(name, temp);
  29566. };
  29567. /**
  29568. * Wrapper for addUniform.
  29569. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29570. * @param {Color3} color
  29571. * @param {number} alpha
  29572. */
  29573. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29574. var temp = new Array();
  29575. color.toArray(temp);
  29576. temp.push(alpha);
  29577. this.addUniform(name, temp);
  29578. };
  29579. /**
  29580. * Wrapper for addUniform.
  29581. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29582. * @param {Vector3} vector
  29583. */
  29584. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29585. var temp = new Array();
  29586. vector.toArray(temp);
  29587. this.addUniform(name, temp);
  29588. };
  29589. /**
  29590. * Wrapper for addUniform.
  29591. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29592. */
  29593. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29594. this.addUniform(name, 12);
  29595. };
  29596. /**
  29597. * Wrapper for addUniform.
  29598. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29599. */
  29600. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29601. this.addUniform(name, 8);
  29602. };
  29603. /**
  29604. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29605. */
  29606. UniformBuffer.prototype.create = function () {
  29607. if (this._noUBO) {
  29608. return;
  29609. }
  29610. if (this._buffer) {
  29611. return; // nothing to do
  29612. }
  29613. // See spec, alignment must be filled as a vec4
  29614. this._fillAlignment(4);
  29615. this._bufferData = new Float32Array(this._data);
  29616. this._rebuild();
  29617. this._needSync = true;
  29618. };
  29619. UniformBuffer.prototype._rebuild = function () {
  29620. if (this._noUBO) {
  29621. return;
  29622. }
  29623. if (this._dynamic) {
  29624. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29625. }
  29626. else {
  29627. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29628. }
  29629. };
  29630. /**
  29631. * Updates the WebGL Uniform Buffer on the GPU.
  29632. * If the `dynamic` flag is set to true, no cache comparison is done.
  29633. * Otherwise, the buffer will be updated only if the cache differs.
  29634. */
  29635. UniformBuffer.prototype.update = function () {
  29636. if (!this._buffer) {
  29637. this.create();
  29638. return;
  29639. }
  29640. if (!this._dynamic && !this._needSync) {
  29641. return;
  29642. }
  29643. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29644. this._needSync = false;
  29645. };
  29646. /**
  29647. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29648. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29649. * @param {number[]|Float32Array} data Flattened data
  29650. * @param {number} size Size of the data.
  29651. */
  29652. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29653. var location = this._uniformLocations[uniformName];
  29654. if (location === undefined) {
  29655. if (this._buffer) {
  29656. // Cannot add an uniform if the buffer is already created
  29657. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29658. return;
  29659. }
  29660. this.addUniform(uniformName, size);
  29661. location = this._uniformLocations[uniformName];
  29662. }
  29663. if (!this._buffer) {
  29664. this.create();
  29665. }
  29666. if (!this._dynamic) {
  29667. // Cache for static uniform buffers
  29668. var changed = false;
  29669. for (var i = 0; i < size; i++) {
  29670. if (this._bufferData[location + i] !== data[i]) {
  29671. changed = true;
  29672. this._bufferData[location + i] = data[i];
  29673. }
  29674. }
  29675. this._needSync = this._needSync || changed;
  29676. }
  29677. else {
  29678. // No cache for dynamic
  29679. for (var i = 0; i < size; i++) {
  29680. this._bufferData[location + i] = data[i];
  29681. }
  29682. }
  29683. };
  29684. // Update methods
  29685. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29686. // To match std140, matrix must be realigned
  29687. for (var i = 0; i < 3; i++) {
  29688. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29689. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29690. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29691. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29692. }
  29693. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29694. };
  29695. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29696. this._currentEffect.setMatrix3x3(name, matrix);
  29697. };
  29698. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29699. this._currentEffect.setMatrix2x2(name, matrix);
  29700. };
  29701. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29702. // To match std140, matrix must be realigned
  29703. for (var i = 0; i < 2; i++) {
  29704. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29705. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29706. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29707. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29708. }
  29709. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29710. };
  29711. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29712. this._currentEffect.setFloat(name, x);
  29713. };
  29714. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29715. UniformBuffer._tempBuffer[0] = x;
  29716. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29717. };
  29718. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29719. if (suffix === void 0) { suffix = ""; }
  29720. this._currentEffect.setFloat2(name + suffix, x, y);
  29721. };
  29722. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29723. if (suffix === void 0) { suffix = ""; }
  29724. UniformBuffer._tempBuffer[0] = x;
  29725. UniformBuffer._tempBuffer[1] = y;
  29726. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29727. };
  29728. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29729. if (suffix === void 0) { suffix = ""; }
  29730. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29731. };
  29732. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29733. if (suffix === void 0) { suffix = ""; }
  29734. UniformBuffer._tempBuffer[0] = x;
  29735. UniformBuffer._tempBuffer[1] = y;
  29736. UniformBuffer._tempBuffer[2] = z;
  29737. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29738. };
  29739. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29740. if (suffix === void 0) { suffix = ""; }
  29741. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29742. };
  29743. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29744. if (suffix === void 0) { suffix = ""; }
  29745. UniformBuffer._tempBuffer[0] = x;
  29746. UniformBuffer._tempBuffer[1] = y;
  29747. UniformBuffer._tempBuffer[2] = z;
  29748. UniformBuffer._tempBuffer[3] = w;
  29749. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29750. };
  29751. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29752. this._currentEffect.setMatrix(name, mat);
  29753. };
  29754. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29755. this.updateUniform(name, mat.toArray(), 16);
  29756. };
  29757. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29758. this._currentEffect.setVector3(name, vector);
  29759. };
  29760. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29761. vector.toArray(UniformBuffer._tempBuffer);
  29762. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29763. };
  29764. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29765. this._currentEffect.setVector4(name, vector);
  29766. };
  29767. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29768. vector.toArray(UniformBuffer._tempBuffer);
  29769. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29770. };
  29771. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29772. if (suffix === void 0) { suffix = ""; }
  29773. this._currentEffect.setColor3(name + suffix, color);
  29774. };
  29775. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29776. if (suffix === void 0) { suffix = ""; }
  29777. color.toArray(UniformBuffer._tempBuffer);
  29778. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29779. };
  29780. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29781. if (suffix === void 0) { suffix = ""; }
  29782. this._currentEffect.setColor4(name + suffix, color, alpha);
  29783. };
  29784. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29785. if (suffix === void 0) { suffix = ""; }
  29786. color.toArray(UniformBuffer._tempBuffer);
  29787. UniformBuffer._tempBuffer[3] = alpha;
  29788. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29789. };
  29790. /**
  29791. * Sets a sampler uniform on the effect.
  29792. * @param {string} name Name of the sampler.
  29793. * @param {Texture} texture
  29794. */
  29795. UniformBuffer.prototype.setTexture = function (name, texture) {
  29796. this._currentEffect.setTexture(name, texture);
  29797. };
  29798. /**
  29799. * Directly updates the value of the uniform in the cache AND on the GPU.
  29800. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29801. * @param {number[]|Float32Array} data Flattened data
  29802. */
  29803. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29804. this.updateUniform(uniformName, data, data.length);
  29805. this.update();
  29806. };
  29807. /**
  29808. * Binds this uniform buffer to an effect.
  29809. * @param {Effect} effect
  29810. * @param {string} name Name of the uniform block in the shader.
  29811. */
  29812. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29813. this._currentEffect = effect;
  29814. if (this._noUBO || !this._buffer) {
  29815. return;
  29816. }
  29817. effect.bindUniformBuffer(this._buffer, name);
  29818. };
  29819. /**
  29820. * Disposes the uniform buffer.
  29821. */
  29822. UniformBuffer.prototype.dispose = function () {
  29823. if (this._noUBO) {
  29824. return;
  29825. }
  29826. var index = this._engine._uniformBuffers.indexOf(this);
  29827. if (index !== -1) {
  29828. this._engine._uniformBuffers.splice(index, 1);
  29829. }
  29830. if (!this._buffer) {
  29831. return;
  29832. }
  29833. if (this._engine._releaseBuffer(this._buffer)) {
  29834. this._buffer = null;
  29835. }
  29836. };
  29837. // Pool for avoiding memory leaks
  29838. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29839. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29840. return UniformBuffer;
  29841. }());
  29842. BABYLON.UniformBuffer = UniformBuffer;
  29843. })(BABYLON || (BABYLON = {}));
  29844. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29845. var BABYLON;
  29846. (function (BABYLON) {
  29847. var VertexData = /** @class */ (function () {
  29848. function VertexData() {
  29849. }
  29850. VertexData.prototype.set = function (data, kind) {
  29851. switch (kind) {
  29852. case BABYLON.VertexBuffer.PositionKind:
  29853. this.positions = data;
  29854. break;
  29855. case BABYLON.VertexBuffer.NormalKind:
  29856. this.normals = data;
  29857. break;
  29858. case BABYLON.VertexBuffer.TangentKind:
  29859. this.tangents = data;
  29860. break;
  29861. case BABYLON.VertexBuffer.UVKind:
  29862. this.uvs = data;
  29863. break;
  29864. case BABYLON.VertexBuffer.UV2Kind:
  29865. this.uvs2 = data;
  29866. break;
  29867. case BABYLON.VertexBuffer.UV3Kind:
  29868. this.uvs3 = data;
  29869. break;
  29870. case BABYLON.VertexBuffer.UV4Kind:
  29871. this.uvs4 = data;
  29872. break;
  29873. case BABYLON.VertexBuffer.UV5Kind:
  29874. this.uvs5 = data;
  29875. break;
  29876. case BABYLON.VertexBuffer.UV6Kind:
  29877. this.uvs6 = data;
  29878. break;
  29879. case BABYLON.VertexBuffer.ColorKind:
  29880. this.colors = data;
  29881. break;
  29882. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29883. this.matricesIndices = data;
  29884. break;
  29885. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29886. this.matricesWeights = data;
  29887. break;
  29888. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29889. this.matricesIndicesExtra = data;
  29890. break;
  29891. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29892. this.matricesWeightsExtra = data;
  29893. break;
  29894. }
  29895. };
  29896. /**
  29897. * Associates the vertexData to the passed Mesh.
  29898. * Sets it as updatable or not (default `false`).
  29899. * Returns the VertexData.
  29900. */
  29901. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29902. this._applyTo(mesh, updatable);
  29903. return this;
  29904. };
  29905. /**
  29906. * Associates the vertexData to the passed Geometry.
  29907. * Sets it as updatable or not (default `false`).
  29908. * Returns the VertexData.
  29909. */
  29910. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29911. this._applyTo(geometry, updatable);
  29912. return this;
  29913. };
  29914. /**
  29915. * Updates the associated mesh.
  29916. * Returns the VertexData.
  29917. */
  29918. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29919. this._update(mesh);
  29920. return this;
  29921. };
  29922. /**
  29923. * Updates the associated geometry.
  29924. * Returns the VertexData.
  29925. */
  29926. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29927. this._update(geometry);
  29928. return this;
  29929. };
  29930. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29931. if (updatable === void 0) { updatable = false; }
  29932. if (this.positions) {
  29933. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29934. }
  29935. if (this.normals) {
  29936. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29937. }
  29938. if (this.tangents) {
  29939. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29940. }
  29941. if (this.uvs) {
  29942. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29943. }
  29944. if (this.uvs2) {
  29945. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29946. }
  29947. if (this.uvs3) {
  29948. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29949. }
  29950. if (this.uvs4) {
  29951. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29952. }
  29953. if (this.uvs5) {
  29954. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29955. }
  29956. if (this.uvs6) {
  29957. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29958. }
  29959. if (this.colors) {
  29960. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29961. }
  29962. if (this.matricesIndices) {
  29963. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29964. }
  29965. if (this.matricesWeights) {
  29966. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29967. }
  29968. if (this.matricesIndicesExtra) {
  29969. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29970. }
  29971. if (this.matricesWeightsExtra) {
  29972. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29973. }
  29974. if (this.indices) {
  29975. meshOrGeometry.setIndices(this.indices, null, updatable);
  29976. }
  29977. return this;
  29978. };
  29979. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29980. if (this.positions) {
  29981. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29982. }
  29983. if (this.normals) {
  29984. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29985. }
  29986. if (this.tangents) {
  29987. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29988. }
  29989. if (this.uvs) {
  29990. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29991. }
  29992. if (this.uvs2) {
  29993. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29994. }
  29995. if (this.uvs3) {
  29996. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29997. }
  29998. if (this.uvs4) {
  29999. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30000. }
  30001. if (this.uvs5) {
  30002. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30003. }
  30004. if (this.uvs6) {
  30005. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30006. }
  30007. if (this.colors) {
  30008. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30009. }
  30010. if (this.matricesIndices) {
  30011. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30012. }
  30013. if (this.matricesWeights) {
  30014. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30015. }
  30016. if (this.matricesIndicesExtra) {
  30017. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30018. }
  30019. if (this.matricesWeightsExtra) {
  30020. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30021. }
  30022. if (this.indices) {
  30023. meshOrGeometry.setIndices(this.indices, null);
  30024. }
  30025. return this;
  30026. };
  30027. /**
  30028. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30029. * Returns the VertexData.
  30030. */
  30031. VertexData.prototype.transform = function (matrix) {
  30032. var transformed = BABYLON.Vector3.Zero();
  30033. var index;
  30034. if (this.positions) {
  30035. var position = BABYLON.Vector3.Zero();
  30036. for (index = 0; index < this.positions.length; index += 3) {
  30037. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30038. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30039. this.positions[index] = transformed.x;
  30040. this.positions[index + 1] = transformed.y;
  30041. this.positions[index + 2] = transformed.z;
  30042. }
  30043. }
  30044. if (this.normals) {
  30045. var normal = BABYLON.Vector3.Zero();
  30046. for (index = 0; index < this.normals.length; index += 3) {
  30047. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30048. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30049. this.normals[index] = transformed.x;
  30050. this.normals[index + 1] = transformed.y;
  30051. this.normals[index + 2] = transformed.z;
  30052. }
  30053. }
  30054. if (this.tangents) {
  30055. var tangent = BABYLON.Vector4.Zero();
  30056. var tangentTransformed = BABYLON.Vector4.Zero();
  30057. for (index = 0; index < this.tangents.length; index += 4) {
  30058. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30059. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30060. this.tangents[index] = tangentTransformed.x;
  30061. this.tangents[index + 1] = tangentTransformed.y;
  30062. this.tangents[index + 2] = tangentTransformed.z;
  30063. this.tangents[index + 3] = tangentTransformed.w;
  30064. }
  30065. }
  30066. return this;
  30067. };
  30068. /**
  30069. * Merges the passed VertexData into the current one.
  30070. * Returns the modified VertexData.
  30071. */
  30072. VertexData.prototype.merge = function (other, options) {
  30073. options = options || {};
  30074. if (other.indices) {
  30075. if (!this.indices) {
  30076. this.indices = [];
  30077. }
  30078. var offset = this.positions ? this.positions.length / 3 : 0;
  30079. for (var index = 0; index < other.indices.length; index++) {
  30080. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30081. this.indices.push(other.indices[index] + offset);
  30082. }
  30083. }
  30084. this.positions = this._mergeElement(this.positions, other.positions);
  30085. if (!this.positions) {
  30086. return this;
  30087. }
  30088. var count = this.positions.length / 3;
  30089. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30090. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30091. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30092. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30093. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30094. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30095. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30096. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30097. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30098. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30099. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30100. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30101. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30102. return this;
  30103. };
  30104. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30105. if (length === void 0) { length = 0; }
  30106. if (defaultValue === void 0) { defaultValue = 0; }
  30107. if (!other && !source) {
  30108. return null;
  30109. }
  30110. if (!other) {
  30111. var padding = new Float32Array(source.length);
  30112. padding.fill(defaultValue);
  30113. return this._mergeElement(source, padding, length);
  30114. }
  30115. if (!source) {
  30116. if (length === 0 || length === other.length) {
  30117. return other;
  30118. }
  30119. var padding = new Float32Array(length - other.length);
  30120. padding.fill(defaultValue);
  30121. return this._mergeElement(padding, other, length);
  30122. }
  30123. var len = other.length + source.length;
  30124. var isSrcTypedArray = source instanceof Float32Array;
  30125. var isOthTypedArray = other instanceof Float32Array;
  30126. // use non-loop method when the source is Float32Array
  30127. if (isSrcTypedArray) {
  30128. var ret32 = new Float32Array(len);
  30129. ret32.set(source);
  30130. ret32.set(other, source.length);
  30131. return ret32;
  30132. // source is number[], when other is also use concat
  30133. }
  30134. else if (!isOthTypedArray) {
  30135. return source.concat(other);
  30136. // source is a number[], but other is a Float32Array, loop required
  30137. }
  30138. else {
  30139. var ret = source.slice(0); // copy source to a separate array
  30140. for (var i = 0, len = other.length; i < len; i++) {
  30141. ret.push(other[i]);
  30142. }
  30143. return ret;
  30144. }
  30145. };
  30146. /**
  30147. * Serializes the VertexData.
  30148. * Returns a serialized object.
  30149. */
  30150. VertexData.prototype.serialize = function () {
  30151. var serializationObject = this.serialize();
  30152. if (this.positions) {
  30153. serializationObject.positions = this.positions;
  30154. }
  30155. if (this.normals) {
  30156. serializationObject.normals = this.normals;
  30157. }
  30158. if (this.tangents) {
  30159. serializationObject.tangents = this.tangents;
  30160. }
  30161. if (this.uvs) {
  30162. serializationObject.uvs = this.uvs;
  30163. }
  30164. if (this.uvs2) {
  30165. serializationObject.uvs2 = this.uvs2;
  30166. }
  30167. if (this.uvs3) {
  30168. serializationObject.uvs3 = this.uvs3;
  30169. }
  30170. if (this.uvs4) {
  30171. serializationObject.uvs4 = this.uvs4;
  30172. }
  30173. if (this.uvs5) {
  30174. serializationObject.uvs5 = this.uvs5;
  30175. }
  30176. if (this.uvs6) {
  30177. serializationObject.uvs6 = this.uvs6;
  30178. }
  30179. if (this.colors) {
  30180. serializationObject.colors = this.colors;
  30181. }
  30182. if (this.matricesIndices) {
  30183. serializationObject.matricesIndices = this.matricesIndices;
  30184. serializationObject.matricesIndices._isExpanded = true;
  30185. }
  30186. if (this.matricesWeights) {
  30187. serializationObject.matricesWeights = this.matricesWeights;
  30188. }
  30189. if (this.matricesIndicesExtra) {
  30190. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30191. serializationObject.matricesIndicesExtra._isExpanded = true;
  30192. }
  30193. if (this.matricesWeightsExtra) {
  30194. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30195. }
  30196. serializationObject.indices = this.indices;
  30197. return serializationObject;
  30198. };
  30199. // Statics
  30200. /**
  30201. * Returns the object VertexData associated to the passed mesh.
  30202. */
  30203. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30204. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30205. };
  30206. /**
  30207. * Returns the object VertexData associated to the passed geometry.
  30208. */
  30209. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30210. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30211. };
  30212. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30213. var result = new VertexData();
  30214. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30215. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30216. }
  30217. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30218. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30219. }
  30220. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30221. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30222. }
  30223. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30224. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30225. }
  30226. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30227. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30228. }
  30229. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30230. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30231. }
  30232. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30233. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30234. }
  30235. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30236. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30237. }
  30238. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30239. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30240. }
  30241. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30242. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30243. }
  30244. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30245. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30246. }
  30247. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30248. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30249. }
  30250. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30251. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30252. }
  30253. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30254. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30255. }
  30256. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30257. return result;
  30258. };
  30259. /**
  30260. * Creates the vertexData of the Ribbon.
  30261. */
  30262. VertexData.CreateRibbon = function (options) {
  30263. var pathArray = options.pathArray;
  30264. var closeArray = options.closeArray || false;
  30265. var closePath = options.closePath || false;
  30266. var invertUV = options.invertUV || false;
  30267. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30268. var offset = options.offset || defaultOffset;
  30269. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30270. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30271. var customUV = options.uvs;
  30272. var customColors = options.colors;
  30273. var positions = [];
  30274. var indices = [];
  30275. var normals = [];
  30276. var uvs = [];
  30277. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30278. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30279. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30280. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30281. var minlg; // minimal length among all paths from pathArray
  30282. var lg = []; // array of path lengths : nb of vertex per path
  30283. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30284. var p; // path iterator
  30285. var i; // point iterator
  30286. var j; // point iterator
  30287. // if single path in pathArray
  30288. if (pathArray.length < 2) {
  30289. var ar1 = [];
  30290. var ar2 = [];
  30291. for (i = 0; i < pathArray[0].length - offset; i++) {
  30292. ar1.push(pathArray[0][i]);
  30293. ar2.push(pathArray[0][i + offset]);
  30294. }
  30295. pathArray = [ar1, ar2];
  30296. }
  30297. // positions and horizontal distances (u)
  30298. var idc = 0;
  30299. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30300. var path;
  30301. var l;
  30302. minlg = pathArray[0].length;
  30303. var vectlg;
  30304. var dist;
  30305. for (p = 0; p < pathArray.length; p++) {
  30306. uTotalDistance[p] = 0;
  30307. us[p] = [0];
  30308. path = pathArray[p];
  30309. l = path.length;
  30310. minlg = (minlg < l) ? minlg : l;
  30311. j = 0;
  30312. while (j < l) {
  30313. positions.push(path[j].x, path[j].y, path[j].z);
  30314. if (j > 0) {
  30315. vectlg = path[j].subtract(path[j - 1]).length();
  30316. dist = vectlg + uTotalDistance[p];
  30317. us[p].push(dist);
  30318. uTotalDistance[p] = dist;
  30319. }
  30320. j++;
  30321. }
  30322. if (closePath) {
  30323. j--;
  30324. positions.push(path[0].x, path[0].y, path[0].z);
  30325. vectlg = path[j].subtract(path[0]).length();
  30326. dist = vectlg + uTotalDistance[p];
  30327. us[p].push(dist);
  30328. uTotalDistance[p] = dist;
  30329. }
  30330. lg[p] = l + closePathCorr;
  30331. idx[p] = idc;
  30332. idc += (l + closePathCorr);
  30333. }
  30334. // vertical distances (v)
  30335. var path1;
  30336. var path2;
  30337. var vertex1 = null;
  30338. var vertex2 = null;
  30339. for (i = 0; i < minlg + closePathCorr; i++) {
  30340. vTotalDistance[i] = 0;
  30341. vs[i] = [0];
  30342. for (p = 0; p < pathArray.length - 1; p++) {
  30343. path1 = pathArray[p];
  30344. path2 = pathArray[p + 1];
  30345. if (i === minlg) {
  30346. vertex1 = path1[0];
  30347. vertex2 = path2[0];
  30348. }
  30349. else {
  30350. vertex1 = path1[i];
  30351. vertex2 = path2[i];
  30352. }
  30353. vectlg = vertex2.subtract(vertex1).length();
  30354. dist = vectlg + vTotalDistance[i];
  30355. vs[i].push(dist);
  30356. vTotalDistance[i] = dist;
  30357. }
  30358. if (closeArray && vertex2 && vertex1) {
  30359. path1 = pathArray[p];
  30360. path2 = pathArray[0];
  30361. if (i === minlg) {
  30362. vertex2 = path2[0];
  30363. }
  30364. vectlg = vertex2.subtract(vertex1).length();
  30365. dist = vectlg + vTotalDistance[i];
  30366. vTotalDistance[i] = dist;
  30367. }
  30368. }
  30369. // uvs
  30370. var u;
  30371. var v;
  30372. if (customUV) {
  30373. for (p = 0; p < customUV.length; p++) {
  30374. uvs.push(customUV[p].x, customUV[p].y);
  30375. }
  30376. }
  30377. else {
  30378. for (p = 0; p < pathArray.length; p++) {
  30379. for (i = 0; i < minlg + closePathCorr; i++) {
  30380. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30381. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30382. if (invertUV) {
  30383. uvs.push(v, u);
  30384. }
  30385. else {
  30386. uvs.push(u, v);
  30387. }
  30388. }
  30389. }
  30390. }
  30391. // indices
  30392. p = 0; // path index
  30393. var pi = 0; // positions array index
  30394. var l1 = lg[p] - 1; // path1 length
  30395. var l2 = lg[p + 1] - 1; // path2 length
  30396. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30397. var shft = idx[1] - idx[0]; // shift
  30398. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30399. while (pi <= min && p < path1nb) {
  30400. // 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
  30401. indices.push(pi, pi + shft, pi + 1);
  30402. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30403. pi += 1;
  30404. if (pi === min) {
  30405. p++;
  30406. if (p === lg.length - 1) {
  30407. shft = idx[0] - idx[p];
  30408. l1 = lg[p] - 1;
  30409. l2 = lg[0] - 1;
  30410. }
  30411. else {
  30412. shft = idx[p + 1] - idx[p];
  30413. l1 = lg[p] - 1;
  30414. l2 = lg[p + 1] - 1;
  30415. }
  30416. pi = idx[p];
  30417. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30418. }
  30419. }
  30420. // normals
  30421. VertexData.ComputeNormals(positions, indices, normals);
  30422. if (closePath) {
  30423. var indexFirst = 0;
  30424. var indexLast = 0;
  30425. for (p = 0; p < pathArray.length; p++) {
  30426. indexFirst = idx[p] * 3;
  30427. if (p + 1 < pathArray.length) {
  30428. indexLast = (idx[p + 1] - 1) * 3;
  30429. }
  30430. else {
  30431. indexLast = normals.length - 3;
  30432. }
  30433. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30434. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30435. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30436. normals[indexLast] = normals[indexFirst];
  30437. normals[indexLast + 1] = normals[indexFirst + 1];
  30438. normals[indexLast + 2] = normals[indexFirst + 2];
  30439. }
  30440. }
  30441. // sides
  30442. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30443. // Colors
  30444. var colors = null;
  30445. if (customColors) {
  30446. colors = new Float32Array(customColors.length * 4);
  30447. for (var c = 0; c < customColors.length; c++) {
  30448. colors[c * 4] = customColors[c].r;
  30449. colors[c * 4 + 1] = customColors[c].g;
  30450. colors[c * 4 + 2] = customColors[c].b;
  30451. colors[c * 4 + 3] = customColors[c].a;
  30452. }
  30453. }
  30454. // Result
  30455. var vertexData = new VertexData();
  30456. var positions32 = new Float32Array(positions);
  30457. var normals32 = new Float32Array(normals);
  30458. var uvs32 = new Float32Array(uvs);
  30459. vertexData.indices = indices;
  30460. vertexData.positions = positions32;
  30461. vertexData.normals = normals32;
  30462. vertexData.uvs = uvs32;
  30463. if (colors) {
  30464. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30465. }
  30466. if (closePath) {
  30467. vertexData._idx = idx;
  30468. }
  30469. return vertexData;
  30470. };
  30471. /**
  30472. * Creates the VertexData of the Box.
  30473. */
  30474. VertexData.CreateBox = function (options) {
  30475. var normalsSource = [
  30476. new BABYLON.Vector3(0, 0, 1),
  30477. new BABYLON.Vector3(0, 0, -1),
  30478. new BABYLON.Vector3(1, 0, 0),
  30479. new BABYLON.Vector3(-1, 0, 0),
  30480. new BABYLON.Vector3(0, 1, 0),
  30481. new BABYLON.Vector3(0, -1, 0)
  30482. ];
  30483. var indices = [];
  30484. var positions = [];
  30485. var normals = [];
  30486. var uvs = [];
  30487. var width = options.width || options.size || 1;
  30488. var height = options.height || options.size || 1;
  30489. var depth = options.depth || options.size || 1;
  30490. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30491. var faceUV = options.faceUV || new Array(6);
  30492. var faceColors = options.faceColors;
  30493. var colors = [];
  30494. // default face colors and UV if undefined
  30495. for (var f = 0; f < 6; f++) {
  30496. if (faceUV[f] === undefined) {
  30497. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30498. }
  30499. if (faceColors && faceColors[f] === undefined) {
  30500. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30501. }
  30502. }
  30503. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30504. // Create each face in turn.
  30505. for (var index = 0; index < normalsSource.length; index++) {
  30506. var normal = normalsSource[index];
  30507. // Get two vectors perpendicular to the face normal and to each other.
  30508. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30509. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30510. // Six indices (two triangles) per face.
  30511. var verticesLength = positions.length / 3;
  30512. indices.push(verticesLength);
  30513. indices.push(verticesLength + 1);
  30514. indices.push(verticesLength + 2);
  30515. indices.push(verticesLength);
  30516. indices.push(verticesLength + 2);
  30517. indices.push(verticesLength + 3);
  30518. // Four vertices per face.
  30519. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30520. positions.push(vertex.x, vertex.y, vertex.z);
  30521. normals.push(normal.x, normal.y, normal.z);
  30522. uvs.push(faceUV[index].z, faceUV[index].w);
  30523. if (faceColors) {
  30524. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30525. }
  30526. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30527. positions.push(vertex.x, vertex.y, vertex.z);
  30528. normals.push(normal.x, normal.y, normal.z);
  30529. uvs.push(faceUV[index].x, faceUV[index].w);
  30530. if (faceColors) {
  30531. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30532. }
  30533. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30534. positions.push(vertex.x, vertex.y, vertex.z);
  30535. normals.push(normal.x, normal.y, normal.z);
  30536. uvs.push(faceUV[index].x, faceUV[index].y);
  30537. if (faceColors) {
  30538. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30539. }
  30540. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30541. positions.push(vertex.x, vertex.y, vertex.z);
  30542. normals.push(normal.x, normal.y, normal.z);
  30543. uvs.push(faceUV[index].z, faceUV[index].y);
  30544. if (faceColors) {
  30545. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30546. }
  30547. }
  30548. // sides
  30549. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30550. // Result
  30551. var vertexData = new VertexData();
  30552. vertexData.indices = indices;
  30553. vertexData.positions = positions;
  30554. vertexData.normals = normals;
  30555. vertexData.uvs = uvs;
  30556. if (faceColors) {
  30557. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30558. vertexData.colors = totalColors;
  30559. }
  30560. return vertexData;
  30561. };
  30562. /**
  30563. * Creates the VertexData of the Sphere.
  30564. */
  30565. VertexData.CreateSphere = function (options) {
  30566. var segments = options.segments || 32;
  30567. var diameterX = options.diameterX || options.diameter || 1;
  30568. var diameterY = options.diameterY || options.diameter || 1;
  30569. var diameterZ = options.diameterZ || options.diameter || 1;
  30570. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30571. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30572. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30573. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30574. var totalZRotationSteps = 2 + segments;
  30575. var totalYRotationSteps = 2 * totalZRotationSteps;
  30576. var indices = [];
  30577. var positions = [];
  30578. var normals = [];
  30579. var uvs = [];
  30580. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30581. var normalizedZ = zRotationStep / totalZRotationSteps;
  30582. var angleZ = normalizedZ * Math.PI * slice;
  30583. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30584. var normalizedY = yRotationStep / totalYRotationSteps;
  30585. var angleY = normalizedY * Math.PI * 2 * arc;
  30586. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30587. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30588. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30589. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30590. var vertex = complete.multiply(radius);
  30591. var normal = complete.divide(radius).normalize();
  30592. positions.push(vertex.x, vertex.y, vertex.z);
  30593. normals.push(normal.x, normal.y, normal.z);
  30594. uvs.push(normalizedY, normalizedZ);
  30595. }
  30596. if (zRotationStep > 0) {
  30597. var verticesCount = positions.length / 3;
  30598. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30599. indices.push((firstIndex));
  30600. indices.push((firstIndex + 1));
  30601. indices.push(firstIndex + totalYRotationSteps + 1);
  30602. indices.push((firstIndex + totalYRotationSteps + 1));
  30603. indices.push((firstIndex + 1));
  30604. indices.push((firstIndex + totalYRotationSteps + 2));
  30605. }
  30606. }
  30607. }
  30608. // Sides
  30609. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30610. // Result
  30611. var vertexData = new VertexData();
  30612. vertexData.indices = indices;
  30613. vertexData.positions = positions;
  30614. vertexData.normals = normals;
  30615. vertexData.uvs = uvs;
  30616. return vertexData;
  30617. };
  30618. /**
  30619. * Creates the VertexData of the Cylinder or Cone.
  30620. */
  30621. VertexData.CreateCylinder = function (options) {
  30622. var height = options.height || 2;
  30623. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30624. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30625. var tessellation = options.tessellation || 24;
  30626. var subdivisions = options.subdivisions || 1;
  30627. var hasRings = options.hasRings ? true : false;
  30628. var enclose = options.enclose ? true : false;
  30629. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30630. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30631. var faceUV = options.faceUV || new Array(3);
  30632. var faceColors = options.faceColors;
  30633. // default face colors and UV if undefined
  30634. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30635. var ringNb = (hasRings) ? subdivisions : 1;
  30636. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30637. var f;
  30638. for (f = 0; f < surfaceNb; f++) {
  30639. if (faceColors && faceColors[f] === undefined) {
  30640. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30641. }
  30642. }
  30643. for (f = 0; f < surfaceNb; f++) {
  30644. if (faceUV && faceUV[f] === undefined) {
  30645. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30646. }
  30647. }
  30648. var indices = new Array();
  30649. var positions = new Array();
  30650. var normals = new Array();
  30651. var uvs = new Array();
  30652. var colors = new Array();
  30653. var angle_step = Math.PI * 2 * arc / tessellation;
  30654. var angle;
  30655. var h;
  30656. var radius;
  30657. var tan = (diameterBottom - diameterTop) / 2 / height;
  30658. var ringVertex = BABYLON.Vector3.Zero();
  30659. var ringNormal = BABYLON.Vector3.Zero();
  30660. var ringFirstVertex = BABYLON.Vector3.Zero();
  30661. var ringFirstNormal = BABYLON.Vector3.Zero();
  30662. var quadNormal = BABYLON.Vector3.Zero();
  30663. var Y = BABYLON.Axis.Y;
  30664. // positions, normals, uvs
  30665. var i;
  30666. var j;
  30667. var r;
  30668. var ringIdx = 1;
  30669. var s = 1; // surface index
  30670. var cs = 0;
  30671. var v = 0;
  30672. for (i = 0; i <= subdivisions; i++) {
  30673. h = i / subdivisions;
  30674. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30675. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30676. for (r = 0; r < ringIdx; r++) {
  30677. if (hasRings) {
  30678. s += r;
  30679. }
  30680. if (enclose) {
  30681. s += 2 * r;
  30682. }
  30683. for (j = 0; j <= tessellation; j++) {
  30684. angle = j * angle_step;
  30685. // position
  30686. ringVertex.x = Math.cos(-angle) * radius;
  30687. ringVertex.y = -height / 2 + h * height;
  30688. ringVertex.z = Math.sin(-angle) * radius;
  30689. // normal
  30690. if (diameterTop === 0 && i === subdivisions) {
  30691. // if no top cap, reuse former normals
  30692. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30693. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30694. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30695. }
  30696. else {
  30697. ringNormal.x = ringVertex.x;
  30698. ringNormal.z = ringVertex.z;
  30699. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30700. ringNormal.normalize();
  30701. }
  30702. // keep first ring vertex values for enclose
  30703. if (j === 0) {
  30704. ringFirstVertex.copyFrom(ringVertex);
  30705. ringFirstNormal.copyFrom(ringNormal);
  30706. }
  30707. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30708. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30709. if (hasRings) {
  30710. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30711. }
  30712. else {
  30713. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30714. }
  30715. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30716. if (faceColors) {
  30717. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30718. }
  30719. }
  30720. // if enclose, add four vertices and their dedicated normals
  30721. if (arc !== 1 && enclose) {
  30722. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30723. positions.push(0, ringVertex.y, 0);
  30724. positions.push(0, ringVertex.y, 0);
  30725. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30726. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30727. quadNormal.normalize();
  30728. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30729. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30730. quadNormal.normalize();
  30731. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30732. if (hasRings) {
  30733. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30734. }
  30735. else {
  30736. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30737. }
  30738. uvs.push(faceUV[s + 1].x, v);
  30739. uvs.push(faceUV[s + 1].z, v);
  30740. if (hasRings) {
  30741. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30742. }
  30743. else {
  30744. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30745. }
  30746. uvs.push(faceUV[s + 2].x, v);
  30747. uvs.push(faceUV[s + 2].z, v);
  30748. if (faceColors) {
  30749. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30750. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30751. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30752. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30753. }
  30754. }
  30755. if (cs !== s) {
  30756. cs = s;
  30757. }
  30758. }
  30759. }
  30760. // indices
  30761. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30762. var s;
  30763. i = 0;
  30764. for (s = 0; s < subdivisions; s++) {
  30765. var i0 = 0;
  30766. var i1 = 0;
  30767. var i2 = 0;
  30768. var i3 = 0;
  30769. for (j = 0; j < tessellation; j++) {
  30770. i0 = i * (e + 1) + j;
  30771. i1 = (i + 1) * (e + 1) + j;
  30772. i2 = i * (e + 1) + (j + 1);
  30773. i3 = (i + 1) * (e + 1) + (j + 1);
  30774. indices.push(i0, i1, i2);
  30775. indices.push(i3, i2, i1);
  30776. }
  30777. if (arc !== 1 && enclose) {
  30778. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30779. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30780. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30781. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30782. }
  30783. i = (hasRings) ? (i + 2) : (i + 1);
  30784. }
  30785. // Caps
  30786. var createCylinderCap = function (isTop) {
  30787. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30788. if (radius === 0) {
  30789. return;
  30790. }
  30791. // Cap positions, normals & uvs
  30792. var angle;
  30793. var circleVector;
  30794. var i;
  30795. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30796. var c = null;
  30797. if (faceColors) {
  30798. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30799. }
  30800. // cap center
  30801. var vbase = positions.length / 3;
  30802. var offset = isTop ? height / 2 : -height / 2;
  30803. var center = new BABYLON.Vector3(0, offset, 0);
  30804. positions.push(center.x, center.y, center.z);
  30805. normals.push(0, isTop ? 1 : -1, 0);
  30806. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30807. if (c) {
  30808. colors.push(c.r, c.g, c.b, c.a);
  30809. }
  30810. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30811. for (i = 0; i <= tessellation; i++) {
  30812. angle = Math.PI * 2 * i * arc / tessellation;
  30813. var cos = Math.cos(-angle);
  30814. var sin = Math.sin(-angle);
  30815. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30816. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30817. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30818. normals.push(0, isTop ? 1 : -1, 0);
  30819. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30820. if (c) {
  30821. colors.push(c.r, c.g, c.b, c.a);
  30822. }
  30823. }
  30824. // Cap indices
  30825. for (i = 0; i < tessellation; i++) {
  30826. if (!isTop) {
  30827. indices.push(vbase);
  30828. indices.push(vbase + (i + 1));
  30829. indices.push(vbase + (i + 2));
  30830. }
  30831. else {
  30832. indices.push(vbase);
  30833. indices.push(vbase + (i + 2));
  30834. indices.push(vbase + (i + 1));
  30835. }
  30836. }
  30837. };
  30838. // add caps to geometry
  30839. createCylinderCap(false);
  30840. createCylinderCap(true);
  30841. // Sides
  30842. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30843. var vertexData = new VertexData();
  30844. vertexData.indices = indices;
  30845. vertexData.positions = positions;
  30846. vertexData.normals = normals;
  30847. vertexData.uvs = uvs;
  30848. if (faceColors) {
  30849. vertexData.colors = colors;
  30850. }
  30851. return vertexData;
  30852. };
  30853. /**
  30854. * Creates the VertexData of the Torus.
  30855. */
  30856. VertexData.CreateTorus = function (options) {
  30857. var indices = [];
  30858. var positions = [];
  30859. var normals = [];
  30860. var uvs = [];
  30861. var diameter = options.diameter || 1;
  30862. var thickness = options.thickness || 0.5;
  30863. var tessellation = options.tessellation || 16;
  30864. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30865. var stride = tessellation + 1;
  30866. for (var i = 0; i <= tessellation; i++) {
  30867. var u = i / tessellation;
  30868. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30869. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30870. for (var j = 0; j <= tessellation; j++) {
  30871. var v = 1 - j / tessellation;
  30872. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30873. var dx = Math.cos(innerAngle);
  30874. var dy = Math.sin(innerAngle);
  30875. // Create a vertex.
  30876. var normal = new BABYLON.Vector3(dx, dy, 0);
  30877. var position = normal.scale(thickness / 2);
  30878. var textureCoordinate = new BABYLON.Vector2(u, v);
  30879. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30880. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30881. positions.push(position.x, position.y, position.z);
  30882. normals.push(normal.x, normal.y, normal.z);
  30883. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30884. // And create indices for two triangles.
  30885. var nextI = (i + 1) % stride;
  30886. var nextJ = (j + 1) % stride;
  30887. indices.push(i * stride + j);
  30888. indices.push(i * stride + nextJ);
  30889. indices.push(nextI * stride + j);
  30890. indices.push(i * stride + nextJ);
  30891. indices.push(nextI * stride + nextJ);
  30892. indices.push(nextI * stride + j);
  30893. }
  30894. }
  30895. // Sides
  30896. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30897. // Result
  30898. var vertexData = new VertexData();
  30899. vertexData.indices = indices;
  30900. vertexData.positions = positions;
  30901. vertexData.normals = normals;
  30902. vertexData.uvs = uvs;
  30903. return vertexData;
  30904. };
  30905. /**
  30906. * Creates the VertexData of the LineSystem.
  30907. */
  30908. VertexData.CreateLineSystem = function (options) {
  30909. var indices = [];
  30910. var positions = [];
  30911. var lines = options.lines;
  30912. var colors = options.colors;
  30913. var vertexColors = [];
  30914. var idx = 0;
  30915. for (var l = 0; l < lines.length; l++) {
  30916. var points = lines[l];
  30917. for (var index = 0; index < points.length; index++) {
  30918. positions.push(points[index].x, points[index].y, points[index].z);
  30919. if (colors) {
  30920. var color = colors[l];
  30921. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30922. }
  30923. if (index > 0) {
  30924. indices.push(idx - 1);
  30925. indices.push(idx);
  30926. }
  30927. idx++;
  30928. }
  30929. }
  30930. var vertexData = new VertexData();
  30931. vertexData.indices = indices;
  30932. vertexData.positions = positions;
  30933. if (colors) {
  30934. vertexData.colors = vertexColors;
  30935. }
  30936. return vertexData;
  30937. };
  30938. /**
  30939. * Create the VertexData of the DashedLines.
  30940. */
  30941. VertexData.CreateDashedLines = function (options) {
  30942. var dashSize = options.dashSize || 3;
  30943. var gapSize = options.gapSize || 1;
  30944. var dashNb = options.dashNb || 200;
  30945. var points = options.points;
  30946. var positions = new Array();
  30947. var indices = new Array();
  30948. var curvect = BABYLON.Vector3.Zero();
  30949. var lg = 0;
  30950. var nb = 0;
  30951. var shft = 0;
  30952. var dashshft = 0;
  30953. var curshft = 0;
  30954. var idx = 0;
  30955. var i = 0;
  30956. for (i = 0; i < points.length - 1; i++) {
  30957. points[i + 1].subtractToRef(points[i], curvect);
  30958. lg += curvect.length();
  30959. }
  30960. shft = lg / dashNb;
  30961. dashshft = dashSize * shft / (dashSize + gapSize);
  30962. for (i = 0; i < points.length - 1; i++) {
  30963. points[i + 1].subtractToRef(points[i], curvect);
  30964. nb = Math.floor(curvect.length() / shft);
  30965. curvect.normalize();
  30966. for (var j = 0; j < nb; j++) {
  30967. curshft = shft * j;
  30968. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30969. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30970. indices.push(idx, idx + 1);
  30971. idx += 2;
  30972. }
  30973. }
  30974. // Result
  30975. var vertexData = new VertexData();
  30976. vertexData.positions = positions;
  30977. vertexData.indices = indices;
  30978. return vertexData;
  30979. };
  30980. /**
  30981. * Creates the VertexData of the Ground.
  30982. */
  30983. VertexData.CreateGround = function (options) {
  30984. var indices = [];
  30985. var positions = [];
  30986. var normals = [];
  30987. var uvs = [];
  30988. var row, col;
  30989. var width = options.width || 1;
  30990. var height = options.height || 1;
  30991. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30992. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30993. for (row = 0; row <= subdivisionsY; row++) {
  30994. for (col = 0; col <= subdivisionsX; col++) {
  30995. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30996. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30997. positions.push(position.x, position.y, position.z);
  30998. normals.push(normal.x, normal.y, normal.z);
  30999. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31000. }
  31001. }
  31002. for (row = 0; row < subdivisionsY; row++) {
  31003. for (col = 0; col < subdivisionsX; col++) {
  31004. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31005. indices.push(col + 1 + row * (subdivisionsX + 1));
  31006. indices.push(col + row * (subdivisionsX + 1));
  31007. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31008. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31009. indices.push(col + row * (subdivisionsX + 1));
  31010. }
  31011. }
  31012. // Result
  31013. var vertexData = new VertexData();
  31014. vertexData.indices = indices;
  31015. vertexData.positions = positions;
  31016. vertexData.normals = normals;
  31017. vertexData.uvs = uvs;
  31018. return vertexData;
  31019. };
  31020. /**
  31021. * Creates the VertexData of the TiledGround.
  31022. */
  31023. VertexData.CreateTiledGround = function (options) {
  31024. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31025. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31026. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31027. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31028. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31029. var precision = options.precision || { w: 1, h: 1 };
  31030. var indices = new Array();
  31031. var positions = new Array();
  31032. var normals = new Array();
  31033. var uvs = new Array();
  31034. var row, col, tileRow, tileCol;
  31035. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31036. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31037. precision.w = (precision.w < 1) ? 1 : precision.w;
  31038. precision.h = (precision.h < 1) ? 1 : precision.h;
  31039. var tileSize = {
  31040. 'w': (xmax - xmin) / subdivisions.w,
  31041. 'h': (zmax - zmin) / subdivisions.h
  31042. };
  31043. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31044. // Indices
  31045. var base = positions.length / 3;
  31046. var rowLength = precision.w + 1;
  31047. for (row = 0; row < precision.h; row++) {
  31048. for (col = 0; col < precision.w; col++) {
  31049. var square = [
  31050. base + col + row * rowLength,
  31051. base + (col + 1) + row * rowLength,
  31052. base + (col + 1) + (row + 1) * rowLength,
  31053. base + col + (row + 1) * rowLength
  31054. ];
  31055. indices.push(square[1]);
  31056. indices.push(square[2]);
  31057. indices.push(square[3]);
  31058. indices.push(square[0]);
  31059. indices.push(square[1]);
  31060. indices.push(square[3]);
  31061. }
  31062. }
  31063. // Position, normals and uvs
  31064. var position = BABYLON.Vector3.Zero();
  31065. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31066. for (row = 0; row <= precision.h; row++) {
  31067. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31068. for (col = 0; col <= precision.w; col++) {
  31069. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31070. position.y = 0;
  31071. positions.push(position.x, position.y, position.z);
  31072. normals.push(normal.x, normal.y, normal.z);
  31073. uvs.push(col / precision.w, row / precision.h);
  31074. }
  31075. }
  31076. }
  31077. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31078. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31079. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31080. }
  31081. }
  31082. // Result
  31083. var vertexData = new VertexData();
  31084. vertexData.indices = indices;
  31085. vertexData.positions = positions;
  31086. vertexData.normals = normals;
  31087. vertexData.uvs = uvs;
  31088. return vertexData;
  31089. };
  31090. /**
  31091. * Creates the VertexData of the Ground designed from a heightmap.
  31092. */
  31093. VertexData.CreateGroundFromHeightMap = function (options) {
  31094. var indices = [];
  31095. var positions = [];
  31096. var normals = [];
  31097. var uvs = [];
  31098. var row, col;
  31099. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31100. // Vertices
  31101. for (row = 0; row <= options.subdivisions; row++) {
  31102. for (col = 0; col <= options.subdivisions; col++) {
  31103. 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));
  31104. // Compute height
  31105. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31106. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31107. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31108. var r = options.buffer[pos] / 255.0;
  31109. var g = options.buffer[pos + 1] / 255.0;
  31110. var b = options.buffer[pos + 2] / 255.0;
  31111. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31112. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31113. // Add vertex
  31114. positions.push(position.x, position.y, position.z);
  31115. normals.push(0, 0, 0);
  31116. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31117. }
  31118. }
  31119. // Indices
  31120. for (row = 0; row < options.subdivisions; row++) {
  31121. for (col = 0; col < options.subdivisions; col++) {
  31122. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31123. indices.push(col + 1 + row * (options.subdivisions + 1));
  31124. indices.push(col + row * (options.subdivisions + 1));
  31125. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31126. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31127. indices.push(col + row * (options.subdivisions + 1));
  31128. }
  31129. }
  31130. // Normals
  31131. VertexData.ComputeNormals(positions, indices, normals);
  31132. // Result
  31133. var vertexData = new VertexData();
  31134. vertexData.indices = indices;
  31135. vertexData.positions = positions;
  31136. vertexData.normals = normals;
  31137. vertexData.uvs = uvs;
  31138. return vertexData;
  31139. };
  31140. /**
  31141. * Creates the VertexData of the Plane.
  31142. */
  31143. VertexData.CreatePlane = function (options) {
  31144. var indices = [];
  31145. var positions = [];
  31146. var normals = [];
  31147. var uvs = [];
  31148. var width = options.width || options.size || 1;
  31149. var height = options.height || options.size || 1;
  31150. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31151. // Vertices
  31152. var halfWidth = width / 2.0;
  31153. var halfHeight = height / 2.0;
  31154. positions.push(-halfWidth, -halfHeight, 0);
  31155. normals.push(0, 0, -1.0);
  31156. uvs.push(0.0, 0.0);
  31157. positions.push(halfWidth, -halfHeight, 0);
  31158. normals.push(0, 0, -1.0);
  31159. uvs.push(1.0, 0.0);
  31160. positions.push(halfWidth, halfHeight, 0);
  31161. normals.push(0, 0, -1.0);
  31162. uvs.push(1.0, 1.0);
  31163. positions.push(-halfWidth, halfHeight, 0);
  31164. normals.push(0, 0, -1.0);
  31165. uvs.push(0.0, 1.0);
  31166. // Indices
  31167. indices.push(0);
  31168. indices.push(1);
  31169. indices.push(2);
  31170. indices.push(0);
  31171. indices.push(2);
  31172. indices.push(3);
  31173. // Sides
  31174. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31175. // Result
  31176. var vertexData = new VertexData();
  31177. vertexData.indices = indices;
  31178. vertexData.positions = positions;
  31179. vertexData.normals = normals;
  31180. vertexData.uvs = uvs;
  31181. return vertexData;
  31182. };
  31183. /**
  31184. * Creates the VertexData of the Disc or regular Polygon.
  31185. */
  31186. VertexData.CreateDisc = function (options) {
  31187. var positions = new Array();
  31188. var indices = new Array();
  31189. var normals = new Array();
  31190. var uvs = new Array();
  31191. var radius = options.radius || 0.5;
  31192. var tessellation = options.tessellation || 64;
  31193. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31194. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31195. // positions and uvs
  31196. positions.push(0, 0, 0); // disc center first
  31197. uvs.push(0.5, 0.5);
  31198. var theta = Math.PI * 2 * arc;
  31199. var step = theta / tessellation;
  31200. for (var a = 0; a < theta; a += step) {
  31201. var x = Math.cos(a);
  31202. var y = Math.sin(a);
  31203. var u = (x + 1) / 2;
  31204. var v = (1 - y) / 2;
  31205. positions.push(radius * x, radius * y, 0);
  31206. uvs.push(u, v);
  31207. }
  31208. if (arc === 1) {
  31209. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31210. uvs.push(uvs[2], uvs[3]);
  31211. }
  31212. //indices
  31213. var vertexNb = positions.length / 3;
  31214. for (var i = 1; i < vertexNb - 1; i++) {
  31215. indices.push(i + 1, 0, i);
  31216. }
  31217. // result
  31218. VertexData.ComputeNormals(positions, indices, normals);
  31219. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31220. var vertexData = new VertexData();
  31221. vertexData.indices = indices;
  31222. vertexData.positions = positions;
  31223. vertexData.normals = normals;
  31224. vertexData.uvs = uvs;
  31225. return vertexData;
  31226. };
  31227. /**
  31228. * Re-creates the VertexData of the Polygon for sideOrientation.
  31229. */
  31230. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31231. var faceUV = fUV || new Array(3);
  31232. var faceColors = fColors;
  31233. var colors = [];
  31234. // default face colors and UV if undefined
  31235. for (var f = 0; f < 3; f++) {
  31236. if (faceUV[f] === undefined) {
  31237. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31238. }
  31239. if (faceColors && faceColors[f] === undefined) {
  31240. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31241. }
  31242. }
  31243. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31244. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31245. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31246. var indices = polygon.getIndices();
  31247. // set face colours and textures
  31248. var idx = 0;
  31249. var face = 0;
  31250. for (var index = 0; index < normals.length; index += 3) {
  31251. //Edge Face no. 1
  31252. if (Math.abs(normals[index + 1]) < 0.001) {
  31253. face = 1;
  31254. }
  31255. //Top Face no. 0
  31256. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31257. face = 0;
  31258. }
  31259. //Bottom Face no. 2
  31260. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31261. face = 2;
  31262. }
  31263. idx = index / 3;
  31264. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31265. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31266. if (faceColors) {
  31267. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31268. }
  31269. }
  31270. // sides
  31271. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31272. // Result
  31273. var vertexData = new VertexData();
  31274. vertexData.indices = indices;
  31275. vertexData.positions = positions;
  31276. vertexData.normals = normals;
  31277. vertexData.uvs = uvs;
  31278. if (faceColors) {
  31279. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31280. vertexData.colors = totalColors;
  31281. }
  31282. return vertexData;
  31283. };
  31284. /**
  31285. * Creates the VertexData of the IcoSphere.
  31286. */
  31287. VertexData.CreateIcoSphere = function (options) {
  31288. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31289. var radius = options.radius || 1;
  31290. var flat = (options.flat === undefined) ? true : options.flat;
  31291. var subdivisions = options.subdivisions || 4;
  31292. var radiusX = options.radiusX || radius;
  31293. var radiusY = options.radiusY || radius;
  31294. var radiusZ = options.radiusZ || radius;
  31295. var t = (1 + Math.sqrt(5)) / 2;
  31296. // 12 vertex x,y,z
  31297. var ico_vertices = [
  31298. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31299. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31300. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31301. ];
  31302. // index of 3 vertex makes a face of icopshere
  31303. var ico_indices = [
  31304. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31305. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31306. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31307. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31308. ];
  31309. // vertex for uv have aliased position, not for UV
  31310. var vertices_unalias_id = [
  31311. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31312. // vertex alias
  31313. 0,
  31314. 2,
  31315. 3,
  31316. 3,
  31317. 3,
  31318. 4,
  31319. 7,
  31320. 8,
  31321. 9,
  31322. 9,
  31323. 10,
  31324. 11 // 23: B + 12
  31325. ];
  31326. // uv as integer step (not pixels !)
  31327. var ico_vertexuv = [
  31328. 5, 1, 3, 1, 6, 4, 0, 0,
  31329. 5, 3, 4, 2, 2, 2, 4, 0,
  31330. 2, 0, 1, 1, 6, 0, 6, 2,
  31331. // vertex alias (for same vertex on different faces)
  31332. 0, 4,
  31333. 3, 3,
  31334. 4, 4,
  31335. 3, 1,
  31336. 4, 2,
  31337. 4, 4,
  31338. 0, 2,
  31339. 1, 1,
  31340. 2, 2,
  31341. 3, 3,
  31342. 1, 3,
  31343. 2, 4 // 23: B + 12
  31344. ];
  31345. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31346. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31347. // First island of uv mapping
  31348. // v = 4h 3+ 2
  31349. // v = 3h 9+ 4
  31350. // v = 2h 9+ 5 B
  31351. // v = 1h 9 1 0
  31352. // v = 0h 3 8 7 A
  31353. // u = 0 1 2 3 4 5 6 *a
  31354. // Second island of uv mapping
  31355. // v = 4h 0+ B+ 4+
  31356. // v = 3h A+ 2+
  31357. // v = 2h 7+ 6 3+
  31358. // v = 1h 8+ 3+
  31359. // v = 0h
  31360. // u = 0 1 2 3 4 5 6 *a
  31361. // Face layout on texture UV mapping
  31362. // ============
  31363. // \ 4 /\ 16 / ======
  31364. // \ / \ / /\ 11 /
  31365. // \/ 7 \/ / \ /
  31366. // ======= / 10 \/
  31367. // /\ 17 /\ =======
  31368. // / \ / \ \ 15 /\
  31369. // / 8 \/ 12 \ \ / \
  31370. // ============ \/ 6 \
  31371. // \ 18 /\ ============
  31372. // \ / \ \ 5 /\ 0 /
  31373. // \/ 13 \ \ / \ /
  31374. // ======= \/ 1 \/
  31375. // =============
  31376. // /\ 19 /\ 2 /\
  31377. // / \ / \ / \
  31378. // / 14 \/ 9 \/ 3 \
  31379. // ===================
  31380. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31381. var ustep = 138 / 1024;
  31382. var vstep = 239 / 1024;
  31383. var uoffset = 60 / 1024;
  31384. var voffset = 26 / 1024;
  31385. // Second island should have margin, not to touch the first island
  31386. // avoid any borderline artefact in pixel rounding
  31387. var island_u_offset = -40 / 1024;
  31388. var island_v_offset = +20 / 1024;
  31389. // face is either island 0 or 1 :
  31390. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31391. var island = [
  31392. 0, 0, 0, 0, 1,
  31393. 0, 0, 1, 1, 0,
  31394. 0, 0, 1, 1, 0,
  31395. 0, 1, 1, 1, 0 // 15 - 19
  31396. ];
  31397. var indices = new Array();
  31398. var positions = new Array();
  31399. var normals = new Array();
  31400. var uvs = new Array();
  31401. var current_indice = 0;
  31402. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31403. var face_vertex_pos = new Array(3);
  31404. var face_vertex_uv = new Array(3);
  31405. var v012;
  31406. for (v012 = 0; v012 < 3; v012++) {
  31407. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31408. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31409. }
  31410. // create all with normals
  31411. for (var face = 0; face < 20; face++) {
  31412. // 3 vertex per face
  31413. for (v012 = 0; v012 < 3; v012++) {
  31414. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31415. var v_id = ico_indices[3 * face + v012];
  31416. // vertex have 3D position (x,y,z)
  31417. 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]);
  31418. // Normalize to get normal, then scale to radius
  31419. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31420. // uv Coordinates from vertex ID
  31421. 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);
  31422. }
  31423. // Subdivide the face (interpolate pos, norm, uv)
  31424. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31425. // - norm is linear interpolation of vertex corner normal
  31426. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31427. // - uv is linear interpolation
  31428. //
  31429. // Topology is as below for sub-divide by 2
  31430. // vertex shown as v0,v1,v2
  31431. // interp index is i1 to progress in range [v0,v1[
  31432. // interp index is i2 to progress in range [v0,v2[
  31433. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31434. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31435. //
  31436. //
  31437. // i2 v2
  31438. // ^ ^
  31439. // / / \
  31440. // / / \
  31441. // / / \
  31442. // / / (0,1) \
  31443. // / #---------\
  31444. // / / \ (0,0)'/ \
  31445. // / / \ / \
  31446. // / / \ / \
  31447. // / / (0,0) \ / (1,0) \
  31448. // / #---------#---------\
  31449. // v0 v1
  31450. //
  31451. // --------------------> i1
  31452. //
  31453. // interp of (i1,i2):
  31454. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31455. // along i1 : lerp(x0,x1, i1/(S-i2))
  31456. //
  31457. // centroid of triangle is needed to get help normal computation
  31458. // (c1,c2) are used for centroid location
  31459. var interp_vertex = function (i1, i2, c1, c2) {
  31460. // vertex is interpolated from
  31461. // - face_vertex_pos[0..2]
  31462. // - face_vertex_uv[0..2]
  31463. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31464. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31465. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31466. pos_interp.normalize();
  31467. var vertex_normal;
  31468. if (flat) {
  31469. // in flat mode, recalculate normal as face centroid normal
  31470. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31471. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31472. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31473. }
  31474. else {
  31475. // in smooth mode, recalculate normal from each single vertex position
  31476. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31477. }
  31478. // Vertex normal need correction due to X,Y,Z radius scaling
  31479. vertex_normal.x /= radiusX;
  31480. vertex_normal.y /= radiusY;
  31481. vertex_normal.z /= radiusZ;
  31482. vertex_normal.normalize();
  31483. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31484. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31485. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31486. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31487. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31488. uvs.push(uv_interp.x, uv_interp.y);
  31489. // push each vertex has member of a face
  31490. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31491. indices.push(current_indice);
  31492. current_indice++;
  31493. };
  31494. for (var i2 = 0; i2 < subdivisions; i2++) {
  31495. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31496. // face : (i1,i2) for /\ :
  31497. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31498. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31499. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31500. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31501. if (i1 + i2 + 1 < subdivisions) {
  31502. // face : (i1,i2)' for \/ :
  31503. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31504. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31505. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31506. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31507. }
  31508. }
  31509. }
  31510. }
  31511. // Sides
  31512. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31513. // Result
  31514. var vertexData = new VertexData();
  31515. vertexData.indices = indices;
  31516. vertexData.positions = positions;
  31517. vertexData.normals = normals;
  31518. vertexData.uvs = uvs;
  31519. return vertexData;
  31520. };
  31521. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31522. /**
  31523. * Creates the VertexData of the Polyhedron.
  31524. */
  31525. VertexData.CreatePolyhedron = function (options) {
  31526. // provided polyhedron types :
  31527. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31528. // 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)
  31529. var polyhedra = [];
  31530. 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]] };
  31531. 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]] };
  31532. polyhedra[2] = {
  31533. 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]],
  31534. 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]]
  31535. };
  31536. polyhedra[3] = {
  31537. 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]],
  31538. 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]]
  31539. };
  31540. polyhedra[4] = {
  31541. 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]],
  31542. 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]]
  31543. };
  31544. 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]] };
  31545. 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]] };
  31546. 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]] };
  31547. 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]] };
  31548. 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]] };
  31549. 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]] };
  31550. 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]] };
  31551. 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]] };
  31552. 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]] };
  31553. polyhedra[14] = {
  31554. 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]],
  31555. 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]]
  31556. };
  31557. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31558. var size = options.size;
  31559. var sizeX = options.sizeX || size || 1;
  31560. var sizeY = options.sizeY || size || 1;
  31561. var sizeZ = options.sizeZ || size || 1;
  31562. var data = options.custom || polyhedra[type];
  31563. var nbfaces = data.face.length;
  31564. var faceUV = options.faceUV || new Array(nbfaces);
  31565. var faceColors = options.faceColors;
  31566. var flat = (options.flat === undefined) ? true : options.flat;
  31567. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31568. var positions = new Array();
  31569. var indices = new Array();
  31570. var normals = new Array();
  31571. var uvs = new Array();
  31572. var colors = new Array();
  31573. var index = 0;
  31574. var faceIdx = 0; // face cursor in the array "indexes"
  31575. var indexes = new Array();
  31576. var i = 0;
  31577. var f = 0;
  31578. var u, v, ang, x, y, tmp;
  31579. // default face colors and UV if undefined
  31580. if (flat) {
  31581. for (f = 0; f < nbfaces; f++) {
  31582. if (faceColors && faceColors[f] === undefined) {
  31583. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31584. }
  31585. if (faceUV && faceUV[f] === undefined) {
  31586. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31587. }
  31588. }
  31589. }
  31590. if (!flat) {
  31591. for (i = 0; i < data.vertex.length; i++) {
  31592. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31593. uvs.push(0, 0);
  31594. }
  31595. for (f = 0; f < nbfaces; f++) {
  31596. for (i = 0; i < data.face[f].length - 2; i++) {
  31597. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31598. }
  31599. }
  31600. }
  31601. else {
  31602. for (f = 0; f < nbfaces; f++) {
  31603. var fl = data.face[f].length; // number of vertices of the current face
  31604. ang = 2 * Math.PI / fl;
  31605. x = 0.5 * Math.tan(ang / 2);
  31606. y = 0.5;
  31607. // positions, uvs, colors
  31608. for (i = 0; i < fl; i++) {
  31609. // positions
  31610. 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);
  31611. indexes.push(index);
  31612. index++;
  31613. // uvs
  31614. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31615. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31616. uvs.push(u, v);
  31617. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31618. y = x * Math.sin(ang) + y * Math.cos(ang);
  31619. x = tmp;
  31620. // colors
  31621. if (faceColors) {
  31622. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31623. }
  31624. }
  31625. // indices from indexes
  31626. for (i = 0; i < fl - 2; i++) {
  31627. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31628. }
  31629. faceIdx += fl;
  31630. }
  31631. }
  31632. VertexData.ComputeNormals(positions, indices, normals);
  31633. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31634. var vertexData = new VertexData();
  31635. vertexData.positions = positions;
  31636. vertexData.indices = indices;
  31637. vertexData.normals = normals;
  31638. vertexData.uvs = uvs;
  31639. if (faceColors && flat) {
  31640. vertexData.colors = colors;
  31641. }
  31642. return vertexData;
  31643. };
  31644. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31645. /**
  31646. * Creates the VertexData of the Torus Knot.
  31647. */
  31648. VertexData.CreateTorusKnot = function (options) {
  31649. var indices = new Array();
  31650. var positions = new Array();
  31651. var normals = new Array();
  31652. var uvs = new Array();
  31653. var radius = options.radius || 2;
  31654. var tube = options.tube || 0.5;
  31655. var radialSegments = options.radialSegments || 32;
  31656. var tubularSegments = options.tubularSegments || 32;
  31657. var p = options.p || 2;
  31658. var q = options.q || 3;
  31659. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31660. // Helper
  31661. var getPos = function (angle) {
  31662. var cu = Math.cos(angle);
  31663. var su = Math.sin(angle);
  31664. var quOverP = q / p * angle;
  31665. var cs = Math.cos(quOverP);
  31666. var tx = radius * (2 + cs) * 0.5 * cu;
  31667. var ty = radius * (2 + cs) * su * 0.5;
  31668. var tz = radius * Math.sin(quOverP) * 0.5;
  31669. return new BABYLON.Vector3(tx, ty, tz);
  31670. };
  31671. // Vertices
  31672. var i;
  31673. var j;
  31674. for (i = 0; i <= radialSegments; i++) {
  31675. var modI = i % radialSegments;
  31676. var u = modI / radialSegments * 2 * p * Math.PI;
  31677. var p1 = getPos(u);
  31678. var p2 = getPos(u + 0.01);
  31679. var tang = p2.subtract(p1);
  31680. var n = p2.add(p1);
  31681. var bitan = BABYLON.Vector3.Cross(tang, n);
  31682. n = BABYLON.Vector3.Cross(bitan, tang);
  31683. bitan.normalize();
  31684. n.normalize();
  31685. for (j = 0; j < tubularSegments; j++) {
  31686. var modJ = j % tubularSegments;
  31687. var v = modJ / tubularSegments * 2 * Math.PI;
  31688. var cx = -tube * Math.cos(v);
  31689. var cy = tube * Math.sin(v);
  31690. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31691. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31692. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31693. uvs.push(i / radialSegments);
  31694. uvs.push(j / tubularSegments);
  31695. }
  31696. }
  31697. for (i = 0; i < radialSegments; i++) {
  31698. for (j = 0; j < tubularSegments; j++) {
  31699. var jNext = (j + 1) % tubularSegments;
  31700. var a = i * tubularSegments + j;
  31701. var b = (i + 1) * tubularSegments + j;
  31702. var c = (i + 1) * tubularSegments + jNext;
  31703. var d = i * tubularSegments + jNext;
  31704. indices.push(d);
  31705. indices.push(b);
  31706. indices.push(a);
  31707. indices.push(d);
  31708. indices.push(c);
  31709. indices.push(b);
  31710. }
  31711. }
  31712. // Normals
  31713. VertexData.ComputeNormals(positions, indices, normals);
  31714. // Sides
  31715. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31716. // Result
  31717. var vertexData = new VertexData();
  31718. vertexData.indices = indices;
  31719. vertexData.positions = positions;
  31720. vertexData.normals = normals;
  31721. vertexData.uvs = uvs;
  31722. return vertexData;
  31723. };
  31724. // Tools
  31725. /**
  31726. * @param {any} - positions (number[] or Float32Array)
  31727. * @param {any} - indices (number[] or Uint16Array)
  31728. * @param {any} - normals (number[] or Float32Array)
  31729. * options (optional) :
  31730. * facetPositions : optional array of facet positions (vector3)
  31731. * facetNormals : optional array of facet normals (vector3)
  31732. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31733. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31734. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31735. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31736. * bInfo : optional bounding info, required for facetPartitioning computation
  31737. * useRightHandedSystem: optional boolean to for right handed system computation
  31738. * depthSort : optional boolean to enable the facet depth sort computation
  31739. * distanceTo : optional Vector3 to compute the facet depth from this location
  31740. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31741. */
  31742. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31743. // temporary scalar variables
  31744. var index = 0; // facet index
  31745. var p1p2x = 0.0; // p1p2 vector x coordinate
  31746. var p1p2y = 0.0; // p1p2 vector y coordinate
  31747. var p1p2z = 0.0; // p1p2 vector z coordinate
  31748. var p3p2x = 0.0; // p3p2 vector x coordinate
  31749. var p3p2y = 0.0; // p3p2 vector y coordinate
  31750. var p3p2z = 0.0; // p3p2 vector z coordinate
  31751. var faceNormalx = 0.0; // facet normal x coordinate
  31752. var faceNormaly = 0.0; // facet normal y coordinate
  31753. var faceNormalz = 0.0; // facet normal z coordinate
  31754. var length = 0.0; // facet normal length before normalization
  31755. var v1x = 0; // vector1 x index in the positions array
  31756. var v1y = 0; // vector1 y index in the positions array
  31757. var v1z = 0; // vector1 z index in the positions array
  31758. var v2x = 0; // vector2 x index in the positions array
  31759. var v2y = 0; // vector2 y index in the positions array
  31760. var v2z = 0; // vector2 z index in the positions array
  31761. var v3x = 0; // vector3 x index in the positions array
  31762. var v3y = 0; // vector3 y index in the positions array
  31763. var v3z = 0; // vector3 z index in the positions array
  31764. var computeFacetNormals = false;
  31765. var computeFacetPositions = false;
  31766. var computeFacetPartitioning = false;
  31767. var computeDepthSort = false;
  31768. var faceNormalSign = 1;
  31769. var ratio = 0;
  31770. var distanceTo = null;
  31771. if (options) {
  31772. computeFacetNormals = (options.facetNormals) ? true : false;
  31773. computeFacetPositions = (options.facetPositions) ? true : false;
  31774. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31775. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31776. ratio = options.ratio || 0;
  31777. computeDepthSort = (options.depthSort) ? true : false;
  31778. distanceTo = (options.distanceTo);
  31779. if (computeDepthSort) {
  31780. if (distanceTo === undefined) {
  31781. distanceTo = BABYLON.Vector3.Zero();
  31782. }
  31783. var depthSortedFacets = options.depthSortedFacets;
  31784. }
  31785. }
  31786. // facetPartitioning reinit if needed
  31787. var xSubRatio = 0;
  31788. var ySubRatio = 0;
  31789. var zSubRatio = 0;
  31790. var subSq = 0;
  31791. if (computeFacetPartitioning && options && options.bbSize) {
  31792. var ox = 0; // X partitioning index for facet position
  31793. var oy = 0; // Y partinioning index for facet position
  31794. var oz = 0; // Z partinioning index for facet position
  31795. var b1x = 0; // X partitioning index for facet v1 vertex
  31796. var b1y = 0; // Y partitioning index for facet v1 vertex
  31797. var b1z = 0; // z partitioning index for facet v1 vertex
  31798. var b2x = 0; // X partitioning index for facet v2 vertex
  31799. var b2y = 0; // Y partitioning index for facet v2 vertex
  31800. var b2z = 0; // Z partitioning index for facet v2 vertex
  31801. var b3x = 0; // X partitioning index for facet v3 vertex
  31802. var b3y = 0; // Y partitioning index for facet v3 vertex
  31803. var b3z = 0; // Z partitioning index for facet v3 vertex
  31804. var block_idx_o = 0; // facet barycenter block index
  31805. var block_idx_v1 = 0; // v1 vertex block index
  31806. var block_idx_v2 = 0; // v2 vertex block index
  31807. var block_idx_v3 = 0; // v3 vertex block index
  31808. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31809. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31810. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31811. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31812. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31813. subSq = options.subDiv.max * options.subDiv.max;
  31814. options.facetPartitioning.length = 0;
  31815. }
  31816. // reset the normals
  31817. for (index = 0; index < positions.length; index++) {
  31818. normals[index] = 0.0;
  31819. }
  31820. // Loop : 1 indice triplet = 1 facet
  31821. var nbFaces = (indices.length / 3) | 0;
  31822. for (index = 0; index < nbFaces; index++) {
  31823. // get the indexes of the coordinates of each vertex of the facet
  31824. v1x = indices[index * 3] * 3;
  31825. v1y = v1x + 1;
  31826. v1z = v1x + 2;
  31827. v2x = indices[index * 3 + 1] * 3;
  31828. v2y = v2x + 1;
  31829. v2z = v2x + 2;
  31830. v3x = indices[index * 3 + 2] * 3;
  31831. v3y = v3x + 1;
  31832. v3z = v3x + 2;
  31833. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31834. p1p2y = positions[v1y] - positions[v2y];
  31835. p1p2z = positions[v1z] - positions[v2z];
  31836. p3p2x = positions[v3x] - positions[v2x];
  31837. p3p2y = positions[v3y] - positions[v2y];
  31838. p3p2z = positions[v3z] - positions[v2z];
  31839. // compute the face normal with the cross product
  31840. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31841. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31842. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31843. // normalize this normal and store it in the array facetData
  31844. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31845. length = (length === 0) ? 1.0 : length;
  31846. faceNormalx /= length;
  31847. faceNormaly /= length;
  31848. faceNormalz /= length;
  31849. if (computeFacetNormals && options) {
  31850. options.facetNormals[index].x = faceNormalx;
  31851. options.facetNormals[index].y = faceNormaly;
  31852. options.facetNormals[index].z = faceNormalz;
  31853. }
  31854. if (computeFacetPositions && options) {
  31855. // compute and the facet barycenter coordinates in the array facetPositions
  31856. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31857. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31858. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31859. }
  31860. if (computeFacetPartitioning && options) {
  31861. // store the facet indexes in arrays in the main facetPartitioning array :
  31862. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31863. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31864. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31865. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31866. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31867. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31868. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31869. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31870. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31871. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31872. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31873. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31874. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31875. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31876. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31877. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31878. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31879. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31880. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31881. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31882. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31883. // push each facet index in each block containing the vertex
  31884. options.facetPartitioning[block_idx_v1].push(index);
  31885. if (block_idx_v2 != block_idx_v1) {
  31886. options.facetPartitioning[block_idx_v2].push(index);
  31887. }
  31888. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31889. options.facetPartitioning[block_idx_v3].push(index);
  31890. }
  31891. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31892. options.facetPartitioning[block_idx_o].push(index);
  31893. }
  31894. }
  31895. if (computeDepthSort && options && options.facetPositions) {
  31896. var dsf = depthSortedFacets[index];
  31897. dsf.ind = index * 3;
  31898. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31899. }
  31900. // compute the normals anyway
  31901. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31902. normals[v1y] += faceNormaly;
  31903. normals[v1z] += faceNormalz;
  31904. normals[v2x] += faceNormalx;
  31905. normals[v2y] += faceNormaly;
  31906. normals[v2z] += faceNormalz;
  31907. normals[v3x] += faceNormalx;
  31908. normals[v3y] += faceNormaly;
  31909. normals[v3z] += faceNormalz;
  31910. }
  31911. // last normalization of each normal
  31912. for (index = 0; index < normals.length / 3; index++) {
  31913. faceNormalx = normals[index * 3];
  31914. faceNormaly = normals[index * 3 + 1];
  31915. faceNormalz = normals[index * 3 + 2];
  31916. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31917. length = (length === 0) ? 1.0 : length;
  31918. faceNormalx /= length;
  31919. faceNormaly /= length;
  31920. faceNormalz /= length;
  31921. normals[index * 3] = faceNormalx;
  31922. normals[index * 3 + 1] = faceNormaly;
  31923. normals[index * 3 + 2] = faceNormalz;
  31924. }
  31925. };
  31926. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31927. var li = indices.length;
  31928. var ln = normals.length;
  31929. var i;
  31930. var n;
  31931. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31932. switch (sideOrientation) {
  31933. case BABYLON.Mesh.FRONTSIDE:
  31934. // nothing changed
  31935. break;
  31936. case BABYLON.Mesh.BACKSIDE:
  31937. var tmp;
  31938. // indices
  31939. for (i = 0; i < li; i += 3) {
  31940. tmp = indices[i];
  31941. indices[i] = indices[i + 2];
  31942. indices[i + 2] = tmp;
  31943. }
  31944. // normals
  31945. for (n = 0; n < ln; n++) {
  31946. normals[n] = -normals[n];
  31947. }
  31948. break;
  31949. case BABYLON.Mesh.DOUBLESIDE:
  31950. // positions
  31951. var lp = positions.length;
  31952. var l = lp / 3;
  31953. for (var p = 0; p < lp; p++) {
  31954. positions[lp + p] = positions[p];
  31955. }
  31956. // indices
  31957. for (i = 0; i < li; i += 3) {
  31958. indices[i + li] = indices[i + 2] + l;
  31959. indices[i + 1 + li] = indices[i + 1] + l;
  31960. indices[i + 2 + li] = indices[i] + l;
  31961. }
  31962. // normals
  31963. for (n = 0; n < ln; n++) {
  31964. normals[ln + n] = -normals[n];
  31965. }
  31966. // uvs
  31967. var lu = uvs.length;
  31968. var u = 0;
  31969. for (u = 0; u < lu; u++) {
  31970. uvs[u + lu] = uvs[u];
  31971. }
  31972. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31973. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31974. u = 0;
  31975. for (i = 0; i < lu / 2; i++) {
  31976. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31977. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31978. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31979. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31980. u += 2;
  31981. }
  31982. break;
  31983. }
  31984. };
  31985. /**
  31986. * Creates a new VertexData from the imported parameters.
  31987. */
  31988. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31989. var vertexData = new VertexData();
  31990. // positions
  31991. var positions = parsedVertexData.positions;
  31992. if (positions) {
  31993. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31994. }
  31995. // normals
  31996. var normals = parsedVertexData.normals;
  31997. if (normals) {
  31998. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31999. }
  32000. // tangents
  32001. var tangents = parsedVertexData.tangents;
  32002. if (tangents) {
  32003. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32004. }
  32005. // uvs
  32006. var uvs = parsedVertexData.uvs;
  32007. if (uvs) {
  32008. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32009. }
  32010. // uv2s
  32011. var uv2s = parsedVertexData.uv2s;
  32012. if (uv2s) {
  32013. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32014. }
  32015. // uv3s
  32016. var uv3s = parsedVertexData.uv3s;
  32017. if (uv3s) {
  32018. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32019. }
  32020. // uv4s
  32021. var uv4s = parsedVertexData.uv4s;
  32022. if (uv4s) {
  32023. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32024. }
  32025. // uv5s
  32026. var uv5s = parsedVertexData.uv5s;
  32027. if (uv5s) {
  32028. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32029. }
  32030. // uv6s
  32031. var uv6s = parsedVertexData.uv6s;
  32032. if (uv6s) {
  32033. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32034. }
  32035. // colors
  32036. var colors = parsedVertexData.colors;
  32037. if (colors) {
  32038. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32039. }
  32040. // matricesIndices
  32041. var matricesIndices = parsedVertexData.matricesIndices;
  32042. if (matricesIndices) {
  32043. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32044. }
  32045. // matricesWeights
  32046. var matricesWeights = parsedVertexData.matricesWeights;
  32047. if (matricesWeights) {
  32048. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32049. }
  32050. // indices
  32051. var indices = parsedVertexData.indices;
  32052. if (indices) {
  32053. vertexData.indices = indices;
  32054. }
  32055. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32056. };
  32057. return VertexData;
  32058. }());
  32059. BABYLON.VertexData = VertexData;
  32060. })(BABYLON || (BABYLON = {}));
  32061. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32062. var BABYLON;
  32063. (function (BABYLON) {
  32064. /**
  32065. * Class used to store geometry data (vertex buffers + index buffer)
  32066. */
  32067. var Geometry = /** @class */ (function () {
  32068. /**
  32069. * Creates a new geometry
  32070. * @param id defines the unique ID
  32071. * @param scene defines the hosting scene
  32072. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32073. * @param updatable defines if geometry must be updatable (false by default)
  32074. * @param mesh defines the mesh that will be associated with the geometry
  32075. */
  32076. function Geometry(id, scene, vertexData, updatable, mesh) {
  32077. if (updatable === void 0) { updatable = false; }
  32078. if (mesh === void 0) { mesh = null; }
  32079. /**
  32080. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32081. */
  32082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32083. this._totalVertices = 0;
  32084. this._isDisposed = false;
  32085. this._indexBufferIsUpdatable = false;
  32086. this.id = id;
  32087. this._engine = scene.getEngine();
  32088. this._meshes = [];
  32089. this._scene = scene;
  32090. //Init vertex buffer cache
  32091. this._vertexBuffers = {};
  32092. this._indices = [];
  32093. this._updatable = updatable;
  32094. // vertexData
  32095. if (vertexData) {
  32096. this.setAllVerticesData(vertexData, updatable);
  32097. }
  32098. else {
  32099. this._totalVertices = 0;
  32100. this._indices = [];
  32101. }
  32102. if (this._engine.getCaps().vertexArrayObject) {
  32103. this._vertexArrayObjects = {};
  32104. }
  32105. // applyToMesh
  32106. if (mesh) {
  32107. if (mesh.getClassName() === "LinesMesh") {
  32108. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32109. this.updateExtend();
  32110. }
  32111. this.applyToMesh(mesh);
  32112. mesh.computeWorldMatrix(true);
  32113. }
  32114. }
  32115. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32116. /**
  32117. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  32118. */
  32119. get: function () {
  32120. return this._boundingBias;
  32121. },
  32122. /**
  32123. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  32124. */
  32125. set: function (value) {
  32126. if (this._boundingBias && this._boundingBias.equals(value)) {
  32127. return;
  32128. }
  32129. this._boundingBias = value.clone();
  32130. this.updateBoundingInfo(true, null);
  32131. },
  32132. enumerable: true,
  32133. configurable: true
  32134. });
  32135. /**
  32136. * Static function used to attach a new empty geometry to a mesh
  32137. * @param mesh defines the mesh to attach the geometry to
  32138. * @returns the new {BABYLON.Geometry}
  32139. */
  32140. Geometry.CreateGeometryForMesh = function (mesh) {
  32141. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32142. geometry.applyToMesh(mesh);
  32143. return geometry;
  32144. };
  32145. Object.defineProperty(Geometry.prototype, "extend", {
  32146. /**
  32147. * Gets the current extend of the geometry
  32148. */
  32149. get: function () {
  32150. return this._extend;
  32151. },
  32152. enumerable: true,
  32153. configurable: true
  32154. });
  32155. /**
  32156. * Gets the hosting scene
  32157. * @returns the hosting {BABYLON.Scene}
  32158. */
  32159. Geometry.prototype.getScene = function () {
  32160. return this._scene;
  32161. };
  32162. /**
  32163. * Gets the hosting engine
  32164. * @returns the hosting {BABYLON.Engine}
  32165. */
  32166. Geometry.prototype.getEngine = function () {
  32167. return this._engine;
  32168. };
  32169. /**
  32170. * Defines if the geometry is ready to use
  32171. * @returns true if the geometry is ready to be used
  32172. */
  32173. Geometry.prototype.isReady = function () {
  32174. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32175. };
  32176. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32177. /**
  32178. * Gets a value indicating that the geometry should not be serialized
  32179. */
  32180. get: function () {
  32181. for (var index = 0; index < this._meshes.length; index++) {
  32182. if (!this._meshes[index].doNotSerialize) {
  32183. return false;
  32184. }
  32185. }
  32186. return true;
  32187. },
  32188. enumerable: true,
  32189. configurable: true
  32190. });
  32191. /** @ignore */
  32192. Geometry.prototype._rebuild = function () {
  32193. if (this._vertexArrayObjects) {
  32194. this._vertexArrayObjects = {};
  32195. }
  32196. // Index buffer
  32197. if (this._meshes.length !== 0 && this._indices) {
  32198. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32199. }
  32200. // Vertex buffers
  32201. for (var key in this._vertexBuffers) {
  32202. var vertexBuffer = this._vertexBuffers[key];
  32203. vertexBuffer._rebuild();
  32204. }
  32205. };
  32206. /**
  32207. * Affects all gemetry data in one call
  32208. * @param vertexData defines the geometry data
  32209. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32210. */
  32211. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32212. vertexData.applyToGeometry(this, updatable);
  32213. this.notifyUpdate();
  32214. };
  32215. /**
  32216. * Set specific vertex data
  32217. * @param kind defines the data kind (Position, normal, etc...)
  32218. * @param data defines the vertex data to use
  32219. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32220. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32221. */
  32222. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32223. if (updatable === void 0) { updatable = false; }
  32224. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32225. this.setVerticesBuffer(buffer);
  32226. };
  32227. /**
  32228. * Removes a specific vertex data
  32229. * @param kind defines the data kind (Position, normal, etc...)
  32230. */
  32231. Geometry.prototype.removeVerticesData = function (kind) {
  32232. if (this._vertexBuffers[kind]) {
  32233. this._vertexBuffers[kind].dispose();
  32234. delete this._vertexBuffers[kind];
  32235. }
  32236. };
  32237. /**
  32238. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32239. * @param buffer defines the vertex buffer to use
  32240. */
  32241. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32242. var kind = buffer.getKind();
  32243. if (this._vertexBuffers[kind]) {
  32244. this._vertexBuffers[kind].dispose();
  32245. }
  32246. this._vertexBuffers[kind] = buffer;
  32247. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32248. var data = buffer.getData();
  32249. var stride = buffer.getStrideSize();
  32250. this._totalVertices = data.length / stride;
  32251. this.updateExtend(data, stride);
  32252. this._resetPointsArrayCache();
  32253. var meshes = this._meshes;
  32254. var numOfMeshes = meshes.length;
  32255. for (var index = 0; index < numOfMeshes; index++) {
  32256. var mesh = meshes[index];
  32257. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32258. mesh._createGlobalSubMesh(false);
  32259. mesh.computeWorldMatrix(true);
  32260. }
  32261. }
  32262. this.notifyUpdate(kind);
  32263. if (this._vertexArrayObjects) {
  32264. this._disposeVertexArrayObjects();
  32265. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32266. }
  32267. };
  32268. /**
  32269. * Update a specific vertex buffer
  32270. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32271. * It will do nothing if the buffer is not updatable
  32272. * @param kind defines the data kind (Position, normal, etc...)
  32273. * @param data defines the data to use
  32274. * @param offset defines the offset in the target buffer where to store the data
  32275. */
  32276. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32277. var vertexBuffer = this.getVertexBuffer(kind);
  32278. if (!vertexBuffer) {
  32279. return;
  32280. }
  32281. vertexBuffer.updateDirectly(data, offset);
  32282. this.notifyUpdate(kind);
  32283. };
  32284. /**
  32285. * Update a specific vertex buffer
  32286. * This function will create a new buffer if the current one is not updatable
  32287. * @param kind defines the data kind (Position, normal, etc...)
  32288. * @param data defines the data to use
  32289. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32290. */
  32291. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32292. if (updateExtends === void 0) { updateExtends = false; }
  32293. var vertexBuffer = this.getVertexBuffer(kind);
  32294. if (!vertexBuffer) {
  32295. return;
  32296. }
  32297. vertexBuffer.update(data);
  32298. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32299. var stride = vertexBuffer.getStrideSize();
  32300. this._totalVertices = data.length / stride;
  32301. this.updateBoundingInfo(updateExtends, data);
  32302. }
  32303. this.notifyUpdate(kind);
  32304. };
  32305. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32306. if (updateExtends) {
  32307. this.updateExtend(data);
  32308. }
  32309. var meshes = this._meshes;
  32310. var numOfMeshes = meshes.length;
  32311. this._resetPointsArrayCache();
  32312. for (var index = 0; index < numOfMeshes; index++) {
  32313. var mesh = meshes[index];
  32314. if (updateExtends) {
  32315. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32316. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32317. var subMesh = mesh.subMeshes[subIndex];
  32318. subMesh.refreshBoundingInfo();
  32319. }
  32320. }
  32321. }
  32322. };
  32323. /** @ignore */
  32324. Geometry.prototype._bind = function (effect, indexToBind) {
  32325. if (!effect) {
  32326. return;
  32327. }
  32328. if (indexToBind === undefined) {
  32329. indexToBind = this._indexBuffer;
  32330. }
  32331. var vbs = this.getVertexBuffers();
  32332. if (!vbs) {
  32333. return;
  32334. }
  32335. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32336. this._engine.bindBuffers(vbs, indexToBind, effect);
  32337. return;
  32338. }
  32339. // Using VAO
  32340. if (!this._vertexArrayObjects[effect.key]) {
  32341. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32342. }
  32343. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32344. };
  32345. /**
  32346. * Gets total number of vertices
  32347. * @returns the total number of vertices
  32348. */
  32349. Geometry.prototype.getTotalVertices = function () {
  32350. if (!this.isReady()) {
  32351. return 0;
  32352. }
  32353. return this._totalVertices;
  32354. };
  32355. /**
  32356. * Gets a specific vertex data attached to this geometry
  32357. * @param kind defines the data kind (Position, normal, etc...)
  32358. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32359. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32360. * @returns a float array containing vertex data
  32361. */
  32362. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32363. var vertexBuffer = this.getVertexBuffer(kind);
  32364. if (!vertexBuffer) {
  32365. return null;
  32366. }
  32367. var orig = vertexBuffer.getData();
  32368. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32369. return orig;
  32370. }
  32371. else {
  32372. var len = orig.length;
  32373. var copy = [];
  32374. for (var i = 0; i < len; i++) {
  32375. copy.push(orig[i]);
  32376. }
  32377. return copy;
  32378. }
  32379. };
  32380. /**
  32381. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32382. * @param kind defines the data kind (Position, normal, etc...)
  32383. * @returns true if the vertex buffer with the specified kind is updatable
  32384. */
  32385. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32386. var vb = this._vertexBuffers[kind];
  32387. if (!vb) {
  32388. return false;
  32389. }
  32390. return vb.isUpdatable();
  32391. };
  32392. /**
  32393. * Gets a specific vertex buffer
  32394. * @param kind defines the data kind (Position, normal, etc...)
  32395. * @returns a {BABYLON.VertexBuffer}
  32396. */
  32397. Geometry.prototype.getVertexBuffer = function (kind) {
  32398. if (!this.isReady()) {
  32399. return null;
  32400. }
  32401. return this._vertexBuffers[kind];
  32402. };
  32403. /**
  32404. * Returns all vertex buffers
  32405. * @return an object holding all vertex buffers indexed by kind
  32406. */
  32407. Geometry.prototype.getVertexBuffers = function () {
  32408. if (!this.isReady()) {
  32409. return null;
  32410. }
  32411. return this._vertexBuffers;
  32412. };
  32413. /**
  32414. * Gets a boolean indicating if specific vertex buffer is present
  32415. * @param kind defines the data kind (Position, normal, etc...)
  32416. * @returns true if data is present
  32417. */
  32418. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32419. if (!this._vertexBuffers) {
  32420. if (this._delayInfo) {
  32421. return this._delayInfo.indexOf(kind) !== -1;
  32422. }
  32423. return false;
  32424. }
  32425. return this._vertexBuffers[kind] !== undefined;
  32426. };
  32427. /**
  32428. * Gets a list of all attached data kinds (Position, normal, etc...)
  32429. * @returns a list of string containing all kinds
  32430. */
  32431. Geometry.prototype.getVerticesDataKinds = function () {
  32432. var result = [];
  32433. var kind;
  32434. if (!this._vertexBuffers && this._delayInfo) {
  32435. for (kind in this._delayInfo) {
  32436. result.push(kind);
  32437. }
  32438. }
  32439. else {
  32440. for (kind in this._vertexBuffers) {
  32441. result.push(kind);
  32442. }
  32443. }
  32444. return result;
  32445. };
  32446. /**
  32447. * Update index buffer
  32448. * @param indices defines the indices to store in the index buffer
  32449. * @param offset defines the offset in the target buffer where to store the data
  32450. */
  32451. Geometry.prototype.updateIndices = function (indices, offset) {
  32452. if (!this._indexBuffer) {
  32453. return;
  32454. }
  32455. if (!this._indexBufferIsUpdatable) {
  32456. this.setIndices(indices, null, true);
  32457. }
  32458. else {
  32459. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  32460. }
  32461. };
  32462. /**
  32463. * Creates a new index buffer
  32464. * @param indices defines the indices to store in the index buffer
  32465. * @param totalVertices defines the total number of vertices (could be null)
  32466. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  32467. */
  32468. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  32469. if (totalVertices === void 0) { totalVertices = null; }
  32470. if (updatable === void 0) { updatable = false; }
  32471. if (this._indexBuffer) {
  32472. this._engine._releaseBuffer(this._indexBuffer);
  32473. }
  32474. this._disposeVertexArrayObjects();
  32475. this._indices = indices;
  32476. this._indexBufferIsUpdatable = updatable;
  32477. if (this._meshes.length !== 0 && this._indices) {
  32478. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  32479. }
  32480. if (totalVertices != undefined) {
  32481. this._totalVertices = totalVertices;
  32482. }
  32483. var meshes = this._meshes;
  32484. var numOfMeshes = meshes.length;
  32485. for (var index = 0; index < numOfMeshes; index++) {
  32486. meshes[index]._createGlobalSubMesh(true);
  32487. }
  32488. this.notifyUpdate();
  32489. };
  32490. /**
  32491. * Return the total number of indices
  32492. * @returns the total number of indices
  32493. */
  32494. Geometry.prototype.getTotalIndices = function () {
  32495. if (!this.isReady()) {
  32496. return 0;
  32497. }
  32498. return this._indices.length;
  32499. };
  32500. /**
  32501. * Gets the index buffer array
  32502. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32503. * @returns the index buffer array
  32504. */
  32505. Geometry.prototype.getIndices = function (copyWhenShared) {
  32506. if (!this.isReady()) {
  32507. return null;
  32508. }
  32509. var orig = this._indices;
  32510. if (!copyWhenShared || this._meshes.length === 1) {
  32511. return orig;
  32512. }
  32513. else {
  32514. var len = orig.length;
  32515. var copy = [];
  32516. for (var i = 0; i < len; i++) {
  32517. copy.push(orig[i]);
  32518. }
  32519. return copy;
  32520. }
  32521. };
  32522. /**
  32523. * Gets the index buffer
  32524. * @return the index buffer
  32525. */
  32526. Geometry.prototype.getIndexBuffer = function () {
  32527. if (!this.isReady()) {
  32528. return null;
  32529. }
  32530. return this._indexBuffer;
  32531. };
  32532. /** @ignore */
  32533. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  32534. if (effect === void 0) { effect = null; }
  32535. if (!effect || !this._vertexArrayObjects) {
  32536. return;
  32537. }
  32538. if (this._vertexArrayObjects[effect.key]) {
  32539. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  32540. delete this._vertexArrayObjects[effect.key];
  32541. }
  32542. };
  32543. /**
  32544. * Release the associated resources for a specific mesh
  32545. * @param mesh defines the source mesh
  32546. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  32547. */
  32548. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32549. var meshes = this._meshes;
  32550. var index = meshes.indexOf(mesh);
  32551. if (index === -1) {
  32552. return;
  32553. }
  32554. meshes.splice(index, 1);
  32555. mesh._geometry = null;
  32556. if (meshes.length === 0 && shouldDispose) {
  32557. this.dispose();
  32558. }
  32559. };
  32560. /**
  32561. * Apply current geometry to a given mesh
  32562. * @param mesh defines the mesh to apply geometry to
  32563. */
  32564. Geometry.prototype.applyToMesh = function (mesh) {
  32565. if (mesh._geometry === this) {
  32566. return;
  32567. }
  32568. var previousGeometry = mesh._geometry;
  32569. if (previousGeometry) {
  32570. previousGeometry.releaseForMesh(mesh);
  32571. }
  32572. var meshes = this._meshes;
  32573. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32574. mesh._geometry = this;
  32575. this._scene.pushGeometry(this);
  32576. meshes.push(mesh);
  32577. if (this.isReady()) {
  32578. this._applyToMesh(mesh);
  32579. }
  32580. else {
  32581. mesh._boundingInfo = this._boundingInfo;
  32582. }
  32583. };
  32584. Geometry.prototype.updateExtend = function (data, stride) {
  32585. if (data === void 0) { data = null; }
  32586. if (!data) {
  32587. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32588. }
  32589. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32590. };
  32591. Geometry.prototype._applyToMesh = function (mesh) {
  32592. var numOfMeshes = this._meshes.length;
  32593. // vertexBuffers
  32594. for (var kind in this._vertexBuffers) {
  32595. if (numOfMeshes === 1) {
  32596. this._vertexBuffers[kind].create();
  32597. }
  32598. var buffer = this._vertexBuffers[kind].getBuffer();
  32599. if (buffer)
  32600. buffer.references = numOfMeshes;
  32601. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32602. if (!this._extend) {
  32603. this.updateExtend(this._vertexBuffers[kind].getData());
  32604. }
  32605. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32606. mesh._createGlobalSubMesh(false);
  32607. //bounding info was just created again, world matrix should be applied again.
  32608. mesh._updateBoundingInfo();
  32609. }
  32610. }
  32611. // indexBuffer
  32612. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  32613. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32614. }
  32615. if (this._indexBuffer) {
  32616. this._indexBuffer.references = numOfMeshes;
  32617. }
  32618. };
  32619. Geometry.prototype.notifyUpdate = function (kind) {
  32620. if (this.onGeometryUpdated) {
  32621. this.onGeometryUpdated(this, kind);
  32622. }
  32623. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  32624. var mesh = _a[_i];
  32625. mesh._markSubMeshesAsAttributesDirty();
  32626. }
  32627. };
  32628. /**
  32629. * Load the geometry if it was flagged as delay loaded
  32630. * @param scene defines the hosting scene
  32631. * @param onLoaded defines a callback called when the geometry is loaded
  32632. */
  32633. Geometry.prototype.load = function (scene, onLoaded) {
  32634. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32635. return;
  32636. }
  32637. if (this.isReady()) {
  32638. if (onLoaded) {
  32639. onLoaded();
  32640. }
  32641. return;
  32642. }
  32643. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32644. this._queueLoad(scene, onLoaded);
  32645. };
  32646. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32647. var _this = this;
  32648. if (!this.delayLoadingFile) {
  32649. return;
  32650. }
  32651. scene._addPendingData(this);
  32652. scene._loadFile(this.delayLoadingFile, function (data) {
  32653. if (!_this._delayLoadingFunction) {
  32654. return;
  32655. }
  32656. _this._delayLoadingFunction(JSON.parse(data), _this);
  32657. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32658. _this._delayInfo = [];
  32659. scene._removePendingData(_this);
  32660. var meshes = _this._meshes;
  32661. var numOfMeshes = meshes.length;
  32662. for (var index = 0; index < numOfMeshes; index++) {
  32663. _this._applyToMesh(meshes[index]);
  32664. }
  32665. if (onLoaded) {
  32666. onLoaded();
  32667. }
  32668. }, undefined, true);
  32669. };
  32670. /**
  32671. * Invert the geometry to move from a right handed system to a left handed one.
  32672. */
  32673. Geometry.prototype.toLeftHanded = function () {
  32674. // Flip faces
  32675. var tIndices = this.getIndices(false);
  32676. if (tIndices != null && tIndices.length > 0) {
  32677. for (var i = 0; i < tIndices.length; i += 3) {
  32678. var tTemp = tIndices[i + 0];
  32679. tIndices[i + 0] = tIndices[i + 2];
  32680. tIndices[i + 2] = tTemp;
  32681. }
  32682. this.setIndices(tIndices);
  32683. }
  32684. // Negate position.z
  32685. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32686. if (tPositions != null && tPositions.length > 0) {
  32687. for (var i = 0; i < tPositions.length; i += 3) {
  32688. tPositions[i + 2] = -tPositions[i + 2];
  32689. }
  32690. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32691. }
  32692. // Negate normal.z
  32693. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32694. if (tNormals != null && tNormals.length > 0) {
  32695. for (var i = 0; i < tNormals.length; i += 3) {
  32696. tNormals[i + 2] = -tNormals[i + 2];
  32697. }
  32698. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32699. }
  32700. };
  32701. // Cache
  32702. /** @ignore */
  32703. Geometry.prototype._resetPointsArrayCache = function () {
  32704. this._positions = null;
  32705. };
  32706. /** @ignore */
  32707. Geometry.prototype._generatePointsArray = function () {
  32708. if (this._positions)
  32709. return true;
  32710. this._positions = [];
  32711. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32712. if (!data) {
  32713. return false;
  32714. }
  32715. for (var index = 0; index < data.length; index += 3) {
  32716. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32717. }
  32718. return true;
  32719. };
  32720. /**
  32721. * Gets a value indicating if the geometry is disposed
  32722. * @returns true if the geometry was disposed
  32723. */
  32724. Geometry.prototype.isDisposed = function () {
  32725. return this._isDisposed;
  32726. };
  32727. Geometry.prototype._disposeVertexArrayObjects = function () {
  32728. if (this._vertexArrayObjects) {
  32729. for (var kind in this._vertexArrayObjects) {
  32730. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32731. }
  32732. this._vertexArrayObjects = {};
  32733. }
  32734. };
  32735. /**
  32736. * Free all associated resources
  32737. */
  32738. Geometry.prototype.dispose = function () {
  32739. var meshes = this._meshes;
  32740. var numOfMeshes = meshes.length;
  32741. var index;
  32742. for (index = 0; index < numOfMeshes; index++) {
  32743. this.releaseForMesh(meshes[index]);
  32744. }
  32745. this._meshes = [];
  32746. this._disposeVertexArrayObjects();
  32747. for (var kind in this._vertexBuffers) {
  32748. this._vertexBuffers[kind].dispose();
  32749. }
  32750. this._vertexBuffers = {};
  32751. this._totalVertices = 0;
  32752. if (this._indexBuffer) {
  32753. this._engine._releaseBuffer(this._indexBuffer);
  32754. }
  32755. this._indexBuffer = null;
  32756. this._indices = [];
  32757. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32758. this.delayLoadingFile = null;
  32759. this._delayLoadingFunction = null;
  32760. this._delayInfo = [];
  32761. this._boundingInfo = null;
  32762. this._scene.removeGeometry(this);
  32763. this._isDisposed = true;
  32764. };
  32765. /**
  32766. * Clone the current geometry into a new geometry
  32767. * @param id defines the unique ID of the new geometry
  32768. * @returns a new geometry object
  32769. */
  32770. Geometry.prototype.copy = function (id) {
  32771. var vertexData = new BABYLON.VertexData();
  32772. vertexData.indices = [];
  32773. var indices = this.getIndices();
  32774. if (indices) {
  32775. for (var index = 0; index < indices.length; index++) {
  32776. vertexData.indices.push(indices[index]);
  32777. }
  32778. }
  32779. var updatable = false;
  32780. var stopChecking = false;
  32781. var kind;
  32782. for (kind in this._vertexBuffers) {
  32783. // using slice() to make a copy of the array and not just reference it
  32784. var data = this.getVerticesData(kind);
  32785. if (data instanceof Float32Array) {
  32786. vertexData.set(new Float32Array(data), kind);
  32787. }
  32788. else {
  32789. vertexData.set(data.slice(0), kind);
  32790. }
  32791. if (!stopChecking) {
  32792. var vb = this.getVertexBuffer(kind);
  32793. if (vb) {
  32794. updatable = vb.isUpdatable();
  32795. stopChecking = !updatable;
  32796. }
  32797. }
  32798. }
  32799. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32800. geometry.delayLoadState = this.delayLoadState;
  32801. geometry.delayLoadingFile = this.delayLoadingFile;
  32802. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32803. for (kind in this._delayInfo) {
  32804. geometry._delayInfo = geometry._delayInfo || [];
  32805. geometry._delayInfo.push(kind);
  32806. }
  32807. // Bounding info
  32808. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32809. return geometry;
  32810. };
  32811. /**
  32812. * Serialize the current geometry info (and not the vertices data) into a JSON object
  32813. * @return a JSON representation of the current geometry data (without the vertices data)
  32814. */
  32815. Geometry.prototype.serialize = function () {
  32816. var serializationObject = {};
  32817. serializationObject.id = this.id;
  32818. serializationObject.updatable = this._updatable;
  32819. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32820. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32821. }
  32822. return serializationObject;
  32823. };
  32824. Geometry.prototype.toNumberArray = function (origin) {
  32825. if (Array.isArray(origin)) {
  32826. return origin;
  32827. }
  32828. else {
  32829. return Array.prototype.slice.call(origin);
  32830. }
  32831. };
  32832. /**
  32833. * Serialize all vertices data into a JSON oject
  32834. * @returns a JSON representation of the current geometry data
  32835. */
  32836. Geometry.prototype.serializeVerticeData = function () {
  32837. var serializationObject = this.serialize();
  32838. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32839. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32840. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32841. serializationObject.positions._updatable = true;
  32842. }
  32843. }
  32844. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32845. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32846. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32847. serializationObject.normals._updatable = true;
  32848. }
  32849. }
  32850. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32851. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  32852. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  32853. serializationObject.tangets._updatable = true;
  32854. }
  32855. }
  32856. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32857. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32858. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32859. serializationObject.uvs._updatable = true;
  32860. }
  32861. }
  32862. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32863. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32864. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32865. serializationObject.uv2s._updatable = true;
  32866. }
  32867. }
  32868. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32869. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32870. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32871. serializationObject.uv3s._updatable = true;
  32872. }
  32873. }
  32874. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32875. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32876. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32877. serializationObject.uv4s._updatable = true;
  32878. }
  32879. }
  32880. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32881. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32882. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32883. serializationObject.uv5s._updatable = true;
  32884. }
  32885. }
  32886. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32887. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32888. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32889. serializationObject.uv6s._updatable = true;
  32890. }
  32891. }
  32892. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32893. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32894. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32895. serializationObject.colors._updatable = true;
  32896. }
  32897. }
  32898. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32899. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32900. serializationObject.matricesIndices._isExpanded = true;
  32901. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32902. serializationObject.matricesIndices._updatable = true;
  32903. }
  32904. }
  32905. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32906. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32907. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32908. serializationObject.matricesWeights._updatable = true;
  32909. }
  32910. }
  32911. serializationObject.indices = this.toNumberArray(this.getIndices());
  32912. return serializationObject;
  32913. };
  32914. // Statics
  32915. /**
  32916. * Extracts a clone of a mesh geometry
  32917. * @param mesh defines the source mesh
  32918. * @param id defines the unique ID of the new geometry object
  32919. * @returns the new geometry object
  32920. */
  32921. Geometry.ExtractFromMesh = function (mesh, id) {
  32922. var geometry = mesh._geometry;
  32923. if (!geometry) {
  32924. return null;
  32925. }
  32926. return geometry.copy(id);
  32927. };
  32928. /**
  32929. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32930. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32931. * Be aware Math.random() could cause collisions, but:
  32932. * "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"
  32933. * @returns a string containing a new GUID
  32934. */
  32935. Geometry.RandomId = function () {
  32936. return BABYLON.Tools.RandomId();
  32937. };
  32938. /** @ignore */
  32939. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  32940. var scene = mesh.getScene();
  32941. // Geometry
  32942. var geometryId = parsedGeometry.geometryId;
  32943. if (geometryId) {
  32944. var geometry = scene.getGeometryByID(geometryId);
  32945. if (geometry) {
  32946. geometry.applyToMesh(mesh);
  32947. }
  32948. }
  32949. else if (parsedGeometry instanceof ArrayBuffer) {
  32950. var binaryInfo = mesh._binaryInfo;
  32951. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32952. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32953. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32954. }
  32955. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32956. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32957. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32958. }
  32959. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  32960. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  32961. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  32962. }
  32963. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32964. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32965. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32966. }
  32967. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32968. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32969. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32970. }
  32971. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32972. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32973. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32974. }
  32975. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32976. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32977. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32978. }
  32979. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32980. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32981. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32982. }
  32983. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32984. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32985. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32986. }
  32987. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32988. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32989. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32990. }
  32991. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32992. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32993. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32994. }
  32995. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32996. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32997. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32998. }
  32999. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33000. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33001. mesh.setIndices(indicesData, null);
  33002. }
  33003. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33004. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33005. mesh.subMeshes = [];
  33006. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33007. var materialIndex = subMeshesData[(i * 5) + 0];
  33008. var verticesStart = subMeshesData[(i * 5) + 1];
  33009. var verticesCount = subMeshesData[(i * 5) + 2];
  33010. var indexStart = subMeshesData[(i * 5) + 3];
  33011. var indexCount = subMeshesData[(i * 5) + 4];
  33012. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33013. }
  33014. }
  33015. }
  33016. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33017. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33018. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33019. if (parsedGeometry.tangents) {
  33020. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33021. }
  33022. if (parsedGeometry.uvs) {
  33023. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33024. }
  33025. if (parsedGeometry.uvs2) {
  33026. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33027. }
  33028. if (parsedGeometry.uvs3) {
  33029. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33030. }
  33031. if (parsedGeometry.uvs4) {
  33032. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33033. }
  33034. if (parsedGeometry.uvs5) {
  33035. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33036. }
  33037. if (parsedGeometry.uvs6) {
  33038. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33039. }
  33040. if (parsedGeometry.colors) {
  33041. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33042. }
  33043. if (parsedGeometry.matricesIndices) {
  33044. if (!parsedGeometry.matricesIndices._isExpanded) {
  33045. var floatIndices = [];
  33046. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33047. var matricesIndex = parsedGeometry.matricesIndices[i];
  33048. floatIndices.push(matricesIndex & 0x000000FF);
  33049. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33050. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33051. floatIndices.push(matricesIndex >> 24);
  33052. }
  33053. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33054. }
  33055. else {
  33056. delete parsedGeometry.matricesIndices._isExpanded;
  33057. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33058. }
  33059. }
  33060. if (parsedGeometry.matricesIndicesExtra) {
  33061. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33062. var floatIndices = [];
  33063. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33064. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33065. floatIndices.push(matricesIndex & 0x000000FF);
  33066. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33067. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33068. floatIndices.push(matricesIndex >> 24);
  33069. }
  33070. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33071. }
  33072. else {
  33073. delete parsedGeometry.matricesIndices._isExpanded;
  33074. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33075. }
  33076. }
  33077. if (parsedGeometry.matricesWeights) {
  33078. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33079. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33080. }
  33081. if (parsedGeometry.matricesWeightsExtra) {
  33082. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33083. }
  33084. mesh.setIndices(parsedGeometry.indices, null);
  33085. }
  33086. // SubMeshes
  33087. if (parsedGeometry.subMeshes) {
  33088. mesh.subMeshes = [];
  33089. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33090. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33091. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33092. }
  33093. }
  33094. // Flat shading
  33095. if (mesh._shouldGenerateFlatShading) {
  33096. mesh.convertToFlatShadedMesh();
  33097. delete mesh._shouldGenerateFlatShading;
  33098. }
  33099. // Update
  33100. mesh.computeWorldMatrix(true);
  33101. // Octree
  33102. var sceneOctree = scene.selectionOctree;
  33103. if (sceneOctree !== undefined && sceneOctree !== null) {
  33104. sceneOctree.addMesh(mesh);
  33105. }
  33106. };
  33107. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33108. var epsilon = 1e-3;
  33109. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33110. return;
  33111. }
  33112. var noInfluenceBoneIndex = 0.0;
  33113. if (parsedGeometry.skeletonId > -1) {
  33114. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33115. if (!skeleton) {
  33116. return;
  33117. }
  33118. noInfluenceBoneIndex = skeleton.bones.length;
  33119. }
  33120. else {
  33121. return;
  33122. }
  33123. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33124. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33125. var matricesWeights = parsedGeometry.matricesWeights;
  33126. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33127. var influencers = parsedGeometry.numBoneInfluencer;
  33128. var size = matricesWeights.length;
  33129. for (var i = 0; i < size; i += 4) {
  33130. var weight = 0.0;
  33131. var firstZeroWeight = -1;
  33132. for (var j = 0; j < 4; j++) {
  33133. var w = matricesWeights[i + j];
  33134. weight += w;
  33135. if (w < epsilon && firstZeroWeight < 0) {
  33136. firstZeroWeight = j;
  33137. }
  33138. }
  33139. if (matricesWeightsExtra) {
  33140. for (var j = 0; j < 4; j++) {
  33141. var w = matricesWeightsExtra[i + j];
  33142. weight += w;
  33143. if (w < epsilon && firstZeroWeight < 0) {
  33144. firstZeroWeight = j + 4;
  33145. }
  33146. }
  33147. }
  33148. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33149. firstZeroWeight = influencers - 1;
  33150. }
  33151. if (weight > epsilon) {
  33152. var mweight = 1.0 / weight;
  33153. for (var j = 0; j < 4; j++) {
  33154. matricesWeights[i + j] *= mweight;
  33155. }
  33156. if (matricesWeightsExtra) {
  33157. for (var j = 0; j < 4; j++) {
  33158. matricesWeightsExtra[i + j] *= mweight;
  33159. }
  33160. }
  33161. }
  33162. else {
  33163. if (firstZeroWeight >= 4) {
  33164. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33165. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33166. }
  33167. else {
  33168. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33169. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33170. }
  33171. }
  33172. }
  33173. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33174. if (parsedGeometry.matricesWeightsExtra) {
  33175. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33176. }
  33177. };
  33178. /**
  33179. * Create a new geometry from persisted data (Using .babylon file format)
  33180. * @param parsedVertexData defines the persisted data
  33181. * @param scene defines the hosting scene
  33182. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33183. * @returns the new geometry object
  33184. */
  33185. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33186. if (scene.getGeometryByID(parsedVertexData.id)) {
  33187. return null; // null since geometry could be something else than a box...
  33188. }
  33189. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33190. if (BABYLON.Tags) {
  33191. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33192. }
  33193. if (parsedVertexData.delayLoadingFile) {
  33194. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33195. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33196. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33197. geometry._delayInfo = [];
  33198. if (parsedVertexData.hasUVs) {
  33199. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33200. }
  33201. if (parsedVertexData.hasUVs2) {
  33202. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33203. }
  33204. if (parsedVertexData.hasUVs3) {
  33205. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33206. }
  33207. if (parsedVertexData.hasUVs4) {
  33208. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33209. }
  33210. if (parsedVertexData.hasUVs5) {
  33211. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33212. }
  33213. if (parsedVertexData.hasUVs6) {
  33214. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33215. }
  33216. if (parsedVertexData.hasColors) {
  33217. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33218. }
  33219. if (parsedVertexData.hasMatricesIndices) {
  33220. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33221. }
  33222. if (parsedVertexData.hasMatricesWeights) {
  33223. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33224. }
  33225. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33226. }
  33227. else {
  33228. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33229. }
  33230. scene.pushGeometry(geometry, true);
  33231. return geometry;
  33232. };
  33233. return Geometry;
  33234. }());
  33235. BABYLON.Geometry = Geometry;
  33236. // Primitives
  33237. /// Abstract class
  33238. /**
  33239. * Abstract class used to provide common services for all typed geometries
  33240. */
  33241. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33242. __extends(_PrimitiveGeometry, _super);
  33243. /**
  33244. * Creates a new typed geometry
  33245. * @param id defines the unique ID of the geometry
  33246. * @param scene defines the hosting scene
  33247. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33248. * @param mesh defines the hosting mesh (can be null)
  33249. */
  33250. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33251. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33252. if (mesh === void 0) { mesh = null; }
  33253. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33254. _this._canBeRegenerated = _canBeRegenerated;
  33255. _this._beingRegenerated = true;
  33256. _this.regenerate();
  33257. _this._beingRegenerated = false;
  33258. return _this;
  33259. }
  33260. /**
  33261. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33262. * @returns true if the geometry can be regenerated
  33263. */
  33264. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33265. return this._canBeRegenerated;
  33266. };
  33267. /**
  33268. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33269. */
  33270. _PrimitiveGeometry.prototype.regenerate = function () {
  33271. if (!this._canBeRegenerated) {
  33272. return;
  33273. }
  33274. this._beingRegenerated = true;
  33275. this.setAllVerticesData(this._regenerateVertexData(), false);
  33276. this._beingRegenerated = false;
  33277. };
  33278. /**
  33279. * Clone the geometry
  33280. * @param id defines the unique ID of the new geometry
  33281. * @returns the new geometry
  33282. */
  33283. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33284. return _super.prototype.copy.call(this, id);
  33285. };
  33286. // overrides
  33287. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33288. if (!this._beingRegenerated) {
  33289. return;
  33290. }
  33291. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33292. };
  33293. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33294. if (!this._beingRegenerated) {
  33295. return;
  33296. }
  33297. _super.prototype.setVerticesData.call(this, kind, data, false);
  33298. };
  33299. // to override
  33300. /** @ignore */
  33301. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33302. throw new Error("Abstract method");
  33303. };
  33304. _PrimitiveGeometry.prototype.copy = function (id) {
  33305. throw new Error("Must be overriden in sub-classes.");
  33306. };
  33307. _PrimitiveGeometry.prototype.serialize = function () {
  33308. var serializationObject = _super.prototype.serialize.call(this);
  33309. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33310. return serializationObject;
  33311. };
  33312. return _PrimitiveGeometry;
  33313. }(Geometry));
  33314. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33315. /**
  33316. * Creates a ribbon geometry
  33317. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33318. */
  33319. var RibbonGeometry = /** @class */ (function (_super) {
  33320. __extends(RibbonGeometry, _super);
  33321. /**
  33322. * Creates a ribbon geometry
  33323. * @param id defines the unique ID of the geometry
  33324. * @param scene defines the hosting scene
  33325. * @param pathArray defines the array of paths to use
  33326. * @param closeArray defines if the last path and the first path must be joined
  33327. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33328. * @param offset defines the offset between points
  33329. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33330. * @param mesh defines the hosting mesh (can be null)
  33331. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33332. */
  33333. function RibbonGeometry(id, scene,
  33334. /**
  33335. * Defines the array of paths to use
  33336. */
  33337. pathArray,
  33338. /**
  33339. * Defines if the last and first points of each path in your pathArray must be joined
  33340. */
  33341. closeArray,
  33342. /**
  33343. * Defines if the last and first points of each path in your pathArray must be joined
  33344. */
  33345. closePath,
  33346. /**
  33347. * Defines the offset between points
  33348. */
  33349. offset, canBeRegenerated, mesh,
  33350. /**
  33351. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33352. */
  33353. side) {
  33354. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33355. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33356. _this.pathArray = pathArray;
  33357. _this.closeArray = closeArray;
  33358. _this.closePath = closePath;
  33359. _this.offset = offset;
  33360. _this.side = side;
  33361. return _this;
  33362. }
  33363. /** @ignore */
  33364. RibbonGeometry.prototype._regenerateVertexData = function () {
  33365. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33366. };
  33367. RibbonGeometry.prototype.copy = function (id) {
  33368. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33369. };
  33370. return RibbonGeometry;
  33371. }(_PrimitiveGeometry));
  33372. BABYLON.RibbonGeometry = RibbonGeometry;
  33373. /**
  33374. * Creates a box geometry
  33375. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33376. */
  33377. var BoxGeometry = /** @class */ (function (_super) {
  33378. __extends(BoxGeometry, _super);
  33379. /**
  33380. * Creates a box geometry
  33381. * @param id defines the unique ID of the geometry
  33382. * @param scene defines the hosting scene
  33383. * @param size defines the zise of the box (width, height and depth are the same)
  33384. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33385. * @param mesh defines the hosting mesh (can be null)
  33386. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33387. */
  33388. function BoxGeometry(id, scene,
  33389. /**
  33390. * Defines the zise of the box (width, height and depth are the same)
  33391. */
  33392. size, canBeRegenerated, mesh,
  33393. /**
  33394. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33395. */
  33396. side) {
  33397. if (mesh === void 0) { mesh = null; }
  33398. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33399. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33400. _this.size = size;
  33401. _this.side = side;
  33402. return _this;
  33403. }
  33404. BoxGeometry.prototype._regenerateVertexData = function () {
  33405. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33406. };
  33407. BoxGeometry.prototype.copy = function (id) {
  33408. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33409. };
  33410. BoxGeometry.prototype.serialize = function () {
  33411. var serializationObject = _super.prototype.serialize.call(this);
  33412. serializationObject.size = this.size;
  33413. return serializationObject;
  33414. };
  33415. BoxGeometry.Parse = function (parsedBox, scene) {
  33416. if (scene.getGeometryByID(parsedBox.id)) {
  33417. return null; // null since geometry could be something else than a box...
  33418. }
  33419. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33420. if (BABYLON.Tags) {
  33421. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33422. }
  33423. scene.pushGeometry(box, true);
  33424. return box;
  33425. };
  33426. return BoxGeometry;
  33427. }(_PrimitiveGeometry));
  33428. BABYLON.BoxGeometry = BoxGeometry;
  33429. /**
  33430. * Creates a sphere geometry
  33431. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33432. */
  33433. var SphereGeometry = /** @class */ (function (_super) {
  33434. __extends(SphereGeometry, _super);
  33435. /**
  33436. * Create a new sphere geometry
  33437. * @param id defines the unique ID of the geometry
  33438. * @param scene defines the hosting scene
  33439. * @param segments defines the number of segments to use to create the sphere
  33440. * @param diameter defines the diameter of the sphere
  33441. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33442. * @param mesh defines the hosting mesh (can be null)
  33443. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33444. */
  33445. function SphereGeometry(id, scene,
  33446. /**
  33447. * Defines the number of segments to use to create the sphere
  33448. */
  33449. segments,
  33450. /**
  33451. * Defines the diameter of the sphere
  33452. */
  33453. diameter, canBeRegenerated, mesh,
  33454. /**
  33455. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33456. */
  33457. side) {
  33458. if (mesh === void 0) { mesh = null; }
  33459. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33460. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33461. _this.segments = segments;
  33462. _this.diameter = diameter;
  33463. _this.side = side;
  33464. return _this;
  33465. }
  33466. SphereGeometry.prototype._regenerateVertexData = function () {
  33467. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33468. };
  33469. SphereGeometry.prototype.copy = function (id) {
  33470. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33471. };
  33472. SphereGeometry.prototype.serialize = function () {
  33473. var serializationObject = _super.prototype.serialize.call(this);
  33474. serializationObject.segments = this.segments;
  33475. serializationObject.diameter = this.diameter;
  33476. return serializationObject;
  33477. };
  33478. SphereGeometry.Parse = function (parsedSphere, scene) {
  33479. if (scene.getGeometryByID(parsedSphere.id)) {
  33480. return null; // null since geometry could be something else than a sphere...
  33481. }
  33482. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33483. if (BABYLON.Tags) {
  33484. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33485. }
  33486. scene.pushGeometry(sphere, true);
  33487. return sphere;
  33488. };
  33489. return SphereGeometry;
  33490. }(_PrimitiveGeometry));
  33491. BABYLON.SphereGeometry = SphereGeometry;
  33492. /**
  33493. * Creates a disc geometry
  33494. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  33495. */
  33496. var DiscGeometry = /** @class */ (function (_super) {
  33497. __extends(DiscGeometry, _super);
  33498. /**
  33499. * Creates a new disc geometry
  33500. * @param id defines the unique ID of the geometry
  33501. * @param scene defines the hosting scene
  33502. * @param radius defines the radius of the disc
  33503. * @param tessellation defines the tesselation factor to apply to the disc
  33504. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33505. * @param mesh defines the hosting mesh (can be null)
  33506. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33507. */
  33508. function DiscGeometry(id, scene,
  33509. /**
  33510. * Defines the radius of the disc
  33511. */
  33512. radius,
  33513. /**
  33514. * Defines the tesselation factor to apply to the disc
  33515. */
  33516. tessellation, canBeRegenerated, mesh,
  33517. /**
  33518. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33519. */
  33520. side) {
  33521. if (mesh === void 0) { mesh = null; }
  33522. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33523. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33524. _this.radius = radius;
  33525. _this.tessellation = tessellation;
  33526. _this.side = side;
  33527. return _this;
  33528. }
  33529. DiscGeometry.prototype._regenerateVertexData = function () {
  33530. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33531. };
  33532. DiscGeometry.prototype.copy = function (id) {
  33533. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33534. };
  33535. return DiscGeometry;
  33536. }(_PrimitiveGeometry));
  33537. BABYLON.DiscGeometry = DiscGeometry;
  33538. /**
  33539. * Creates a new cylinder geometry
  33540. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  33541. */
  33542. var CylinderGeometry = /** @class */ (function (_super) {
  33543. __extends(CylinderGeometry, _super);
  33544. /**
  33545. * Creates a new cylinder geometry
  33546. * @param id defines the unique ID of the geometry
  33547. * @param scene defines the hosting scene
  33548. * @param height defines the height of the cylinder
  33549. * @param diameterTop defines the diameter of the cylinder's top cap
  33550. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  33551. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  33552. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  33553. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33554. * @param mesh defines the hosting mesh (can be null)
  33555. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33556. */
  33557. function CylinderGeometry(id, scene,
  33558. /**
  33559. * Defines the height of the cylinder
  33560. */
  33561. height,
  33562. /**
  33563. * Defines the diameter of the cylinder's top cap
  33564. */
  33565. diameterTop,
  33566. /**
  33567. * Defines the diameter of the cylinder's bottom cap
  33568. */
  33569. diameterBottom,
  33570. /**
  33571. * Defines the tessellation factor to apply to the cylinder
  33572. */
  33573. tessellation,
  33574. /**
  33575. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  33576. */
  33577. subdivisions, canBeRegenerated, mesh,
  33578. /**
  33579. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33580. */
  33581. side) {
  33582. if (subdivisions === void 0) { subdivisions = 1; }
  33583. if (mesh === void 0) { mesh = null; }
  33584. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33585. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33586. _this.height = height;
  33587. _this.diameterTop = diameterTop;
  33588. _this.diameterBottom = diameterBottom;
  33589. _this.tessellation = tessellation;
  33590. _this.subdivisions = subdivisions;
  33591. _this.side = side;
  33592. return _this;
  33593. }
  33594. CylinderGeometry.prototype._regenerateVertexData = function () {
  33595. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33596. };
  33597. CylinderGeometry.prototype.copy = function (id) {
  33598. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33599. };
  33600. CylinderGeometry.prototype.serialize = function () {
  33601. var serializationObject = _super.prototype.serialize.call(this);
  33602. serializationObject.height = this.height;
  33603. serializationObject.diameterTop = this.diameterTop;
  33604. serializationObject.diameterBottom = this.diameterBottom;
  33605. serializationObject.tessellation = this.tessellation;
  33606. return serializationObject;
  33607. };
  33608. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  33609. if (scene.getGeometryByID(parsedCylinder.id)) {
  33610. return null; // null since geometry could be something else than a cylinder...
  33611. }
  33612. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33613. if (BABYLON.Tags) {
  33614. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33615. }
  33616. scene.pushGeometry(cylinder, true);
  33617. return cylinder;
  33618. };
  33619. return CylinderGeometry;
  33620. }(_PrimitiveGeometry));
  33621. BABYLON.CylinderGeometry = CylinderGeometry;
  33622. /**
  33623. * Creates a new torus geometry
  33624. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  33625. */
  33626. var TorusGeometry = /** @class */ (function (_super) {
  33627. __extends(TorusGeometry, _super);
  33628. /**
  33629. * Creates a new torus geometry
  33630. * @param id defines the unique ID of the geometry
  33631. * @param scene defines the hosting scene
  33632. * @param diameter defines the diameter of the torus
  33633. * @param thickness defines the thickness of the torus (ie. internal diameter)
  33634. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  33635. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33636. * @param mesh defines the hosting mesh (can be null)
  33637. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33638. */
  33639. function TorusGeometry(id, scene,
  33640. /**
  33641. * Defines the diameter of the torus
  33642. */
  33643. diameter,
  33644. /**
  33645. * Defines the thickness of the torus (ie. internal diameter)
  33646. */
  33647. thickness,
  33648. /**
  33649. * Defines the tesselation factor to apply to the torus
  33650. */
  33651. tessellation, canBeRegenerated, mesh,
  33652. /**
  33653. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33654. */
  33655. side) {
  33656. if (mesh === void 0) { mesh = null; }
  33657. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33658. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33659. _this.diameter = diameter;
  33660. _this.thickness = thickness;
  33661. _this.tessellation = tessellation;
  33662. _this.side = side;
  33663. return _this;
  33664. }
  33665. TorusGeometry.prototype._regenerateVertexData = function () {
  33666. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33667. };
  33668. TorusGeometry.prototype.copy = function (id) {
  33669. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33670. };
  33671. TorusGeometry.prototype.serialize = function () {
  33672. var serializationObject = _super.prototype.serialize.call(this);
  33673. serializationObject.diameter = this.diameter;
  33674. serializationObject.thickness = this.thickness;
  33675. serializationObject.tessellation = this.tessellation;
  33676. return serializationObject;
  33677. };
  33678. TorusGeometry.Parse = function (parsedTorus, scene) {
  33679. if (scene.getGeometryByID(parsedTorus.id)) {
  33680. return null; // null since geometry could be something else than a torus...
  33681. }
  33682. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33683. if (BABYLON.Tags) {
  33684. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33685. }
  33686. scene.pushGeometry(torus, true);
  33687. return torus;
  33688. };
  33689. return TorusGeometry;
  33690. }(_PrimitiveGeometry));
  33691. BABYLON.TorusGeometry = TorusGeometry;
  33692. /**
  33693. * Creates a new ground geometry
  33694. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  33695. */
  33696. var GroundGeometry = /** @class */ (function (_super) {
  33697. __extends(GroundGeometry, _super);
  33698. /**
  33699. * Creates a new ground geometry
  33700. * @param id defines the unique ID of the geometry
  33701. * @param scene defines the hosting scene
  33702. * @param width defines the width of the ground
  33703. * @param height defines the height of the ground
  33704. * @param subdivisions defines the subdivisions to apply to the ground
  33705. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33706. * @param mesh defines the hosting mesh (can be null)
  33707. */
  33708. function GroundGeometry(id, scene,
  33709. /**
  33710. * Defines the width of the ground
  33711. */
  33712. width,
  33713. /**
  33714. * Defines the height of the ground
  33715. */
  33716. height,
  33717. /**
  33718. * Defines the subdivisions to apply to the ground
  33719. */
  33720. subdivisions, canBeRegenerated, mesh) {
  33721. if (mesh === void 0) { mesh = null; }
  33722. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33723. _this.width = width;
  33724. _this.height = height;
  33725. _this.subdivisions = subdivisions;
  33726. return _this;
  33727. }
  33728. GroundGeometry.prototype._regenerateVertexData = function () {
  33729. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33730. };
  33731. GroundGeometry.prototype.copy = function (id) {
  33732. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33733. };
  33734. GroundGeometry.prototype.serialize = function () {
  33735. var serializationObject = _super.prototype.serialize.call(this);
  33736. serializationObject.width = this.width;
  33737. serializationObject.height = this.height;
  33738. serializationObject.subdivisions = this.subdivisions;
  33739. return serializationObject;
  33740. };
  33741. GroundGeometry.Parse = function (parsedGround, scene) {
  33742. if (scene.getGeometryByID(parsedGround.id)) {
  33743. return null; // null since geometry could be something else than a ground...
  33744. }
  33745. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33746. if (BABYLON.Tags) {
  33747. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33748. }
  33749. scene.pushGeometry(ground, true);
  33750. return ground;
  33751. };
  33752. return GroundGeometry;
  33753. }(_PrimitiveGeometry));
  33754. BABYLON.GroundGeometry = GroundGeometry;
  33755. /**
  33756. * Creates a tiled ground geometry
  33757. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  33758. */
  33759. var TiledGroundGeometry = /** @class */ (function (_super) {
  33760. __extends(TiledGroundGeometry, _super);
  33761. /**
  33762. * Creates a tiled ground geometry
  33763. * @param id defines the unique ID of the geometry
  33764. * @param scene defines the hosting scene
  33765. * @param xmin defines the minimum value on X axis
  33766. * @param zmin defines the minimum value on Z axis
  33767. * @param xmax defines the maximum value on X axis
  33768. * @param zmax defines the maximum value on Z axis
  33769. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  33770. * @param precision defines the precision to use when computing the tiles
  33771. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33772. * @param mesh defines the hosting mesh (can be null)
  33773. */
  33774. function TiledGroundGeometry(id, scene,
  33775. /**
  33776. * Defines the minimum value on X axis
  33777. */
  33778. xmin,
  33779. /**
  33780. * Defines the minimum value on Z axis
  33781. */
  33782. zmin,
  33783. /**
  33784. * Defines the maximum value on X axis
  33785. */
  33786. xmax,
  33787. /**
  33788. * Defines the maximum value on Z axis
  33789. */
  33790. zmax,
  33791. /**
  33792. * Defines the subdivisions to apply to the ground
  33793. */
  33794. subdivisions,
  33795. /**
  33796. * Defines the precision to use when computing the tiles
  33797. */
  33798. precision, canBeRegenerated, mesh) {
  33799. if (mesh === void 0) { mesh = null; }
  33800. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33801. _this.xmin = xmin;
  33802. _this.zmin = zmin;
  33803. _this.xmax = xmax;
  33804. _this.zmax = zmax;
  33805. _this.subdivisions = subdivisions;
  33806. _this.precision = precision;
  33807. return _this;
  33808. }
  33809. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  33810. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33811. };
  33812. TiledGroundGeometry.prototype.copy = function (id) {
  33813. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33814. };
  33815. return TiledGroundGeometry;
  33816. }(_PrimitiveGeometry));
  33817. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  33818. /**
  33819. * Creates a plane geometry
  33820. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  33821. */
  33822. var PlaneGeometry = /** @class */ (function (_super) {
  33823. __extends(PlaneGeometry, _super);
  33824. /**
  33825. * Creates a plane geometry
  33826. * @param id defines the unique ID of the geometry
  33827. * @param scene defines the hosting scene
  33828. * @param size defines the size of the plane (width === height)
  33829. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33830. * @param mesh defines the hosting mesh (can be null)
  33831. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33832. */
  33833. function PlaneGeometry(id, scene,
  33834. /**
  33835. * Defines the size of the plane (width === height)
  33836. */
  33837. size, canBeRegenerated, mesh,
  33838. /**
  33839. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33840. */
  33841. side) {
  33842. if (mesh === void 0) { mesh = null; }
  33843. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33844. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33845. _this.size = size;
  33846. _this.side = side;
  33847. return _this;
  33848. }
  33849. PlaneGeometry.prototype._regenerateVertexData = function () {
  33850. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33851. };
  33852. PlaneGeometry.prototype.copy = function (id) {
  33853. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33854. };
  33855. PlaneGeometry.prototype.serialize = function () {
  33856. var serializationObject = _super.prototype.serialize.call(this);
  33857. serializationObject.size = this.size;
  33858. return serializationObject;
  33859. };
  33860. PlaneGeometry.Parse = function (parsedPlane, scene) {
  33861. if (scene.getGeometryByID(parsedPlane.id)) {
  33862. return null; // null since geometry could be something else than a ground...
  33863. }
  33864. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33865. if (BABYLON.Tags) {
  33866. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33867. }
  33868. scene.pushGeometry(plane, true);
  33869. return plane;
  33870. };
  33871. return PlaneGeometry;
  33872. }(_PrimitiveGeometry));
  33873. BABYLON.PlaneGeometry = PlaneGeometry;
  33874. /**
  33875. * Creates a torus knot geometry
  33876. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  33877. */
  33878. var TorusKnotGeometry = /** @class */ (function (_super) {
  33879. __extends(TorusKnotGeometry, _super);
  33880. /**
  33881. * Creates a torus knot geometry
  33882. * @param id defines the unique ID of the geometry
  33883. * @param scene defines the hosting scene
  33884. * @param radius defines the radius of the torus knot
  33885. * @param tube defines the thickness of the torus knot tube
  33886. * @param radialSegments defines the number of radial segments
  33887. * @param tubularSegments defines the number of tubular segments
  33888. * @param p defines the first number of windings
  33889. * @param q defines the second number of windings
  33890. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33891. * @param mesh defines the hosting mesh (can be null)
  33892. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33893. */
  33894. function TorusKnotGeometry(id, scene,
  33895. /**
  33896. * Defines the radius of the torus knot
  33897. */
  33898. radius,
  33899. /**
  33900. * Defines the thickness of the torus knot tube
  33901. */
  33902. tube,
  33903. /**
  33904. * Defines the number of radial segments
  33905. */
  33906. radialSegments,
  33907. /**
  33908. * Defines the number of tubular segments
  33909. */
  33910. tubularSegments,
  33911. /**
  33912. * Defines the first number of windings
  33913. */
  33914. p,
  33915. /**
  33916. * Defines the second number of windings
  33917. */
  33918. q, canBeRegenerated, mesh,
  33919. /**
  33920. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33921. */
  33922. side) {
  33923. if (mesh === void 0) { mesh = null; }
  33924. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33925. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33926. _this.radius = radius;
  33927. _this.tube = tube;
  33928. _this.radialSegments = radialSegments;
  33929. _this.tubularSegments = tubularSegments;
  33930. _this.p = p;
  33931. _this.q = q;
  33932. _this.side = side;
  33933. return _this;
  33934. }
  33935. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  33936. 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 });
  33937. };
  33938. TorusKnotGeometry.prototype.copy = function (id) {
  33939. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33940. };
  33941. TorusKnotGeometry.prototype.serialize = function () {
  33942. var serializationObject = _super.prototype.serialize.call(this);
  33943. serializationObject.radius = this.radius;
  33944. serializationObject.tube = this.tube;
  33945. serializationObject.radialSegments = this.radialSegments;
  33946. serializationObject.tubularSegments = this.tubularSegments;
  33947. serializationObject.p = this.p;
  33948. serializationObject.q = this.q;
  33949. return serializationObject;
  33950. };
  33951. ;
  33952. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  33953. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  33954. return null; // null since geometry could be something else than a ground...
  33955. }
  33956. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  33957. if (BABYLON.Tags) {
  33958. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  33959. }
  33960. scene.pushGeometry(torusKnot, true);
  33961. return torusKnot;
  33962. };
  33963. return TorusKnotGeometry;
  33964. }(_PrimitiveGeometry));
  33965. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  33966. //}
  33967. })(BABYLON || (BABYLON = {}));
  33968. //# sourceMappingURL=babylon.geometry.js.map
  33969. var BABYLON;
  33970. (function (BABYLON) {
  33971. var PostProcessManager = /** @class */ (function () {
  33972. function PostProcessManager(scene) {
  33973. this._vertexBuffers = {};
  33974. this._scene = scene;
  33975. }
  33976. PostProcessManager.prototype._prepareBuffers = function () {
  33977. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  33978. return;
  33979. }
  33980. // VBO
  33981. var vertices = [];
  33982. vertices.push(1, 1);
  33983. vertices.push(-1, 1);
  33984. vertices.push(-1, -1);
  33985. vertices.push(1, -1);
  33986. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  33987. this._buildIndexBuffer();
  33988. };
  33989. PostProcessManager.prototype._buildIndexBuffer = function () {
  33990. // Indices
  33991. var indices = [];
  33992. indices.push(0);
  33993. indices.push(1);
  33994. indices.push(2);
  33995. indices.push(0);
  33996. indices.push(2);
  33997. indices.push(3);
  33998. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  33999. };
  34000. PostProcessManager.prototype._rebuild = function () {
  34001. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34002. if (!vb) {
  34003. return;
  34004. }
  34005. vb._rebuild();
  34006. this._buildIndexBuffer();
  34007. };
  34008. // Methods
  34009. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34010. if (sourceTexture === void 0) { sourceTexture = null; }
  34011. if (postProcesses === void 0) { postProcesses = null; }
  34012. var camera = this._scene.activeCamera;
  34013. if (!camera) {
  34014. return false;
  34015. }
  34016. var postProcesses = postProcesses || camera._postProcesses;
  34017. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34018. return false;
  34019. }
  34020. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34021. return true;
  34022. };
  34023. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34024. if (targetTexture === void 0) { targetTexture = null; }
  34025. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34026. var engine = this._scene.getEngine();
  34027. for (var index = 0; index < postProcesses.length; index++) {
  34028. if (index < postProcesses.length - 1) {
  34029. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34030. }
  34031. else {
  34032. if (targetTexture) {
  34033. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34034. }
  34035. else {
  34036. engine.restoreDefaultFramebuffer();
  34037. }
  34038. }
  34039. var pp = postProcesses[index];
  34040. var effect = pp.apply();
  34041. if (effect) {
  34042. pp.onBeforeRenderObservable.notifyObservers(effect);
  34043. // VBOs
  34044. this._prepareBuffers();
  34045. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34046. // Draw order
  34047. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34048. pp.onAfterRenderObservable.notifyObservers(effect);
  34049. }
  34050. }
  34051. // Restore depth buffer
  34052. engine.setDepthBuffer(true);
  34053. engine.setDepthWrite(true);
  34054. };
  34055. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34056. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34057. var camera = this._scene.activeCamera;
  34058. if (!camera) {
  34059. return;
  34060. }
  34061. postProcesses = postProcesses || camera._postProcesses;
  34062. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34063. return;
  34064. }
  34065. var engine = this._scene.getEngine();
  34066. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34067. if (index < len - 1) {
  34068. postProcesses[index + 1].activate(camera, targetTexture);
  34069. }
  34070. else {
  34071. if (targetTexture) {
  34072. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34073. }
  34074. else {
  34075. engine.restoreDefaultFramebuffer();
  34076. }
  34077. }
  34078. if (doNotPresent) {
  34079. break;
  34080. }
  34081. var pp = postProcesses[index];
  34082. var effect = pp.apply();
  34083. if (effect) {
  34084. pp.onBeforeRenderObservable.notifyObservers(effect);
  34085. // VBOs
  34086. this._prepareBuffers();
  34087. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34088. // Draw order
  34089. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34090. pp.onAfterRenderObservable.notifyObservers(effect);
  34091. }
  34092. }
  34093. // Restore states
  34094. engine.setDepthBuffer(true);
  34095. engine.setDepthWrite(true);
  34096. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34097. };
  34098. PostProcessManager.prototype.dispose = function () {
  34099. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34100. if (buffer) {
  34101. buffer.dispose();
  34102. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34103. }
  34104. if (this._indexBuffer) {
  34105. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34106. this._indexBuffer = null;
  34107. }
  34108. };
  34109. return PostProcessManager;
  34110. }());
  34111. BABYLON.PostProcessManager = PostProcessManager;
  34112. })(BABYLON || (BABYLON = {}));
  34113. //# sourceMappingURL=babylon.postProcessManager.js.map
  34114. var BABYLON;
  34115. (function (BABYLON) {
  34116. /**
  34117. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34118. */
  34119. var PerformanceMonitor = /** @class */ (function () {
  34120. /**
  34121. * constructor
  34122. * @param frameSampleSize The number of samples required to saturate the sliding window
  34123. */
  34124. function PerformanceMonitor(frameSampleSize) {
  34125. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34126. this._enabled = true;
  34127. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34128. }
  34129. /**
  34130. * Samples current frame
  34131. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34132. */
  34133. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34134. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34135. if (!this._enabled)
  34136. return;
  34137. if (this._lastFrameTimeMs != null) {
  34138. var dt = timeMs - this._lastFrameTimeMs;
  34139. this._rollingFrameTime.add(dt);
  34140. }
  34141. this._lastFrameTimeMs = timeMs;
  34142. };
  34143. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34144. /**
  34145. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34146. * @return Average frame time in milliseconds
  34147. */
  34148. get: function () {
  34149. return this._rollingFrameTime.average;
  34150. },
  34151. enumerable: true,
  34152. configurable: true
  34153. });
  34154. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34155. /**
  34156. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34157. * @return Frame time variance in milliseconds squared
  34158. */
  34159. get: function () {
  34160. return this._rollingFrameTime.variance;
  34161. },
  34162. enumerable: true,
  34163. configurable: true
  34164. });
  34165. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34166. /**
  34167. * Returns the frame time of the most recent frame
  34168. * @return Frame time in milliseconds
  34169. */
  34170. get: function () {
  34171. return this._rollingFrameTime.history(0);
  34172. },
  34173. enumerable: true,
  34174. configurable: true
  34175. });
  34176. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34177. /**
  34178. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34179. * @return Framerate in frames per second
  34180. */
  34181. get: function () {
  34182. return 1000.0 / this._rollingFrameTime.average;
  34183. },
  34184. enumerable: true,
  34185. configurable: true
  34186. });
  34187. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34188. /**
  34189. * Returns the average framerate in frames per second using the most recent frame time
  34190. * @return Framerate in frames per second
  34191. */
  34192. get: function () {
  34193. var history = this._rollingFrameTime.history(0);
  34194. if (history === 0) {
  34195. return 0;
  34196. }
  34197. return 1000.0 / history;
  34198. },
  34199. enumerable: true,
  34200. configurable: true
  34201. });
  34202. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34203. /**
  34204. * Returns true if enough samples have been taken to completely fill the sliding window
  34205. * @return true if saturated
  34206. */
  34207. get: function () {
  34208. return this._rollingFrameTime.isSaturated();
  34209. },
  34210. enumerable: true,
  34211. configurable: true
  34212. });
  34213. /**
  34214. * Enables contributions to the sliding window sample set
  34215. */
  34216. PerformanceMonitor.prototype.enable = function () {
  34217. this._enabled = true;
  34218. };
  34219. /**
  34220. * Disables contributions to the sliding window sample set
  34221. * Samples will not be interpolated over the disabled period
  34222. */
  34223. PerformanceMonitor.prototype.disable = function () {
  34224. this._enabled = false;
  34225. //clear last sample to avoid interpolating over the disabled period when next enabled
  34226. this._lastFrameTimeMs = null;
  34227. };
  34228. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34229. /**
  34230. * Returns true if sampling is enabled
  34231. * @return true if enabled
  34232. */
  34233. get: function () {
  34234. return this._enabled;
  34235. },
  34236. enumerable: true,
  34237. configurable: true
  34238. });
  34239. /**
  34240. * Resets performance monitor
  34241. */
  34242. PerformanceMonitor.prototype.reset = function () {
  34243. //clear last sample to avoid interpolating over the disabled period when next enabled
  34244. this._lastFrameTimeMs = null;
  34245. //wipe record
  34246. this._rollingFrameTime.reset();
  34247. };
  34248. return PerformanceMonitor;
  34249. }());
  34250. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34251. /**
  34252. * RollingAverage
  34253. *
  34254. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34255. */
  34256. var RollingAverage = /** @class */ (function () {
  34257. /**
  34258. * constructor
  34259. * @param length The number of samples required to saturate the sliding window
  34260. */
  34261. function RollingAverage(length) {
  34262. this._samples = new Array(length);
  34263. this.reset();
  34264. }
  34265. /**
  34266. * Adds a sample to the sample set
  34267. * @param v The sample value
  34268. */
  34269. RollingAverage.prototype.add = function (v) {
  34270. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34271. var delta;
  34272. //we need to check if we've already wrapped round
  34273. if (this.isSaturated()) {
  34274. //remove bottom of stack from mean
  34275. var bottomValue = this._samples[this._pos];
  34276. delta = bottomValue - this.average;
  34277. this.average -= delta / (this._sampleCount - 1);
  34278. this._m2 -= delta * (bottomValue - this.average);
  34279. }
  34280. else {
  34281. this._sampleCount++;
  34282. }
  34283. //add new value to mean
  34284. delta = v - this.average;
  34285. this.average += delta / (this._sampleCount);
  34286. this._m2 += delta * (v - this.average);
  34287. //set the new variance
  34288. this.variance = this._m2 / (this._sampleCount - 1);
  34289. this._samples[this._pos] = v;
  34290. this._pos++;
  34291. this._pos %= this._samples.length; //positive wrap around
  34292. };
  34293. /**
  34294. * Returns previously added values or null if outside of history or outside the sliding window domain
  34295. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34296. * @return Value previously recorded with add() or null if outside of range
  34297. */
  34298. RollingAverage.prototype.history = function (i) {
  34299. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34300. return 0;
  34301. }
  34302. var i0 = this._wrapPosition(this._pos - 1.0);
  34303. return this._samples[this._wrapPosition(i0 - i)];
  34304. };
  34305. /**
  34306. * Returns true if enough samples have been taken to completely fill the sliding window
  34307. * @return true if sample-set saturated
  34308. */
  34309. RollingAverage.prototype.isSaturated = function () {
  34310. return this._sampleCount >= this._samples.length;
  34311. };
  34312. /**
  34313. * Resets the rolling average (equivalent to 0 samples taken so far)
  34314. */
  34315. RollingAverage.prototype.reset = function () {
  34316. this.average = 0;
  34317. this.variance = 0;
  34318. this._sampleCount = 0;
  34319. this._pos = 0;
  34320. this._m2 = 0;
  34321. };
  34322. /**
  34323. * Wraps a value around the sample range boundaries
  34324. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34325. * @return Wrapped position in sample range
  34326. */
  34327. RollingAverage.prototype._wrapPosition = function (i) {
  34328. var max = this._samples.length;
  34329. return ((i % max) + max) % max;
  34330. };
  34331. return RollingAverage;
  34332. }());
  34333. BABYLON.RollingAverage = RollingAverage;
  34334. })(BABYLON || (BABYLON = {}));
  34335. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34336. var BABYLON;
  34337. (function (BABYLON) {
  34338. /**
  34339. * This groups together the common properties used for image processing either in direct forward pass
  34340. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34341. * or not.
  34342. */
  34343. var ImageProcessingConfiguration = /** @class */ (function () {
  34344. function ImageProcessingConfiguration() {
  34345. /**
  34346. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34347. */
  34348. this.colorCurves = new BABYLON.ColorCurves();
  34349. this._colorCurvesEnabled = false;
  34350. this._colorGradingEnabled = false;
  34351. this._colorGradingWithGreenDepth = true;
  34352. this._colorGradingBGR = true;
  34353. this._exposure = 1.0;
  34354. this._toneMappingEnabled = false;
  34355. this._contrast = 1.0;
  34356. /**
  34357. * Vignette stretch size.
  34358. */
  34359. this.vignetteStretch = 0;
  34360. /**
  34361. * Vignette centre X Offset.
  34362. */
  34363. this.vignetteCentreX = 0;
  34364. /**
  34365. * Vignette centre Y Offset.
  34366. */
  34367. this.vignetteCentreY = 0;
  34368. /**
  34369. * Vignette weight or intensity of the vignette effect.
  34370. */
  34371. this.vignetteWeight = 1.5;
  34372. /**
  34373. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34374. * if vignetteEnabled is set to true.
  34375. */
  34376. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34377. /**
  34378. * Camera field of view used by the Vignette effect.
  34379. */
  34380. this.vignetteCameraFov = 0.5;
  34381. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34382. this._vignetteEnabled = false;
  34383. this._applyByPostProcess = false;
  34384. this._isEnabled = true;
  34385. /**
  34386. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34387. * @type {BABYLON.Observable}
  34388. */
  34389. this.onUpdateParameters = new BABYLON.Observable();
  34390. }
  34391. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34392. /**
  34393. * Gets wether the color curves effect is enabled.
  34394. */
  34395. get: function () {
  34396. return this._colorCurvesEnabled;
  34397. },
  34398. /**
  34399. * Sets wether the color curves effect is enabled.
  34400. */
  34401. set: function (value) {
  34402. if (this._colorCurvesEnabled === value) {
  34403. return;
  34404. }
  34405. this._colorCurvesEnabled = value;
  34406. this._updateParameters();
  34407. },
  34408. enumerable: true,
  34409. configurable: true
  34410. });
  34411. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34412. /**
  34413. * Gets wether the color grading effect is enabled.
  34414. */
  34415. get: function () {
  34416. return this._colorGradingEnabled;
  34417. },
  34418. /**
  34419. * Sets wether the color grading effect is enabled.
  34420. */
  34421. set: function (value) {
  34422. if (this._colorGradingEnabled === value) {
  34423. return;
  34424. }
  34425. this._colorGradingEnabled = value;
  34426. this._updateParameters();
  34427. },
  34428. enumerable: true,
  34429. configurable: true
  34430. });
  34431. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34432. /**
  34433. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34434. */
  34435. get: function () {
  34436. return this._colorGradingWithGreenDepth;
  34437. },
  34438. /**
  34439. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34440. */
  34441. set: function (value) {
  34442. if (this._colorGradingWithGreenDepth === value) {
  34443. return;
  34444. }
  34445. this._colorGradingWithGreenDepth = value;
  34446. this._updateParameters();
  34447. },
  34448. enumerable: true,
  34449. configurable: true
  34450. });
  34451. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34452. /**
  34453. * Gets wether the color grading texture contains BGR values.
  34454. */
  34455. get: function () {
  34456. return this._colorGradingBGR;
  34457. },
  34458. /**
  34459. * Sets wether the color grading texture contains BGR values.
  34460. */
  34461. set: function (value) {
  34462. if (this._colorGradingBGR === value) {
  34463. return;
  34464. }
  34465. this._colorGradingBGR = value;
  34466. this._updateParameters();
  34467. },
  34468. enumerable: true,
  34469. configurable: true
  34470. });
  34471. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  34472. /**
  34473. * Gets the Exposure used in the effect.
  34474. */
  34475. get: function () {
  34476. return this._exposure;
  34477. },
  34478. /**
  34479. * Sets the Exposure used in the effect.
  34480. */
  34481. set: function (value) {
  34482. if (this._exposure === value) {
  34483. return;
  34484. }
  34485. this._exposure = value;
  34486. this._updateParameters();
  34487. },
  34488. enumerable: true,
  34489. configurable: true
  34490. });
  34491. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  34492. /**
  34493. * Gets wether the tone mapping effect is enabled.
  34494. */
  34495. get: function () {
  34496. return this._toneMappingEnabled;
  34497. },
  34498. /**
  34499. * Sets wether the tone mapping effect is enabled.
  34500. */
  34501. set: function (value) {
  34502. if (this._toneMappingEnabled === value) {
  34503. return;
  34504. }
  34505. this._toneMappingEnabled = value;
  34506. this._updateParameters();
  34507. },
  34508. enumerable: true,
  34509. configurable: true
  34510. });
  34511. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  34512. /**
  34513. * Gets the contrast used in the effect.
  34514. */
  34515. get: function () {
  34516. return this._contrast;
  34517. },
  34518. /**
  34519. * Sets the contrast used in the effect.
  34520. */
  34521. set: function (value) {
  34522. if (this._contrast === value) {
  34523. return;
  34524. }
  34525. this._contrast = value;
  34526. this._updateParameters();
  34527. },
  34528. enumerable: true,
  34529. configurable: true
  34530. });
  34531. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  34532. /**
  34533. * Gets the vignette blend mode allowing different kind of effect.
  34534. */
  34535. get: function () {
  34536. return this._vignetteBlendMode;
  34537. },
  34538. /**
  34539. * Sets the vignette blend mode allowing different kind of effect.
  34540. */
  34541. set: function (value) {
  34542. if (this._vignetteBlendMode === value) {
  34543. return;
  34544. }
  34545. this._vignetteBlendMode = value;
  34546. this._updateParameters();
  34547. },
  34548. enumerable: true,
  34549. configurable: true
  34550. });
  34551. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  34552. /**
  34553. * Gets wether the vignette effect is enabled.
  34554. */
  34555. get: function () {
  34556. return this._vignetteEnabled;
  34557. },
  34558. /**
  34559. * Sets wether the vignette effect is enabled.
  34560. */
  34561. set: function (value) {
  34562. if (this._vignetteEnabled === value) {
  34563. return;
  34564. }
  34565. this._vignetteEnabled = value;
  34566. this._updateParameters();
  34567. },
  34568. enumerable: true,
  34569. configurable: true
  34570. });
  34571. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  34572. /**
  34573. * Gets wether the image processing is applied through a post process or not.
  34574. */
  34575. get: function () {
  34576. return this._applyByPostProcess;
  34577. },
  34578. /**
  34579. * Sets wether the image processing is applied through a post process or not.
  34580. */
  34581. set: function (value) {
  34582. if (this._applyByPostProcess === value) {
  34583. return;
  34584. }
  34585. this._applyByPostProcess = value;
  34586. this._updateParameters();
  34587. },
  34588. enumerable: true,
  34589. configurable: true
  34590. });
  34591. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  34592. /**
  34593. * Gets wether the image processing is enabled or not.
  34594. */
  34595. get: function () {
  34596. return this._isEnabled;
  34597. },
  34598. /**
  34599. * Sets wether the image processing is enabled or not.
  34600. */
  34601. set: function (value) {
  34602. if (this._isEnabled === value) {
  34603. return;
  34604. }
  34605. this._isEnabled = value;
  34606. this._updateParameters();
  34607. },
  34608. enumerable: true,
  34609. configurable: true
  34610. });
  34611. /**
  34612. * Method called each time the image processing information changes requires to recompile the effect.
  34613. */
  34614. ImageProcessingConfiguration.prototype._updateParameters = function () {
  34615. this.onUpdateParameters.notifyObservers(this);
  34616. };
  34617. ImageProcessingConfiguration.prototype.getClassName = function () {
  34618. return "ImageProcessingConfiguration";
  34619. };
  34620. /**
  34621. * Prepare the list of uniforms associated with the Image Processing effects.
  34622. * @param uniformsList The list of uniforms used in the effect
  34623. * @param defines the list of defines currently in use
  34624. */
  34625. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  34626. if (defines.EXPOSURE) {
  34627. uniforms.push("exposureLinear");
  34628. }
  34629. if (defines.CONTRAST) {
  34630. uniforms.push("contrast");
  34631. }
  34632. if (defines.COLORGRADING) {
  34633. uniforms.push("colorTransformSettings");
  34634. }
  34635. if (defines.VIGNETTE) {
  34636. uniforms.push("vInverseScreenSize");
  34637. uniforms.push("vignetteSettings1");
  34638. uniforms.push("vignetteSettings2");
  34639. }
  34640. if (defines.COLORCURVES) {
  34641. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  34642. }
  34643. };
  34644. /**
  34645. * Prepare the list of samplers associated with the Image Processing effects.
  34646. * @param uniformsList The list of uniforms used in the effect
  34647. * @param defines the list of defines currently in use
  34648. */
  34649. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  34650. if (defines.COLORGRADING) {
  34651. samplersList.push("txColorTransform");
  34652. }
  34653. };
  34654. /**
  34655. * Prepare the list of defines associated to the shader.
  34656. * @param defines the list of defines to complete
  34657. */
  34658. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  34659. if (forPostProcess === void 0) { forPostProcess = false; }
  34660. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  34661. defines.VIGNETTE = false;
  34662. defines.TONEMAPPING = false;
  34663. defines.CONTRAST = false;
  34664. defines.EXPOSURE = false;
  34665. defines.COLORCURVES = false;
  34666. defines.COLORGRADING = false;
  34667. defines.COLORGRADING3D = false;
  34668. defines.IMAGEPROCESSING = false;
  34669. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  34670. return;
  34671. }
  34672. defines.VIGNETTE = this.vignetteEnabled;
  34673. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  34674. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  34675. defines.TONEMAPPING = this.toneMappingEnabled;
  34676. defines.CONTRAST = (this.contrast !== 1.0);
  34677. defines.EXPOSURE = (this.exposure !== 1.0);
  34678. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  34679. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  34680. if (defines.COLORGRADING) {
  34681. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  34682. }
  34683. else {
  34684. defines.COLORGRADING3D = false;
  34685. }
  34686. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  34687. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  34688. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  34689. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  34690. };
  34691. /**
  34692. * Returns true if all the image processing information are ready.
  34693. */
  34694. ImageProcessingConfiguration.prototype.isReady = function () {
  34695. // Color Grading texure can not be none blocking.
  34696. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  34697. };
  34698. /**
  34699. * Binds the image processing to the shader.
  34700. * @param effect The effect to bind to
  34701. */
  34702. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  34703. if (aspectRatio === void 0) { aspectRatio = 1; }
  34704. // Color Curves
  34705. if (this._colorCurvesEnabled && this.colorCurves) {
  34706. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  34707. }
  34708. // Vignette
  34709. if (this._vignetteEnabled) {
  34710. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  34711. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  34712. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  34713. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  34714. var vignetteScaleX = vignetteScaleY * aspectRatio;
  34715. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  34716. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  34717. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  34718. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  34719. var vignettePower = -2.0 * this.vignetteWeight;
  34720. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  34721. }
  34722. // Exposure
  34723. effect.setFloat("exposureLinear", this.exposure);
  34724. // Contrast
  34725. effect.setFloat("contrast", this.contrast);
  34726. // Color transform settings
  34727. if (this.colorGradingTexture) {
  34728. effect.setTexture("txColorTransform", this.colorGradingTexture);
  34729. var textureSize = this.colorGradingTexture.getSize().height;
  34730. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  34731. 0.5 / textureSize, // textureOffset
  34732. textureSize, // textureSize
  34733. this.colorGradingTexture.level // weight
  34734. );
  34735. }
  34736. };
  34737. /**
  34738. * Clones the current image processing instance.
  34739. * @return The cloned image processing
  34740. */
  34741. ImageProcessingConfiguration.prototype.clone = function () {
  34742. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  34743. };
  34744. /**
  34745. * Serializes the current image processing instance to a json representation.
  34746. * @return a JSON representation
  34747. */
  34748. ImageProcessingConfiguration.prototype.serialize = function () {
  34749. return BABYLON.SerializationHelper.Serialize(this);
  34750. };
  34751. /**
  34752. * Parses the image processing from a json representation.
  34753. * @param source the JSON source to parse
  34754. * @return The parsed image processing
  34755. */
  34756. ImageProcessingConfiguration.Parse = function (source) {
  34757. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  34758. };
  34759. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  34760. /**
  34761. * Used to apply the vignette as a mix with the pixel color.
  34762. */
  34763. get: function () {
  34764. return this._VIGNETTEMODE_MULTIPLY;
  34765. },
  34766. enumerable: true,
  34767. configurable: true
  34768. });
  34769. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  34770. /**
  34771. * Used to apply the vignette as a replacement of the pixel color.
  34772. */
  34773. get: function () {
  34774. return this._VIGNETTEMODE_OPAQUE;
  34775. },
  34776. enumerable: true,
  34777. configurable: true
  34778. });
  34779. // Static constants associated to the image processing.
  34780. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  34781. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  34782. __decorate([
  34783. BABYLON.serializeAsColorCurves()
  34784. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  34785. __decorate([
  34786. BABYLON.serialize()
  34787. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  34788. __decorate([
  34789. BABYLON.serializeAsTexture()
  34790. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  34791. __decorate([
  34792. BABYLON.serialize()
  34793. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  34794. __decorate([
  34795. BABYLON.serialize()
  34796. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  34797. __decorate([
  34798. BABYLON.serialize()
  34799. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  34800. __decorate([
  34801. BABYLON.serialize()
  34802. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  34803. __decorate([
  34804. BABYLON.serialize()
  34805. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  34806. __decorate([
  34807. BABYLON.serialize()
  34808. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  34809. __decorate([
  34810. BABYLON.serialize()
  34811. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  34812. __decorate([
  34813. BABYLON.serialize()
  34814. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  34815. __decorate([
  34816. BABYLON.serialize()
  34817. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  34818. __decorate([
  34819. BABYLON.serialize()
  34820. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  34821. __decorate([
  34822. BABYLON.serializeAsColor4()
  34823. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  34824. __decorate([
  34825. BABYLON.serialize()
  34826. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  34827. __decorate([
  34828. BABYLON.serialize()
  34829. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  34830. __decorate([
  34831. BABYLON.serialize()
  34832. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  34833. __decorate([
  34834. BABYLON.serialize()
  34835. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  34836. __decorate([
  34837. BABYLON.serialize()
  34838. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  34839. return ImageProcessingConfiguration;
  34840. }());
  34841. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  34842. })(BABYLON || (BABYLON = {}));
  34843. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  34844. var BABYLON;
  34845. (function (BABYLON) {
  34846. /**
  34847. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  34848. * It can help converting any input color in a desired output one. This can then be used to create effects
  34849. * from sepia, black and white to sixties or futuristic rendering...
  34850. *
  34851. * The only supported format is currently 3dl.
  34852. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  34853. */
  34854. var ColorGradingTexture = /** @class */ (function (_super) {
  34855. __extends(ColorGradingTexture, _super);
  34856. /**
  34857. * Instantiates a ColorGradingTexture from the following parameters.
  34858. *
  34859. * @param url The location of the color gradind data (currently only supporting 3dl)
  34860. * @param scene The scene the texture will be used in
  34861. */
  34862. function ColorGradingTexture(url, scene) {
  34863. var _this = _super.call(this, scene) || this;
  34864. if (!url) {
  34865. return _this;
  34866. }
  34867. _this._engine = scene.getEngine();
  34868. _this._textureMatrix = BABYLON.Matrix.Identity();
  34869. _this.name = url;
  34870. _this.url = url;
  34871. _this.hasAlpha = false;
  34872. _this.isCube = false;
  34873. _this.is3D = _this._engine.webGLVersion > 1;
  34874. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34875. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34876. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34877. _this.anisotropicFilteringLevel = 1;
  34878. _this._texture = _this._getFromCache(url, true);
  34879. if (!_this._texture) {
  34880. if (!scene.useDelayedTextureLoading) {
  34881. _this.loadTexture();
  34882. }
  34883. else {
  34884. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34885. }
  34886. }
  34887. return _this;
  34888. }
  34889. /**
  34890. * Returns the texture matrix used in most of the material.
  34891. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  34892. */
  34893. ColorGradingTexture.prototype.getTextureMatrix = function () {
  34894. return this._textureMatrix;
  34895. };
  34896. /**
  34897. * Occurs when the file being loaded is a .3dl LUT file.
  34898. */
  34899. ColorGradingTexture.prototype.load3dlTexture = function () {
  34900. var engine = this._engine;
  34901. var texture;
  34902. if (engine.webGLVersion === 1) {
  34903. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34904. }
  34905. else {
  34906. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34907. }
  34908. this._texture = texture;
  34909. var callback = function (text) {
  34910. if (typeof text !== "string") {
  34911. return;
  34912. }
  34913. var data = null;
  34914. var tempData = null;
  34915. var line;
  34916. var lines = text.split('\n');
  34917. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  34918. var maxColor = 0;
  34919. for (var i = 0; i < lines.length; i++) {
  34920. line = lines[i];
  34921. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  34922. continue;
  34923. if (line.indexOf('#') === 0)
  34924. continue;
  34925. var words = line.split(" ");
  34926. if (size === 0) {
  34927. // Number of space + one
  34928. size = words.length;
  34929. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  34930. tempData = new Float32Array(size * size * size * 4);
  34931. continue;
  34932. }
  34933. if (size != 0) {
  34934. var r = Math.max(parseInt(words[0]), 0);
  34935. var g = Math.max(parseInt(words[1]), 0);
  34936. var b = Math.max(parseInt(words[2]), 0);
  34937. maxColor = Math.max(r, maxColor);
  34938. maxColor = Math.max(g, maxColor);
  34939. maxColor = Math.max(b, maxColor);
  34940. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  34941. if (tempData) {
  34942. tempData[pixelStorageIndex + 0] = r;
  34943. tempData[pixelStorageIndex + 1] = g;
  34944. tempData[pixelStorageIndex + 2] = b;
  34945. }
  34946. pixelIndexSlice++;
  34947. if (pixelIndexSlice % size == 0) {
  34948. pixelIndexH++;
  34949. pixelIndexSlice = 0;
  34950. if (pixelIndexH % size == 0) {
  34951. pixelIndexW++;
  34952. pixelIndexH = 0;
  34953. }
  34954. }
  34955. }
  34956. }
  34957. if (tempData && data) {
  34958. for (var i = 0; i < tempData.length; i++) {
  34959. if (i > 0 && (i + 1) % 4 === 0) {
  34960. data[i] = 255;
  34961. }
  34962. else {
  34963. var value = tempData[i];
  34964. data[i] = (value / maxColor * 255);
  34965. }
  34966. }
  34967. }
  34968. if (texture.is3D) {
  34969. texture.updateSize(size, size, size);
  34970. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  34971. }
  34972. else {
  34973. texture.updateSize(size * size, size);
  34974. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  34975. }
  34976. };
  34977. var scene = this.getScene();
  34978. if (scene) {
  34979. scene._loadFile(this.url, callback);
  34980. }
  34981. else {
  34982. this._engine._loadFile(this.url, callback);
  34983. }
  34984. return this._texture;
  34985. };
  34986. /**
  34987. * Starts the loading process of the texture.
  34988. */
  34989. ColorGradingTexture.prototype.loadTexture = function () {
  34990. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  34991. this.load3dlTexture();
  34992. }
  34993. };
  34994. /**
  34995. * Clones the color gradind texture.
  34996. */
  34997. ColorGradingTexture.prototype.clone = function () {
  34998. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  34999. // Base texture
  35000. newTexture.level = this.level;
  35001. return newTexture;
  35002. };
  35003. /**
  35004. * Called during delayed load for textures.
  35005. */
  35006. ColorGradingTexture.prototype.delayLoad = function () {
  35007. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35008. return;
  35009. }
  35010. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35011. this._texture = this._getFromCache(this.url, true);
  35012. if (!this._texture) {
  35013. this.loadTexture();
  35014. }
  35015. };
  35016. /**
  35017. * Parses a color grading texture serialized by Babylon.
  35018. * @param parsedTexture The texture information being parsedTexture
  35019. * @param scene The scene to load the texture in
  35020. * @param rootUrl The root url of the data assets to load
  35021. * @return A color gradind texture
  35022. */
  35023. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35024. var texture = null;
  35025. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35026. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35027. texture.name = parsedTexture.name;
  35028. texture.level = parsedTexture.level;
  35029. }
  35030. return texture;
  35031. };
  35032. /**
  35033. * Serializes the LUT texture to json format.
  35034. */
  35035. ColorGradingTexture.prototype.serialize = function () {
  35036. if (!this.name) {
  35037. return null;
  35038. }
  35039. var serializationObject = {};
  35040. serializationObject.name = this.name;
  35041. serializationObject.level = this.level;
  35042. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35043. return serializationObject;
  35044. };
  35045. /**
  35046. * Empty line regex stored for GC.
  35047. */
  35048. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35049. return ColorGradingTexture;
  35050. }(BABYLON.BaseTexture));
  35051. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35052. })(BABYLON || (BABYLON = {}));
  35053. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35054. var BABYLON;
  35055. (function (BABYLON) {
  35056. /**
  35057. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35058. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35059. * 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;
  35060. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35061. */
  35062. var ColorCurves = /** @class */ (function () {
  35063. function ColorCurves() {
  35064. this._dirty = true;
  35065. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35066. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35067. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35068. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35069. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35070. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35071. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35072. this._globalHue = 30;
  35073. this._globalDensity = 0;
  35074. this._globalSaturation = 0;
  35075. this._globalExposure = 0;
  35076. this._highlightsHue = 30;
  35077. this._highlightsDensity = 0;
  35078. this._highlightsSaturation = 0;
  35079. this._highlightsExposure = 0;
  35080. this._midtonesHue = 30;
  35081. this._midtonesDensity = 0;
  35082. this._midtonesSaturation = 0;
  35083. this._midtonesExposure = 0;
  35084. this._shadowsHue = 30;
  35085. this._shadowsDensity = 0;
  35086. this._shadowsSaturation = 0;
  35087. this._shadowsExposure = 0;
  35088. }
  35089. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35090. /**
  35091. * Gets the global Hue value.
  35092. * 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).
  35093. */
  35094. get: function () {
  35095. return this._globalHue;
  35096. },
  35097. /**
  35098. * Sets the global Hue value.
  35099. * 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).
  35100. */
  35101. set: function (value) {
  35102. this._globalHue = value;
  35103. this._dirty = true;
  35104. },
  35105. enumerable: true,
  35106. configurable: true
  35107. });
  35108. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35109. /**
  35110. * Gets the global Density value.
  35111. * 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.
  35112. * Values less than zero provide a filter of opposite hue.
  35113. */
  35114. get: function () {
  35115. return this._globalDensity;
  35116. },
  35117. /**
  35118. * Sets the global Density value.
  35119. * 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.
  35120. * Values less than zero provide a filter of opposite hue.
  35121. */
  35122. set: function (value) {
  35123. this._globalDensity = value;
  35124. this._dirty = true;
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35130. /**
  35131. * Gets the global Saturation value.
  35132. * 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.
  35133. */
  35134. get: function () {
  35135. return this._globalSaturation;
  35136. },
  35137. /**
  35138. * Sets the global Saturation value.
  35139. * 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.
  35140. */
  35141. set: function (value) {
  35142. this._globalSaturation = value;
  35143. this._dirty = true;
  35144. },
  35145. enumerable: true,
  35146. configurable: true
  35147. });
  35148. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35149. /**
  35150. * Gets the highlights Hue value.
  35151. * 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).
  35152. */
  35153. get: function () {
  35154. return this._highlightsHue;
  35155. },
  35156. /**
  35157. * Sets the highlights Hue value.
  35158. * 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).
  35159. */
  35160. set: function (value) {
  35161. this._highlightsHue = value;
  35162. this._dirty = true;
  35163. },
  35164. enumerable: true,
  35165. configurable: true
  35166. });
  35167. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35168. /**
  35169. * Gets the highlights Density value.
  35170. * 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.
  35171. * Values less than zero provide a filter of opposite hue.
  35172. */
  35173. get: function () {
  35174. return this._highlightsDensity;
  35175. },
  35176. /**
  35177. * Sets the highlights Density value.
  35178. * 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.
  35179. * Values less than zero provide a filter of opposite hue.
  35180. */
  35181. set: function (value) {
  35182. this._highlightsDensity = value;
  35183. this._dirty = true;
  35184. },
  35185. enumerable: true,
  35186. configurable: true
  35187. });
  35188. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35189. /**
  35190. * Gets the highlights Saturation value.
  35191. * 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.
  35192. */
  35193. get: function () {
  35194. return this._highlightsSaturation;
  35195. },
  35196. /**
  35197. * Sets the highlights Saturation value.
  35198. * 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.
  35199. */
  35200. set: function (value) {
  35201. this._highlightsSaturation = value;
  35202. this._dirty = true;
  35203. },
  35204. enumerable: true,
  35205. configurable: true
  35206. });
  35207. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35208. /**
  35209. * Gets the highlights Exposure value.
  35210. * 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.
  35211. */
  35212. get: function () {
  35213. return this._highlightsExposure;
  35214. },
  35215. /**
  35216. * Sets the highlights Exposure value.
  35217. * 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.
  35218. */
  35219. set: function (value) {
  35220. this._highlightsExposure = value;
  35221. this._dirty = true;
  35222. },
  35223. enumerable: true,
  35224. configurable: true
  35225. });
  35226. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35227. /**
  35228. * Gets the midtones Hue value.
  35229. * 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).
  35230. */
  35231. get: function () {
  35232. return this._midtonesHue;
  35233. },
  35234. /**
  35235. * Sets the midtones Hue value.
  35236. * 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).
  35237. */
  35238. set: function (value) {
  35239. this._midtonesHue = value;
  35240. this._dirty = true;
  35241. },
  35242. enumerable: true,
  35243. configurable: true
  35244. });
  35245. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35246. /**
  35247. * Gets the midtones Density value.
  35248. * 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.
  35249. * Values less than zero provide a filter of opposite hue.
  35250. */
  35251. get: function () {
  35252. return this._midtonesDensity;
  35253. },
  35254. /**
  35255. * Sets the midtones Density value.
  35256. * 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.
  35257. * Values less than zero provide a filter of opposite hue.
  35258. */
  35259. set: function (value) {
  35260. this._midtonesDensity = value;
  35261. this._dirty = true;
  35262. },
  35263. enumerable: true,
  35264. configurable: true
  35265. });
  35266. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35267. /**
  35268. * Gets the midtones Saturation value.
  35269. * 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.
  35270. */
  35271. get: function () {
  35272. return this._midtonesSaturation;
  35273. },
  35274. /**
  35275. * Sets the midtones Saturation value.
  35276. * 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.
  35277. */
  35278. set: function (value) {
  35279. this._midtonesSaturation = value;
  35280. this._dirty = true;
  35281. },
  35282. enumerable: true,
  35283. configurable: true
  35284. });
  35285. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35286. /**
  35287. * Gets the midtones Exposure value.
  35288. * 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.
  35289. */
  35290. get: function () {
  35291. return this._midtonesExposure;
  35292. },
  35293. /**
  35294. * Sets the midtones Exposure value.
  35295. * 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.
  35296. */
  35297. set: function (value) {
  35298. this._midtonesExposure = value;
  35299. this._dirty = true;
  35300. },
  35301. enumerable: true,
  35302. configurable: true
  35303. });
  35304. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35305. /**
  35306. * Gets the shadows Hue value.
  35307. * 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).
  35308. */
  35309. get: function () {
  35310. return this._shadowsHue;
  35311. },
  35312. /**
  35313. * Sets the shadows Hue value.
  35314. * 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).
  35315. */
  35316. set: function (value) {
  35317. this._shadowsHue = value;
  35318. this._dirty = true;
  35319. },
  35320. enumerable: true,
  35321. configurable: true
  35322. });
  35323. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35324. /**
  35325. * Gets the shadows Density value.
  35326. * 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.
  35327. * Values less than zero provide a filter of opposite hue.
  35328. */
  35329. get: function () {
  35330. return this._shadowsDensity;
  35331. },
  35332. /**
  35333. * Sets the shadows Density value.
  35334. * 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.
  35335. * Values less than zero provide a filter of opposite hue.
  35336. */
  35337. set: function (value) {
  35338. this._shadowsDensity = value;
  35339. this._dirty = true;
  35340. },
  35341. enumerable: true,
  35342. configurable: true
  35343. });
  35344. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35345. /**
  35346. * Gets the shadows Saturation value.
  35347. * 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.
  35348. */
  35349. get: function () {
  35350. return this._shadowsSaturation;
  35351. },
  35352. /**
  35353. * Sets the shadows Saturation value.
  35354. * 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.
  35355. */
  35356. set: function (value) {
  35357. this._shadowsSaturation = value;
  35358. this._dirty = true;
  35359. },
  35360. enumerable: true,
  35361. configurable: true
  35362. });
  35363. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35364. /**
  35365. * Gets the shadows Exposure value.
  35366. * 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.
  35367. */
  35368. get: function () {
  35369. return this._shadowsExposure;
  35370. },
  35371. /**
  35372. * Sets the shadows Exposure value.
  35373. * 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.
  35374. */
  35375. set: function (value) {
  35376. this._shadowsExposure = value;
  35377. this._dirty = true;
  35378. },
  35379. enumerable: true,
  35380. configurable: true
  35381. });
  35382. ColorCurves.prototype.getClassName = function () {
  35383. return "ColorCurves";
  35384. };
  35385. /**
  35386. * Binds the color curves to the shader.
  35387. * @param colorCurves The color curve to bind
  35388. * @param effect The effect to bind to
  35389. */
  35390. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35391. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35392. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35393. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35394. if (colorCurves._dirty) {
  35395. colorCurves._dirty = false;
  35396. // Fill in global info.
  35397. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35398. // Compute highlights info.
  35399. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35400. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35401. // Compute midtones info.
  35402. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35403. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35404. // Compute shadows info.
  35405. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35406. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35407. // Compute deltas (neutral is midtones).
  35408. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35409. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35410. }
  35411. if (effect) {
  35412. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35413. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35414. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35415. }
  35416. };
  35417. /**
  35418. * Prepare the list of uniforms associated with the ColorCurves effects.
  35419. * @param uniformsList The list of uniforms used in the effect
  35420. */
  35421. ColorCurves.PrepareUniforms = function (uniformsList) {
  35422. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35423. };
  35424. /**
  35425. * Returns color grading data based on a hue, density, saturation and exposure value.
  35426. * @param filterHue The hue of the color filter.
  35427. * @param filterDensity The density of the color filter.
  35428. * @param saturation The saturation.
  35429. * @param exposure The exposure.
  35430. * @param result The result data container.
  35431. */
  35432. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35433. if (hue == null) {
  35434. return;
  35435. }
  35436. hue = ColorCurves.clamp(hue, 0, 360);
  35437. density = ColorCurves.clamp(density, -100, 100);
  35438. saturation = ColorCurves.clamp(saturation, -100, 100);
  35439. exposure = ColorCurves.clamp(exposure, -100, 100);
  35440. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35441. // so that the maximum filter density is only 50% control. This provides fine control
  35442. // for small values and reasonable range.
  35443. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35444. density *= 0.5;
  35445. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35446. if (density < 0) {
  35447. density *= -1;
  35448. hue = (hue + 180) % 360;
  35449. }
  35450. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35451. result.scaleToRef(2, result);
  35452. result.a = 1 + 0.01 * saturation;
  35453. };
  35454. /**
  35455. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  35456. * @param value The input slider value in range [-100,100].
  35457. * @returns Adjusted value.
  35458. */
  35459. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  35460. value /= 100;
  35461. var x = Math.abs(value);
  35462. x = Math.pow(x, 2);
  35463. if (value < 0) {
  35464. x *= -1;
  35465. }
  35466. x *= 100;
  35467. return x;
  35468. };
  35469. /**
  35470. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  35471. * @param hue The hue (H) input.
  35472. * @param saturation The saturation (S) input.
  35473. * @param brightness The brightness (B) input.
  35474. * @result An RGBA color represented as Vector4.
  35475. */
  35476. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  35477. var h = ColorCurves.clamp(hue, 0, 360);
  35478. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  35479. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  35480. if (s === 0) {
  35481. result.r = v;
  35482. result.g = v;
  35483. result.b = v;
  35484. }
  35485. else {
  35486. // sector 0 to 5
  35487. h /= 60;
  35488. var i = Math.floor(h);
  35489. // fractional part of h
  35490. var f = h - i;
  35491. var p = v * (1 - s);
  35492. var q = v * (1 - s * f);
  35493. var t = v * (1 - s * (1 - f));
  35494. switch (i) {
  35495. case 0:
  35496. result.r = v;
  35497. result.g = t;
  35498. result.b = p;
  35499. break;
  35500. case 1:
  35501. result.r = q;
  35502. result.g = v;
  35503. result.b = p;
  35504. break;
  35505. case 2:
  35506. result.r = p;
  35507. result.g = v;
  35508. result.b = t;
  35509. break;
  35510. case 3:
  35511. result.r = p;
  35512. result.g = q;
  35513. result.b = v;
  35514. break;
  35515. case 4:
  35516. result.r = t;
  35517. result.g = p;
  35518. result.b = v;
  35519. break;
  35520. default:// case 5:
  35521. result.r = v;
  35522. result.g = p;
  35523. result.b = q;
  35524. break;
  35525. }
  35526. }
  35527. result.a = 1;
  35528. };
  35529. /**
  35530. * Returns a value clamped between min and max
  35531. * @param value The value to clamp
  35532. * @param min The minimum of value
  35533. * @param max The maximum of value
  35534. * @returns The clamped value.
  35535. */
  35536. ColorCurves.clamp = function (value, min, max) {
  35537. return Math.min(Math.max(value, min), max);
  35538. };
  35539. /**
  35540. * Clones the current color curve instance.
  35541. * @return The cloned curves
  35542. */
  35543. ColorCurves.prototype.clone = function () {
  35544. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  35545. };
  35546. /**
  35547. * Serializes the current color curve instance to a json representation.
  35548. * @return a JSON representation
  35549. */
  35550. ColorCurves.prototype.serialize = function () {
  35551. return BABYLON.SerializationHelper.Serialize(this);
  35552. };
  35553. /**
  35554. * Parses the color curve from a json representation.
  35555. * @param source the JSON source to parse
  35556. * @return The parsed curves
  35557. */
  35558. ColorCurves.Parse = function (source) {
  35559. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  35560. };
  35561. __decorate([
  35562. BABYLON.serialize()
  35563. ], ColorCurves.prototype, "_globalHue", void 0);
  35564. __decorate([
  35565. BABYLON.serialize()
  35566. ], ColorCurves.prototype, "_globalDensity", void 0);
  35567. __decorate([
  35568. BABYLON.serialize()
  35569. ], ColorCurves.prototype, "_globalSaturation", void 0);
  35570. __decorate([
  35571. BABYLON.serialize()
  35572. ], ColorCurves.prototype, "_globalExposure", void 0);
  35573. __decorate([
  35574. BABYLON.serialize()
  35575. ], ColorCurves.prototype, "_highlightsHue", void 0);
  35576. __decorate([
  35577. BABYLON.serialize()
  35578. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  35579. __decorate([
  35580. BABYLON.serialize()
  35581. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  35582. __decorate([
  35583. BABYLON.serialize()
  35584. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  35585. __decorate([
  35586. BABYLON.serialize()
  35587. ], ColorCurves.prototype, "_midtonesHue", void 0);
  35588. __decorate([
  35589. BABYLON.serialize()
  35590. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  35591. __decorate([
  35592. BABYLON.serialize()
  35593. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  35594. __decorate([
  35595. BABYLON.serialize()
  35596. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  35597. return ColorCurves;
  35598. }());
  35599. BABYLON.ColorCurves = ColorCurves;
  35600. })(BABYLON || (BABYLON = {}));
  35601. //# sourceMappingURL=babylon.colorCurves.js.map
  35602. //# sourceMappingURL=babylon.behavior.js.map
  35603. var BABYLON;
  35604. (function (BABYLON) {
  35605. var MaterialHelper = /** @class */ (function () {
  35606. function MaterialHelper() {
  35607. }
  35608. MaterialHelper.BindEyePosition = function (effect, scene) {
  35609. if (scene._forcedViewPosition) {
  35610. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  35611. return;
  35612. }
  35613. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35614. };
  35615. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  35616. defines._needUVs = true;
  35617. defines[key] = true;
  35618. if (texture.getTextureMatrix().isIdentity(true)) {
  35619. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  35620. if (texture.coordinatesIndex === 0) {
  35621. defines["MAINUV1"] = true;
  35622. }
  35623. else {
  35624. defines["MAINUV2"] = true;
  35625. }
  35626. }
  35627. else {
  35628. defines[key + "DIRECTUV"] = 0;
  35629. }
  35630. };
  35631. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  35632. var matrix = texture.getTextureMatrix();
  35633. if (!matrix.isIdentity(true)) {
  35634. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  35635. }
  35636. };
  35637. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  35638. if (defines._areMiscDirty) {
  35639. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  35640. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  35641. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  35642. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  35643. }
  35644. };
  35645. /**
  35646. * Helper used to prepare the list of defines for shader compilation
  35647. * @param scene defines the current scene
  35648. * @param engine defines the current engine
  35649. * @param defines specifies the list of active defines
  35650. * @param useInstances defines if instances have to be turned on
  35651. * @param alphaTest defines if alpha testing has to be turned on
  35652. */
  35653. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, alphaTest) {
  35654. var changed = false;
  35655. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  35656. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  35657. changed = true;
  35658. }
  35659. if (defines["ALPHATEST"] !== alphaTest) {
  35660. defines["ALPHATEST"] = !defines["ALPHATEST"];
  35661. changed = true;
  35662. }
  35663. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  35664. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  35665. changed = true;
  35666. }
  35667. if (defines["INSTANCES"] !== useInstances) {
  35668. defines["INSTANCES"] = useInstances;
  35669. changed = true;
  35670. }
  35671. if (changed) {
  35672. defines.markAsUnprocessed();
  35673. }
  35674. };
  35675. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  35676. if (useMorphTargets === void 0) { useMorphTargets = false; }
  35677. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  35678. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  35679. return false;
  35680. }
  35681. defines._normals = defines._needNormals;
  35682. defines._uvs = defines._needUVs;
  35683. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  35684. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35685. defines["TANGENT"] = true;
  35686. }
  35687. if (defines._needUVs) {
  35688. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  35689. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  35690. }
  35691. else {
  35692. defines["UV1"] = false;
  35693. defines["UV2"] = false;
  35694. }
  35695. if (useVertexColor) {
  35696. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  35697. defines["VERTEXCOLOR"] = hasVertexColors;
  35698. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  35699. }
  35700. if (useBones) {
  35701. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  35702. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  35703. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  35704. }
  35705. else {
  35706. defines["NUM_BONE_INFLUENCERS"] = 0;
  35707. defines["BonesPerMesh"] = 0;
  35708. }
  35709. }
  35710. if (useMorphTargets) {
  35711. var manager = mesh.morphTargetManager;
  35712. if (manager) {
  35713. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  35714. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  35715. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  35716. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  35717. }
  35718. else {
  35719. defines["MORPHTARGETS_TANGENT"] = false;
  35720. defines["MORPHTARGETS_NORMAL"] = false;
  35721. defines["MORPHTARGETS"] = false;
  35722. defines["NUM_MORPH_INFLUENCERS"] = 0;
  35723. }
  35724. }
  35725. return true;
  35726. };
  35727. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  35728. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35729. if (disableLighting === void 0) { disableLighting = false; }
  35730. if (!defines._areLightsDirty) {
  35731. return defines._needNormals;
  35732. }
  35733. var lightIndex = 0;
  35734. var needNormals = false;
  35735. var needRebuild = false;
  35736. var lightmapMode = false;
  35737. var shadowEnabled = false;
  35738. var specularEnabled = false;
  35739. if (scene.lightsEnabled && !disableLighting) {
  35740. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  35741. var light = _a[_i];
  35742. needNormals = true;
  35743. if (defines["LIGHT" + lightIndex] === undefined) {
  35744. needRebuild = true;
  35745. }
  35746. defines["LIGHT" + lightIndex] = true;
  35747. defines["SPOTLIGHT" + lightIndex] = false;
  35748. defines["HEMILIGHT" + lightIndex] = false;
  35749. defines["POINTLIGHT" + lightIndex] = false;
  35750. defines["DIRLIGHT" + lightIndex] = false;
  35751. var type;
  35752. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  35753. type = "SPOTLIGHT" + lightIndex;
  35754. }
  35755. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  35756. type = "HEMILIGHT" + lightIndex;
  35757. }
  35758. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  35759. type = "POINTLIGHT" + lightIndex;
  35760. }
  35761. else {
  35762. type = "DIRLIGHT" + lightIndex;
  35763. }
  35764. defines[type] = true;
  35765. // Specular
  35766. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  35767. specularEnabled = true;
  35768. }
  35769. // Shadows
  35770. defines["SHADOW" + lightIndex] = false;
  35771. defines["SHADOWPCF" + lightIndex] = false;
  35772. defines["SHADOWESM" + lightIndex] = false;
  35773. defines["SHADOWCUBE" + lightIndex] = false;
  35774. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  35775. var shadowGenerator = light.getShadowGenerator();
  35776. if (shadowGenerator) {
  35777. shadowEnabled = true;
  35778. shadowGenerator.prepareDefines(defines, lightIndex);
  35779. }
  35780. }
  35781. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  35782. lightmapMode = true;
  35783. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  35784. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  35785. }
  35786. else {
  35787. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  35788. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  35789. }
  35790. lightIndex++;
  35791. if (lightIndex === maxSimultaneousLights)
  35792. break;
  35793. }
  35794. }
  35795. defines["SPECULARTERM"] = specularEnabled;
  35796. defines["SHADOWS"] = shadowEnabled;
  35797. // Resetting all other lights if any
  35798. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  35799. if (defines["LIGHT" + index] !== undefined) {
  35800. defines["LIGHT" + index] = false;
  35801. defines["HEMILIGHT" + lightIndex] = false;
  35802. defines["POINTLIGHT" + lightIndex] = false;
  35803. defines["DIRLIGHT" + lightIndex] = false;
  35804. defines["SPOTLIGHT" + lightIndex] = false;
  35805. defines["SHADOW" + lightIndex] = false;
  35806. }
  35807. }
  35808. var caps = scene.getEngine().getCaps();
  35809. if (defines["SHADOWFLOAT"] === undefined) {
  35810. needRebuild = true;
  35811. }
  35812. defines["SHADOWFLOAT"] = shadowEnabled &&
  35813. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  35814. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  35815. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  35816. if (needRebuild) {
  35817. defines.rebuild();
  35818. }
  35819. return needNormals;
  35820. };
  35821. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  35822. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35823. var uniformsList;
  35824. var uniformBuffersList = null;
  35825. if (uniformsListOrOptions.uniformsNames) {
  35826. var options = uniformsListOrOptions;
  35827. uniformsList = options.uniformsNames;
  35828. uniformBuffersList = options.uniformBuffersNames;
  35829. samplersList = options.samplers;
  35830. defines = options.defines;
  35831. maxSimultaneousLights = options.maxSimultaneousLights;
  35832. }
  35833. else {
  35834. uniformsList = uniformsListOrOptions;
  35835. if (!samplersList) {
  35836. samplersList = [];
  35837. }
  35838. }
  35839. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  35840. if (!defines["LIGHT" + lightIndex]) {
  35841. break;
  35842. }
  35843. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  35844. if (uniformBuffersList) {
  35845. uniformBuffersList.push("Light" + lightIndex);
  35846. }
  35847. samplersList.push("shadowSampler" + lightIndex);
  35848. }
  35849. if (defines["NUM_MORPH_INFLUENCERS"]) {
  35850. uniformsList.push("morphTargetInfluences");
  35851. }
  35852. };
  35853. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  35854. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35855. if (rank === void 0) { rank = 0; }
  35856. var lightFallbackRank = 0;
  35857. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  35858. if (!defines["LIGHT" + lightIndex]) {
  35859. break;
  35860. }
  35861. if (lightIndex > 0) {
  35862. lightFallbackRank = rank + lightIndex;
  35863. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  35864. }
  35865. if (!defines["SHADOWS"]) {
  35866. if (defines["SHADOW" + lightIndex]) {
  35867. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  35868. }
  35869. if (defines["SHADOWPCF" + lightIndex]) {
  35870. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  35871. }
  35872. if (defines["SHADOWESM" + lightIndex]) {
  35873. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  35874. }
  35875. }
  35876. }
  35877. return lightFallbackRank++;
  35878. };
  35879. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  35880. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  35881. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  35882. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  35883. var manager = mesh.morphTargetManager;
  35884. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  35885. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  35886. for (var index = 0; index < influencers; index++) {
  35887. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  35888. if (normal) {
  35889. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  35890. }
  35891. if (tangent) {
  35892. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  35893. }
  35894. if (attribs.length > maxAttributesCount) {
  35895. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  35896. }
  35897. }
  35898. }
  35899. };
  35900. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  35901. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  35902. fallbacks.addCPUSkinningFallback(0, mesh);
  35903. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35904. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35905. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  35906. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35907. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35908. }
  35909. }
  35910. };
  35911. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  35912. if (defines["INSTANCES"]) {
  35913. attribs.push("world0");
  35914. attribs.push("world1");
  35915. attribs.push("world2");
  35916. attribs.push("world3");
  35917. }
  35918. };
  35919. // Bindings
  35920. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  35921. if (light.shadowEnabled && mesh.receiveShadows) {
  35922. var shadowGenerator = light.getShadowGenerator();
  35923. if (shadowGenerator) {
  35924. shadowGenerator.bindShadowLight(lightIndex, effect);
  35925. }
  35926. }
  35927. };
  35928. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  35929. light.transferToEffect(effect, lightIndex + "");
  35930. };
  35931. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  35932. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35933. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  35934. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  35935. for (var i = 0; i < len; i++) {
  35936. var light = mesh._lightSources[i];
  35937. var iAsString = i.toString();
  35938. var scaledIntensity = light.getScaledIntensity();
  35939. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  35940. MaterialHelper.BindLightProperties(light, effect, i);
  35941. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  35942. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  35943. if (defines["SPECULARTERM"]) {
  35944. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  35945. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  35946. }
  35947. // Shadows
  35948. if (scene.shadowsEnabled) {
  35949. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  35950. }
  35951. light._uniformBuffer.update();
  35952. }
  35953. };
  35954. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  35955. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35956. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  35957. effect.setColor3("vFogColor", scene.fogColor);
  35958. }
  35959. };
  35960. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  35961. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  35962. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  35963. if (matrices && effect) {
  35964. effect.setMatrices("mBones", matrices);
  35965. }
  35966. }
  35967. };
  35968. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  35969. var manager = abstractMesh.morphTargetManager;
  35970. if (!abstractMesh || !manager) {
  35971. return;
  35972. }
  35973. effect.setFloatArray("morphTargetInfluences", manager.influences);
  35974. };
  35975. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  35976. if (defines["LOGARITHMICDEPTH"]) {
  35977. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  35978. }
  35979. };
  35980. MaterialHelper.BindClipPlane = function (effect, scene) {
  35981. if (scene.clipPlane) {
  35982. var clipPlane = scene.clipPlane;
  35983. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35984. }
  35985. };
  35986. return MaterialHelper;
  35987. }());
  35988. BABYLON.MaterialHelper = MaterialHelper;
  35989. })(BABYLON || (BABYLON = {}));
  35990. //# sourceMappingURL=babylon.materialHelper.js.map
  35991. var BABYLON;
  35992. (function (BABYLON) {
  35993. var PushMaterial = /** @class */ (function (_super) {
  35994. __extends(PushMaterial, _super);
  35995. function PushMaterial(name, scene) {
  35996. var _this = _super.call(this, name, scene) || this;
  35997. _this.storeEffectOnSubMeshes = true;
  35998. return _this;
  35999. }
  36000. PushMaterial.prototype.getEffect = function () {
  36001. return this._activeEffect;
  36002. };
  36003. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36004. if (!mesh) {
  36005. return false;
  36006. }
  36007. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36008. return true;
  36009. }
  36010. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36011. };
  36012. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36013. this._activeEffect.setMatrix("world", world);
  36014. };
  36015. PushMaterial.prototype.bind = function (world, mesh) {
  36016. if (!mesh) {
  36017. return;
  36018. }
  36019. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36020. };
  36021. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36022. if (effect === void 0) { effect = null; }
  36023. _super.prototype._afterBind.call(this, mesh);
  36024. this.getScene()._cachedEffect = effect;
  36025. };
  36026. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36027. if (visibility === void 0) { visibility = 1; }
  36028. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36029. };
  36030. return PushMaterial;
  36031. }(BABYLON.Material));
  36032. BABYLON.PushMaterial = PushMaterial;
  36033. })(BABYLON || (BABYLON = {}));
  36034. //# sourceMappingURL=babylon.pushMaterial.js.map
  36035. var BABYLON;
  36036. (function (BABYLON) {
  36037. var StandardMaterialDefines = /** @class */ (function (_super) {
  36038. __extends(StandardMaterialDefines, _super);
  36039. function StandardMaterialDefines() {
  36040. var _this = _super.call(this) || this;
  36041. _this.MAINUV1 = false;
  36042. _this.MAINUV2 = false;
  36043. _this.DIFFUSE = false;
  36044. _this.DIFFUSEDIRECTUV = 0;
  36045. _this.AMBIENT = false;
  36046. _this.AMBIENTDIRECTUV = 0;
  36047. _this.OPACITY = false;
  36048. _this.OPACITYDIRECTUV = 0;
  36049. _this.OPACITYRGB = false;
  36050. _this.REFLECTION = false;
  36051. _this.EMISSIVE = false;
  36052. _this.EMISSIVEDIRECTUV = 0;
  36053. _this.SPECULAR = false;
  36054. _this.SPECULARDIRECTUV = 0;
  36055. _this.BUMP = false;
  36056. _this.BUMPDIRECTUV = 0;
  36057. _this.PARALLAX = false;
  36058. _this.PARALLAXOCCLUSION = false;
  36059. _this.SPECULAROVERALPHA = false;
  36060. _this.CLIPPLANE = false;
  36061. _this.ALPHATEST = false;
  36062. _this.DEPTHPREPASS = false;
  36063. _this.ALPHAFROMDIFFUSE = false;
  36064. _this.POINTSIZE = false;
  36065. _this.FOG = false;
  36066. _this.SPECULARTERM = false;
  36067. _this.DIFFUSEFRESNEL = false;
  36068. _this.OPACITYFRESNEL = false;
  36069. _this.REFLECTIONFRESNEL = false;
  36070. _this.REFRACTIONFRESNEL = false;
  36071. _this.EMISSIVEFRESNEL = false;
  36072. _this.FRESNEL = false;
  36073. _this.NORMAL = false;
  36074. _this.UV1 = false;
  36075. _this.UV2 = false;
  36076. _this.VERTEXCOLOR = false;
  36077. _this.VERTEXALPHA = false;
  36078. _this.NUM_BONE_INFLUENCERS = 0;
  36079. _this.BonesPerMesh = 0;
  36080. _this.INSTANCES = false;
  36081. _this.GLOSSINESS = false;
  36082. _this.ROUGHNESS = false;
  36083. _this.EMISSIVEASILLUMINATION = false;
  36084. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36085. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36086. _this.LIGHTMAP = false;
  36087. _this.LIGHTMAPDIRECTUV = 0;
  36088. _this.USELIGHTMAPASSHADOWMAP = false;
  36089. _this.REFLECTIONMAP_3D = false;
  36090. _this.REFLECTIONMAP_SPHERICAL = false;
  36091. _this.REFLECTIONMAP_PLANAR = false;
  36092. _this.REFLECTIONMAP_CUBIC = false;
  36093. _this.REFLECTIONMAP_PROJECTION = false;
  36094. _this.REFLECTIONMAP_SKYBOX = false;
  36095. _this.REFLECTIONMAP_EXPLICIT = false;
  36096. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36097. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36098. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36099. _this.INVERTCUBICMAP = false;
  36100. _this.LOGARITHMICDEPTH = false;
  36101. _this.REFRACTION = false;
  36102. _this.REFRACTIONMAP_3D = false;
  36103. _this.REFLECTIONOVERALPHA = false;
  36104. _this.TWOSIDEDLIGHTING = false;
  36105. _this.SHADOWFLOAT = false;
  36106. _this.MORPHTARGETS = false;
  36107. _this.MORPHTARGETS_NORMAL = false;
  36108. _this.MORPHTARGETS_TANGENT = false;
  36109. _this.NUM_MORPH_INFLUENCERS = 0;
  36110. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36111. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36112. _this.IMAGEPROCESSING = false;
  36113. _this.VIGNETTE = false;
  36114. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36115. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36116. _this.TONEMAPPING = false;
  36117. _this.CONTRAST = false;
  36118. _this.COLORCURVES = false;
  36119. _this.COLORGRADING = false;
  36120. _this.COLORGRADING3D = false;
  36121. _this.SAMPLER3DGREENDEPTH = false;
  36122. _this.SAMPLER3DBGRMAP = false;
  36123. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36124. _this.EXPOSURE = false;
  36125. _this.rebuild();
  36126. return _this;
  36127. }
  36128. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36129. var modes = [
  36130. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36131. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36132. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36133. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36134. ];
  36135. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36136. var mode = modes_1[_i];
  36137. this[mode] = (mode === modeToEnable);
  36138. }
  36139. };
  36140. return StandardMaterialDefines;
  36141. }(BABYLON.MaterialDefines));
  36142. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36143. var StandardMaterial = /** @class */ (function (_super) {
  36144. __extends(StandardMaterial, _super);
  36145. function StandardMaterial(name, scene) {
  36146. var _this = _super.call(this, name, scene) || this;
  36147. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36148. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36149. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36150. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36151. _this.specularPower = 64;
  36152. _this._useAlphaFromDiffuseTexture = false;
  36153. _this._useEmissiveAsIllumination = false;
  36154. _this._linkEmissiveWithDiffuse = false;
  36155. _this._useSpecularOverAlpha = false;
  36156. _this._useReflectionOverAlpha = false;
  36157. _this._disableLighting = false;
  36158. _this._useParallax = false;
  36159. _this._useParallaxOcclusion = false;
  36160. _this.parallaxScaleBias = 0.05;
  36161. _this._roughness = 0;
  36162. _this.indexOfRefraction = 0.98;
  36163. _this.invertRefractionY = true;
  36164. _this._useLightmapAsShadowmap = false;
  36165. _this._useReflectionFresnelFromSpecular = false;
  36166. _this._useGlossinessFromSpecularMapAlpha = false;
  36167. _this._maxSimultaneousLights = 4;
  36168. /**
  36169. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36170. */
  36171. _this._invertNormalMapX = false;
  36172. /**
  36173. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36174. */
  36175. _this._invertNormalMapY = false;
  36176. /**
  36177. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36178. */
  36179. _this._twoSidedLighting = false;
  36180. _this._renderTargets = new BABYLON.SmartArray(16);
  36181. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36182. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36183. // Setup the default processing configuration to the scene.
  36184. _this._attachImageProcessingConfiguration(null);
  36185. _this.getRenderTargetTextures = function () {
  36186. _this._renderTargets.reset();
  36187. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36188. _this._renderTargets.push(_this._reflectionTexture);
  36189. }
  36190. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36191. _this._renderTargets.push(_this._refractionTexture);
  36192. }
  36193. return _this._renderTargets;
  36194. };
  36195. return _this;
  36196. }
  36197. ;
  36198. ;
  36199. ;
  36200. ;
  36201. ;
  36202. ;
  36203. ;
  36204. ;
  36205. ;
  36206. ;
  36207. ;
  36208. ;
  36209. ;
  36210. ;
  36211. ;
  36212. ;
  36213. ;
  36214. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36215. /**
  36216. * Gets the image processing configuration used either in this material.
  36217. */
  36218. get: function () {
  36219. return this._imageProcessingConfiguration;
  36220. },
  36221. /**
  36222. * Sets the Default image processing configuration used either in the this material.
  36223. *
  36224. * If sets to null, the scene one is in use.
  36225. */
  36226. set: function (value) {
  36227. this._attachImageProcessingConfiguration(value);
  36228. // Ensure the effect will be rebuilt.
  36229. this._markAllSubMeshesAsTexturesDirty();
  36230. },
  36231. enumerable: true,
  36232. configurable: true
  36233. });
  36234. /**
  36235. * Attaches a new image processing configuration to the Standard Material.
  36236. * @param configuration
  36237. */
  36238. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36239. var _this = this;
  36240. if (configuration === this._imageProcessingConfiguration) {
  36241. return;
  36242. }
  36243. // Detaches observer.
  36244. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36245. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36246. }
  36247. // Pick the scene configuration if needed.
  36248. if (!configuration) {
  36249. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36250. }
  36251. else {
  36252. this._imageProcessingConfiguration = configuration;
  36253. }
  36254. // Attaches observer.
  36255. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36256. _this._markAllSubMeshesAsImageProcessingDirty();
  36257. });
  36258. };
  36259. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36260. /**
  36261. * Gets wether the color curves effect is enabled.
  36262. */
  36263. get: function () {
  36264. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36265. },
  36266. /**
  36267. * Sets wether the color curves effect is enabled.
  36268. */
  36269. set: function (value) {
  36270. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36271. },
  36272. enumerable: true,
  36273. configurable: true
  36274. });
  36275. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36276. /**
  36277. * Gets wether the color grading effect is enabled.
  36278. */
  36279. get: function () {
  36280. return this.imageProcessingConfiguration.colorGradingEnabled;
  36281. },
  36282. /**
  36283. * Gets wether the color grading effect is enabled.
  36284. */
  36285. set: function (value) {
  36286. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36287. },
  36288. enumerable: true,
  36289. configurable: true
  36290. });
  36291. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36292. /**
  36293. * Gets wether tonemapping is enabled or not.
  36294. */
  36295. get: function () {
  36296. return this._imageProcessingConfiguration.toneMappingEnabled;
  36297. },
  36298. /**
  36299. * Sets wether tonemapping is enabled or not
  36300. */
  36301. set: function (value) {
  36302. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36303. },
  36304. enumerable: true,
  36305. configurable: true
  36306. });
  36307. ;
  36308. ;
  36309. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36310. /**
  36311. * The camera exposure used on this material.
  36312. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36313. * This corresponds to a photographic exposure.
  36314. */
  36315. get: function () {
  36316. return this._imageProcessingConfiguration.exposure;
  36317. },
  36318. /**
  36319. * The camera exposure used on this material.
  36320. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36321. * This corresponds to a photographic exposure.
  36322. */
  36323. set: function (value) {
  36324. this._imageProcessingConfiguration.exposure = value;
  36325. },
  36326. enumerable: true,
  36327. configurable: true
  36328. });
  36329. ;
  36330. ;
  36331. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  36332. /**
  36333. * Gets The camera contrast used on this material.
  36334. */
  36335. get: function () {
  36336. return this._imageProcessingConfiguration.contrast;
  36337. },
  36338. /**
  36339. * Sets The camera contrast used on this material.
  36340. */
  36341. set: function (value) {
  36342. this._imageProcessingConfiguration.contrast = value;
  36343. },
  36344. enumerable: true,
  36345. configurable: true
  36346. });
  36347. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  36348. /**
  36349. * Gets the Color Grading 2D Lookup Texture.
  36350. */
  36351. get: function () {
  36352. return this._imageProcessingConfiguration.colorGradingTexture;
  36353. },
  36354. /**
  36355. * Sets the Color Grading 2D Lookup Texture.
  36356. */
  36357. set: function (value) {
  36358. this._imageProcessingConfiguration.colorGradingTexture = value;
  36359. },
  36360. enumerable: true,
  36361. configurable: true
  36362. });
  36363. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  36364. /**
  36365. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36366. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36367. * 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;
  36368. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36369. */
  36370. get: function () {
  36371. return this._imageProcessingConfiguration.colorCurves;
  36372. },
  36373. /**
  36374. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36375. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36376. * 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;
  36377. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36378. */
  36379. set: function (value) {
  36380. this._imageProcessingConfiguration.colorCurves = value;
  36381. },
  36382. enumerable: true,
  36383. configurable: true
  36384. });
  36385. StandardMaterial.prototype.getClassName = function () {
  36386. return "StandardMaterial";
  36387. };
  36388. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  36389. get: function () {
  36390. return this._useLogarithmicDepth;
  36391. },
  36392. set: function (value) {
  36393. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36394. this._markAllSubMeshesAsMiscDirty();
  36395. },
  36396. enumerable: true,
  36397. configurable: true
  36398. });
  36399. StandardMaterial.prototype.needAlphaBlending = function () {
  36400. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  36401. };
  36402. StandardMaterial.prototype.needAlphaTesting = function () {
  36403. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  36404. };
  36405. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  36406. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  36407. };
  36408. StandardMaterial.prototype.getAlphaTestTexture = function () {
  36409. return this._diffuseTexture;
  36410. };
  36411. /**
  36412. * Child classes can use it to update shaders
  36413. */
  36414. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36415. if (useInstances === void 0) { useInstances = false; }
  36416. if (subMesh.effect && this.isFrozen) {
  36417. if (this._wasPreviouslyReady && subMesh.effect) {
  36418. return true;
  36419. }
  36420. }
  36421. if (!subMesh._materialDefines) {
  36422. subMesh._materialDefines = new StandardMaterialDefines();
  36423. }
  36424. var scene = this.getScene();
  36425. var defines = subMesh._materialDefines;
  36426. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36427. if (defines._renderId === scene.getRenderId()) {
  36428. return true;
  36429. }
  36430. }
  36431. var engine = scene.getEngine();
  36432. // Lights
  36433. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36434. // Textures
  36435. if (defines._areTexturesDirty) {
  36436. defines._needUVs = false;
  36437. defines.MAINUV1 = false;
  36438. defines.MAINUV2 = false;
  36439. if (scene.texturesEnabled) {
  36440. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36441. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  36442. return false;
  36443. }
  36444. else {
  36445. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  36446. }
  36447. }
  36448. else {
  36449. defines.DIFFUSE = false;
  36450. }
  36451. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36452. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36453. return false;
  36454. }
  36455. else {
  36456. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36457. }
  36458. }
  36459. else {
  36460. defines.AMBIENT = false;
  36461. }
  36462. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36463. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36464. return false;
  36465. }
  36466. else {
  36467. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36468. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36469. }
  36470. }
  36471. else {
  36472. defines.OPACITY = false;
  36473. }
  36474. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36475. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  36476. return false;
  36477. }
  36478. else {
  36479. defines._needNormals = true;
  36480. defines.REFLECTION = true;
  36481. defines.ROUGHNESS = (this._roughness > 0);
  36482. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  36483. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  36484. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  36485. switch (this._reflectionTexture.coordinatesMode) {
  36486. case BABYLON.Texture.CUBIC_MODE:
  36487. case BABYLON.Texture.INVCUBIC_MODE:
  36488. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  36489. break;
  36490. case BABYLON.Texture.EXPLICIT_MODE:
  36491. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  36492. break;
  36493. case BABYLON.Texture.PLANAR_MODE:
  36494. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  36495. break;
  36496. case BABYLON.Texture.PROJECTION_MODE:
  36497. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  36498. break;
  36499. case BABYLON.Texture.SKYBOX_MODE:
  36500. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  36501. break;
  36502. case BABYLON.Texture.SPHERICAL_MODE:
  36503. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  36504. break;
  36505. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36506. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  36507. break;
  36508. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36509. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  36510. break;
  36511. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36512. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  36513. break;
  36514. }
  36515. }
  36516. }
  36517. else {
  36518. defines.REFLECTION = false;
  36519. }
  36520. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36521. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36522. return false;
  36523. }
  36524. else {
  36525. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36526. }
  36527. }
  36528. else {
  36529. defines.EMISSIVE = false;
  36530. }
  36531. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36532. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36533. return false;
  36534. }
  36535. else {
  36536. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36537. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36538. }
  36539. }
  36540. else {
  36541. defines.LIGHTMAP = false;
  36542. }
  36543. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36544. if (!this._specularTexture.isReadyOrNotBlocking()) {
  36545. return false;
  36546. }
  36547. else {
  36548. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  36549. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  36550. }
  36551. }
  36552. else {
  36553. defines.SPECULAR = false;
  36554. }
  36555. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  36556. // Bump texure can not be not blocking.
  36557. if (!this._bumpTexture.isReady()) {
  36558. return false;
  36559. }
  36560. else {
  36561. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36562. defines.PARALLAX = this._useParallax;
  36563. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  36564. }
  36565. }
  36566. else {
  36567. defines.BUMP = false;
  36568. }
  36569. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36570. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  36571. return false;
  36572. }
  36573. else {
  36574. defines._needUVs = true;
  36575. defines.REFRACTION = true;
  36576. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  36577. }
  36578. }
  36579. else {
  36580. defines.REFRACTION = false;
  36581. }
  36582. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  36583. }
  36584. else {
  36585. defines.DIFFUSE = false;
  36586. defines.AMBIENT = false;
  36587. defines.OPACITY = false;
  36588. defines.REFLECTION = false;
  36589. defines.EMISSIVE = false;
  36590. defines.LIGHTMAP = false;
  36591. defines.BUMP = false;
  36592. defines.REFRACTION = false;
  36593. }
  36594. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  36595. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  36596. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  36597. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36598. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36599. }
  36600. if (defines._areImageProcessingDirty) {
  36601. if (!this._imageProcessingConfiguration.isReady()) {
  36602. return false;
  36603. }
  36604. this._imageProcessingConfiguration.prepareDefines(defines);
  36605. }
  36606. if (defines._areFresnelDirty) {
  36607. if (StandardMaterial.FresnelEnabled) {
  36608. // Fresnel
  36609. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  36610. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  36611. this._reflectionFresnelParameters) {
  36612. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  36613. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  36614. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  36615. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  36616. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  36617. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  36618. defines._needNormals = true;
  36619. defines.FRESNEL = true;
  36620. }
  36621. }
  36622. else {
  36623. defines.FRESNEL = false;
  36624. }
  36625. }
  36626. // Misc.
  36627. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36628. // Attribs
  36629. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  36630. // Values that need to be evaluated on every frame
  36631. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  36632. // Get correct effect
  36633. if (defines.isDirty) {
  36634. defines.markAsProcessed();
  36635. scene.resetCachedMaterial();
  36636. // Fallbacks
  36637. var fallbacks = new BABYLON.EffectFallbacks();
  36638. if (defines.REFLECTION) {
  36639. fallbacks.addFallback(0, "REFLECTION");
  36640. }
  36641. if (defines.SPECULAR) {
  36642. fallbacks.addFallback(0, "SPECULAR");
  36643. }
  36644. if (defines.BUMP) {
  36645. fallbacks.addFallback(0, "BUMP");
  36646. }
  36647. if (defines.PARALLAX) {
  36648. fallbacks.addFallback(1, "PARALLAX");
  36649. }
  36650. if (defines.PARALLAXOCCLUSION) {
  36651. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  36652. }
  36653. if (defines.SPECULAROVERALPHA) {
  36654. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  36655. }
  36656. if (defines.FOG) {
  36657. fallbacks.addFallback(1, "FOG");
  36658. }
  36659. if (defines.POINTSIZE) {
  36660. fallbacks.addFallback(0, "POINTSIZE");
  36661. }
  36662. if (defines.LOGARITHMICDEPTH) {
  36663. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  36664. }
  36665. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  36666. if (defines.SPECULARTERM) {
  36667. fallbacks.addFallback(0, "SPECULARTERM");
  36668. }
  36669. if (defines.DIFFUSEFRESNEL) {
  36670. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  36671. }
  36672. if (defines.OPACITYFRESNEL) {
  36673. fallbacks.addFallback(2, "OPACITYFRESNEL");
  36674. }
  36675. if (defines.REFLECTIONFRESNEL) {
  36676. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  36677. }
  36678. if (defines.EMISSIVEFRESNEL) {
  36679. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  36680. }
  36681. if (defines.FRESNEL) {
  36682. fallbacks.addFallback(4, "FRESNEL");
  36683. }
  36684. //Attributes
  36685. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36686. if (defines.NORMAL) {
  36687. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36688. }
  36689. if (defines.UV1) {
  36690. attribs.push(BABYLON.VertexBuffer.UVKind);
  36691. }
  36692. if (defines.UV2) {
  36693. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36694. }
  36695. if (defines.VERTEXCOLOR) {
  36696. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36697. }
  36698. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36699. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36700. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36701. var shaderName = "default";
  36702. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  36703. "vFogInfos", "vFogColor", "pointSize",
  36704. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36705. "mBones",
  36706. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36707. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  36708. "logarithmicDepthConstant", "vTangentSpaceParams"
  36709. ];
  36710. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  36711. var uniformBuffers = ["Material", "Scene"];
  36712. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36713. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36714. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36715. uniformsNames: uniforms,
  36716. uniformBuffersNames: uniformBuffers,
  36717. samplers: samplers,
  36718. defines: defines,
  36719. maxSimultaneousLights: this._maxSimultaneousLights
  36720. });
  36721. if (this.customShaderNameResolve) {
  36722. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  36723. }
  36724. var join = defines.toString();
  36725. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  36726. attributes: attribs,
  36727. uniformsNames: uniforms,
  36728. uniformBuffersNames: uniformBuffers,
  36729. samplers: samplers,
  36730. defines: join,
  36731. fallbacks: fallbacks,
  36732. onCompiled: this.onCompiled,
  36733. onError: this.onError,
  36734. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36735. }, engine), defines);
  36736. this.buildUniformLayout();
  36737. }
  36738. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36739. return false;
  36740. }
  36741. defines._renderId = scene.getRenderId();
  36742. this._wasPreviouslyReady = true;
  36743. return true;
  36744. };
  36745. StandardMaterial.prototype.buildUniformLayout = function () {
  36746. // Order is important !
  36747. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  36748. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  36749. this._uniformBuffer.addUniform("opacityParts", 4);
  36750. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  36751. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  36752. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  36753. this._uniformBuffer.addUniform("refractionRightColor", 4);
  36754. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  36755. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  36756. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  36757. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  36758. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36759. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36760. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36761. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36762. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  36763. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36764. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  36765. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36766. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36767. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36768. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36769. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36770. this._uniformBuffer.addUniform("specularMatrix", 16);
  36771. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36772. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36773. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36774. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36775. this._uniformBuffer.addUniform("vSpecularColor", 4);
  36776. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36777. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  36778. this._uniformBuffer.addUniform("pointSize", 1);
  36779. this._uniformBuffer.create();
  36780. };
  36781. StandardMaterial.prototype.unbind = function () {
  36782. if (this._activeEffect) {
  36783. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36784. this._activeEffect.setTexture("reflection2DSampler", null);
  36785. }
  36786. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36787. this._activeEffect.setTexture("refraction2DSampler", null);
  36788. }
  36789. }
  36790. _super.prototype.unbind.call(this);
  36791. };
  36792. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36793. var scene = this.getScene();
  36794. var defines = subMesh._materialDefines;
  36795. if (!defines) {
  36796. return;
  36797. }
  36798. var effect = subMesh.effect;
  36799. if (!effect) {
  36800. return;
  36801. }
  36802. this._activeEffect = effect;
  36803. // Matrices
  36804. this.bindOnlyWorldMatrix(world);
  36805. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36806. // Bones
  36807. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  36808. if (mustRebind) {
  36809. this._uniformBuffer.bindToEffect(effect, "Material");
  36810. this.bindViewProjection(effect);
  36811. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36812. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  36813. // Fresnel
  36814. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  36815. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  36816. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  36817. }
  36818. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  36819. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  36820. }
  36821. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  36822. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  36823. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  36824. }
  36825. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  36826. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  36827. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  36828. }
  36829. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  36830. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  36831. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  36832. }
  36833. }
  36834. // Textures
  36835. if (scene.texturesEnabled) {
  36836. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36837. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  36838. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  36839. }
  36840. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36841. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  36842. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36843. }
  36844. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36845. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36846. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36847. }
  36848. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36849. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  36850. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  36851. }
  36852. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36853. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36854. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36855. }
  36856. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36857. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36858. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36859. }
  36860. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36861. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  36862. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  36863. }
  36864. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  36865. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  36866. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36867. if (scene._mirroredCameraPosition) {
  36868. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36869. }
  36870. else {
  36871. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36872. }
  36873. }
  36874. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36875. var depth = 1.0;
  36876. if (!this._refractionTexture.isCube) {
  36877. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  36878. if (this._refractionTexture.depth) {
  36879. depth = this._refractionTexture.depth;
  36880. }
  36881. }
  36882. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  36883. }
  36884. }
  36885. // Point size
  36886. if (this.pointsCloud) {
  36887. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36888. }
  36889. if (defines.SPECULARTERM) {
  36890. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  36891. }
  36892. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  36893. // Diffuse
  36894. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  36895. }
  36896. // Textures
  36897. if (scene.texturesEnabled) {
  36898. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36899. effect.setTexture("diffuseSampler", this._diffuseTexture);
  36900. }
  36901. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36902. effect.setTexture("ambientSampler", this._ambientTexture);
  36903. }
  36904. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36905. effect.setTexture("opacitySampler", this._opacityTexture);
  36906. }
  36907. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36908. if (this._reflectionTexture.isCube) {
  36909. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  36910. }
  36911. else {
  36912. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  36913. }
  36914. }
  36915. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36916. effect.setTexture("emissiveSampler", this._emissiveTexture);
  36917. }
  36918. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36919. effect.setTexture("lightmapSampler", this._lightmapTexture);
  36920. }
  36921. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36922. effect.setTexture("specularSampler", this._specularTexture);
  36923. }
  36924. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  36925. effect.setTexture("bumpSampler", this._bumpTexture);
  36926. }
  36927. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36928. var depth = 1.0;
  36929. if (this._refractionTexture.isCube) {
  36930. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  36931. }
  36932. else {
  36933. effect.setTexture("refraction2DSampler", this._refractionTexture);
  36934. }
  36935. }
  36936. }
  36937. // Clip plane
  36938. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  36939. // Colors
  36940. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  36941. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  36942. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36943. }
  36944. if (mustRebind || !this.isFrozen) {
  36945. // Lights
  36946. if (scene.lightsEnabled && !this._disableLighting) {
  36947. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  36948. }
  36949. // View
  36950. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  36951. this.bindView(effect);
  36952. }
  36953. // Fog
  36954. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  36955. // Morph targets
  36956. if (defines.NUM_MORPH_INFLUENCERS) {
  36957. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  36958. }
  36959. // Log. depth
  36960. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  36961. // image processing
  36962. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  36963. this._imageProcessingConfiguration.bind(this._activeEffect);
  36964. }
  36965. }
  36966. this._uniformBuffer.update();
  36967. this._afterBind(mesh, this._activeEffect);
  36968. };
  36969. StandardMaterial.prototype.getAnimatables = function () {
  36970. var results = [];
  36971. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  36972. results.push(this._diffuseTexture);
  36973. }
  36974. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36975. results.push(this._ambientTexture);
  36976. }
  36977. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36978. results.push(this._opacityTexture);
  36979. }
  36980. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36981. results.push(this._reflectionTexture);
  36982. }
  36983. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36984. results.push(this._emissiveTexture);
  36985. }
  36986. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  36987. results.push(this._specularTexture);
  36988. }
  36989. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36990. results.push(this._bumpTexture);
  36991. }
  36992. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36993. results.push(this._lightmapTexture);
  36994. }
  36995. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36996. results.push(this._refractionTexture);
  36997. }
  36998. return results;
  36999. };
  37000. StandardMaterial.prototype.getActiveTextures = function () {
  37001. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37002. if (this._diffuseTexture) {
  37003. activeTextures.push(this._diffuseTexture);
  37004. }
  37005. if (this._ambientTexture) {
  37006. activeTextures.push(this._ambientTexture);
  37007. }
  37008. if (this._opacityTexture) {
  37009. activeTextures.push(this._opacityTexture);
  37010. }
  37011. if (this._reflectionTexture) {
  37012. activeTextures.push(this._reflectionTexture);
  37013. }
  37014. if (this._emissiveTexture) {
  37015. activeTextures.push(this._emissiveTexture);
  37016. }
  37017. if (this._specularTexture) {
  37018. activeTextures.push(this._specularTexture);
  37019. }
  37020. if (this._bumpTexture) {
  37021. activeTextures.push(this._bumpTexture);
  37022. }
  37023. if (this._lightmapTexture) {
  37024. activeTextures.push(this._lightmapTexture);
  37025. }
  37026. if (this._refractionTexture) {
  37027. activeTextures.push(this._refractionTexture);
  37028. }
  37029. return activeTextures;
  37030. };
  37031. StandardMaterial.prototype.hasTexture = function (texture) {
  37032. if (_super.prototype.hasTexture.call(this, texture)) {
  37033. return true;
  37034. }
  37035. if (this._diffuseTexture === texture) {
  37036. return true;
  37037. }
  37038. if (this._ambientTexture === texture) {
  37039. return true;
  37040. }
  37041. if (this._opacityTexture === texture) {
  37042. return true;
  37043. }
  37044. if (this._reflectionTexture === texture) {
  37045. return true;
  37046. }
  37047. if (this._emissiveTexture === texture) {
  37048. return true;
  37049. }
  37050. if (this._specularTexture === texture) {
  37051. return true;
  37052. }
  37053. if (this._bumpTexture === texture) {
  37054. return true;
  37055. }
  37056. if (this._lightmapTexture === texture) {
  37057. return true;
  37058. }
  37059. if (this._refractionTexture === texture) {
  37060. return true;
  37061. }
  37062. return false;
  37063. };
  37064. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37065. if (forceDisposeTextures) {
  37066. if (this._diffuseTexture) {
  37067. this._diffuseTexture.dispose();
  37068. }
  37069. if (this._ambientTexture) {
  37070. this._ambientTexture.dispose();
  37071. }
  37072. if (this._opacityTexture) {
  37073. this._opacityTexture.dispose();
  37074. }
  37075. if (this._reflectionTexture) {
  37076. this._reflectionTexture.dispose();
  37077. }
  37078. if (this._emissiveTexture) {
  37079. this._emissiveTexture.dispose();
  37080. }
  37081. if (this._specularTexture) {
  37082. this._specularTexture.dispose();
  37083. }
  37084. if (this._bumpTexture) {
  37085. this._bumpTexture.dispose();
  37086. }
  37087. if (this._lightmapTexture) {
  37088. this._lightmapTexture.dispose();
  37089. }
  37090. if (this._refractionTexture) {
  37091. this._refractionTexture.dispose();
  37092. }
  37093. }
  37094. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37095. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37096. }
  37097. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37098. };
  37099. StandardMaterial.prototype.clone = function (name) {
  37100. var _this = this;
  37101. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37102. result.name = name;
  37103. result.id = name;
  37104. return result;
  37105. };
  37106. StandardMaterial.prototype.serialize = function () {
  37107. return BABYLON.SerializationHelper.Serialize(this);
  37108. };
  37109. // Statics
  37110. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37111. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37112. };
  37113. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37114. get: function () {
  37115. return StandardMaterial._DiffuseTextureEnabled;
  37116. },
  37117. set: function (value) {
  37118. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37119. return;
  37120. }
  37121. StandardMaterial._DiffuseTextureEnabled = value;
  37122. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37123. },
  37124. enumerable: true,
  37125. configurable: true
  37126. });
  37127. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37128. get: function () {
  37129. return StandardMaterial._AmbientTextureEnabled;
  37130. },
  37131. set: function (value) {
  37132. if (StandardMaterial._AmbientTextureEnabled === value) {
  37133. return;
  37134. }
  37135. StandardMaterial._AmbientTextureEnabled = value;
  37136. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37137. },
  37138. enumerable: true,
  37139. configurable: true
  37140. });
  37141. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37142. get: function () {
  37143. return StandardMaterial._OpacityTextureEnabled;
  37144. },
  37145. set: function (value) {
  37146. if (StandardMaterial._OpacityTextureEnabled === value) {
  37147. return;
  37148. }
  37149. StandardMaterial._OpacityTextureEnabled = value;
  37150. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37151. },
  37152. enumerable: true,
  37153. configurable: true
  37154. });
  37155. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37156. get: function () {
  37157. return StandardMaterial._ReflectionTextureEnabled;
  37158. },
  37159. set: function (value) {
  37160. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37161. return;
  37162. }
  37163. StandardMaterial._ReflectionTextureEnabled = value;
  37164. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37165. },
  37166. enumerable: true,
  37167. configurable: true
  37168. });
  37169. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37170. get: function () {
  37171. return StandardMaterial._EmissiveTextureEnabled;
  37172. },
  37173. set: function (value) {
  37174. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37175. return;
  37176. }
  37177. StandardMaterial._EmissiveTextureEnabled = value;
  37178. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37179. },
  37180. enumerable: true,
  37181. configurable: true
  37182. });
  37183. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37184. get: function () {
  37185. return StandardMaterial._SpecularTextureEnabled;
  37186. },
  37187. set: function (value) {
  37188. if (StandardMaterial._SpecularTextureEnabled === value) {
  37189. return;
  37190. }
  37191. StandardMaterial._SpecularTextureEnabled = value;
  37192. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37193. },
  37194. enumerable: true,
  37195. configurable: true
  37196. });
  37197. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37198. get: function () {
  37199. return StandardMaterial._BumpTextureEnabled;
  37200. },
  37201. set: function (value) {
  37202. if (StandardMaterial._BumpTextureEnabled === value) {
  37203. return;
  37204. }
  37205. StandardMaterial._BumpTextureEnabled = value;
  37206. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37207. },
  37208. enumerable: true,
  37209. configurable: true
  37210. });
  37211. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37212. get: function () {
  37213. return StandardMaterial._LightmapTextureEnabled;
  37214. },
  37215. set: function (value) {
  37216. if (StandardMaterial._LightmapTextureEnabled === value) {
  37217. return;
  37218. }
  37219. StandardMaterial._LightmapTextureEnabled = value;
  37220. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37221. },
  37222. enumerable: true,
  37223. configurable: true
  37224. });
  37225. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37226. get: function () {
  37227. return StandardMaterial._RefractionTextureEnabled;
  37228. },
  37229. set: function (value) {
  37230. if (StandardMaterial._RefractionTextureEnabled === value) {
  37231. return;
  37232. }
  37233. StandardMaterial._RefractionTextureEnabled = value;
  37234. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37235. },
  37236. enumerable: true,
  37237. configurable: true
  37238. });
  37239. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37240. get: function () {
  37241. return StandardMaterial._ColorGradingTextureEnabled;
  37242. },
  37243. set: function (value) {
  37244. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37245. return;
  37246. }
  37247. StandardMaterial._ColorGradingTextureEnabled = value;
  37248. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37249. },
  37250. enumerable: true,
  37251. configurable: true
  37252. });
  37253. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37254. get: function () {
  37255. return StandardMaterial._FresnelEnabled;
  37256. },
  37257. set: function (value) {
  37258. if (StandardMaterial._FresnelEnabled === value) {
  37259. return;
  37260. }
  37261. StandardMaterial._FresnelEnabled = value;
  37262. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37263. },
  37264. enumerable: true,
  37265. configurable: true
  37266. });
  37267. // Flags used to enable or disable a type of texture for all Standard Materials
  37268. StandardMaterial._DiffuseTextureEnabled = true;
  37269. StandardMaterial._AmbientTextureEnabled = true;
  37270. StandardMaterial._OpacityTextureEnabled = true;
  37271. StandardMaterial._ReflectionTextureEnabled = true;
  37272. StandardMaterial._EmissiveTextureEnabled = true;
  37273. StandardMaterial._SpecularTextureEnabled = true;
  37274. StandardMaterial._BumpTextureEnabled = true;
  37275. StandardMaterial._LightmapTextureEnabled = true;
  37276. StandardMaterial._RefractionTextureEnabled = true;
  37277. StandardMaterial._ColorGradingTextureEnabled = true;
  37278. StandardMaterial._FresnelEnabled = true;
  37279. __decorate([
  37280. BABYLON.serializeAsTexture("diffuseTexture")
  37281. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37282. __decorate([
  37283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37284. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37285. __decorate([
  37286. BABYLON.serializeAsTexture("ambientTexture")
  37287. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37288. __decorate([
  37289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37290. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37291. __decorate([
  37292. BABYLON.serializeAsTexture("opacityTexture")
  37293. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37294. __decorate([
  37295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37296. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37297. __decorate([
  37298. BABYLON.serializeAsTexture("reflectionTexture")
  37299. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37300. __decorate([
  37301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37302. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37303. __decorate([
  37304. BABYLON.serializeAsTexture("emissiveTexture")
  37305. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37306. __decorate([
  37307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37308. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37309. __decorate([
  37310. BABYLON.serializeAsTexture("specularTexture")
  37311. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37312. __decorate([
  37313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37314. ], StandardMaterial.prototype, "specularTexture", void 0);
  37315. __decorate([
  37316. BABYLON.serializeAsTexture("bumpTexture")
  37317. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  37318. __decorate([
  37319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37320. ], StandardMaterial.prototype, "bumpTexture", void 0);
  37321. __decorate([
  37322. BABYLON.serializeAsTexture("lightmapTexture")
  37323. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  37324. __decorate([
  37325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37326. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  37327. __decorate([
  37328. BABYLON.serializeAsTexture("refractionTexture")
  37329. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  37330. __decorate([
  37331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37332. ], StandardMaterial.prototype, "refractionTexture", void 0);
  37333. __decorate([
  37334. BABYLON.serializeAsColor3("ambient")
  37335. ], StandardMaterial.prototype, "ambientColor", void 0);
  37336. __decorate([
  37337. BABYLON.serializeAsColor3("diffuse")
  37338. ], StandardMaterial.prototype, "diffuseColor", void 0);
  37339. __decorate([
  37340. BABYLON.serializeAsColor3("specular")
  37341. ], StandardMaterial.prototype, "specularColor", void 0);
  37342. __decorate([
  37343. BABYLON.serializeAsColor3("emissive")
  37344. ], StandardMaterial.prototype, "emissiveColor", void 0);
  37345. __decorate([
  37346. BABYLON.serialize()
  37347. ], StandardMaterial.prototype, "specularPower", void 0);
  37348. __decorate([
  37349. BABYLON.serialize("useAlphaFromDiffuseTexture")
  37350. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  37351. __decorate([
  37352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37353. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  37354. __decorate([
  37355. BABYLON.serialize("useEmissiveAsIllumination")
  37356. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  37357. __decorate([
  37358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37359. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  37360. __decorate([
  37361. BABYLON.serialize("linkEmissiveWithDiffuse")
  37362. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  37363. __decorate([
  37364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37365. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  37366. __decorate([
  37367. BABYLON.serialize("useSpecularOverAlpha")
  37368. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  37369. __decorate([
  37370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37371. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  37372. __decorate([
  37373. BABYLON.serialize("useReflectionOverAlpha")
  37374. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  37375. __decorate([
  37376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37377. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  37378. __decorate([
  37379. BABYLON.serialize("disableLighting")
  37380. ], StandardMaterial.prototype, "_disableLighting", void 0);
  37381. __decorate([
  37382. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37383. ], StandardMaterial.prototype, "disableLighting", void 0);
  37384. __decorate([
  37385. BABYLON.serialize("useParallax")
  37386. ], StandardMaterial.prototype, "_useParallax", void 0);
  37387. __decorate([
  37388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37389. ], StandardMaterial.prototype, "useParallax", void 0);
  37390. __decorate([
  37391. BABYLON.serialize("useParallaxOcclusion")
  37392. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  37393. __decorate([
  37394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37395. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  37396. __decorate([
  37397. BABYLON.serialize()
  37398. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  37399. __decorate([
  37400. BABYLON.serialize("roughness")
  37401. ], StandardMaterial.prototype, "_roughness", void 0);
  37402. __decorate([
  37403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37404. ], StandardMaterial.prototype, "roughness", void 0);
  37405. __decorate([
  37406. BABYLON.serialize()
  37407. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  37408. __decorate([
  37409. BABYLON.serialize()
  37410. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  37411. __decorate([
  37412. BABYLON.serialize("useLightmapAsShadowmap")
  37413. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  37414. __decorate([
  37415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37416. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37417. __decorate([
  37418. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  37419. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  37420. __decorate([
  37421. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37422. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  37423. __decorate([
  37424. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  37425. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  37426. __decorate([
  37427. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37428. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  37429. __decorate([
  37430. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  37431. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  37432. __decorate([
  37433. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37434. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  37435. __decorate([
  37436. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  37437. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  37438. __decorate([
  37439. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37440. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  37441. __decorate([
  37442. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  37443. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  37444. __decorate([
  37445. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37446. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  37447. __decorate([
  37448. BABYLON.serialize("useReflectionFresnelFromSpecular")
  37449. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  37450. __decorate([
  37451. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37452. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  37453. __decorate([
  37454. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  37455. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  37456. __decorate([
  37457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37458. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  37459. __decorate([
  37460. BABYLON.serialize("maxSimultaneousLights")
  37461. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  37462. __decorate([
  37463. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37464. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  37465. __decorate([
  37466. BABYLON.serialize("invertNormalMapX")
  37467. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  37468. __decorate([
  37469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37470. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  37471. __decorate([
  37472. BABYLON.serialize("invertNormalMapY")
  37473. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  37474. __decorate([
  37475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37476. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  37477. __decorate([
  37478. BABYLON.serialize("twoSidedLighting")
  37479. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  37480. __decorate([
  37481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37482. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  37483. __decorate([
  37484. BABYLON.serialize()
  37485. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  37486. return StandardMaterial;
  37487. }(BABYLON.PushMaterial));
  37488. BABYLON.StandardMaterial = StandardMaterial;
  37489. })(BABYLON || (BABYLON = {}));
  37490. //# sourceMappingURL=babylon.standardMaterial.js.map
  37491. var BABYLON;
  37492. (function (BABYLON) {
  37493. var PBRMaterialDefines = /** @class */ (function (_super) {
  37494. __extends(PBRMaterialDefines, _super);
  37495. function PBRMaterialDefines() {
  37496. var _this = _super.call(this) || this;
  37497. _this.PBR = true;
  37498. _this.MAINUV1 = false;
  37499. _this.MAINUV2 = false;
  37500. _this.UV1 = false;
  37501. _this.UV2 = false;
  37502. _this.ALBEDO = false;
  37503. _this.ALBEDODIRECTUV = 0;
  37504. _this.VERTEXCOLOR = false;
  37505. _this.AMBIENT = false;
  37506. _this.AMBIENTDIRECTUV = 0;
  37507. _this.AMBIENTINGRAYSCALE = false;
  37508. _this.OPACITY = false;
  37509. _this.VERTEXALPHA = false;
  37510. _this.OPACITYDIRECTUV = 0;
  37511. _this.OPACITYRGB = false;
  37512. _this.ALPHATEST = false;
  37513. _this.DEPTHPREPASS = false;
  37514. _this.ALPHABLEND = false;
  37515. _this.ALPHAFROMALBEDO = false;
  37516. _this.ALPHATESTVALUE = 0.5;
  37517. _this.SPECULAROVERALPHA = false;
  37518. _this.RADIANCEOVERALPHA = false;
  37519. _this.ALPHAFRESNEL = false;
  37520. _this.LINEARALPHAFRESNEL = false;
  37521. _this.PREMULTIPLYALPHA = false;
  37522. _this.EMISSIVE = false;
  37523. _this.EMISSIVEDIRECTUV = 0;
  37524. _this.REFLECTIVITY = false;
  37525. _this.REFLECTIVITYDIRECTUV = 0;
  37526. _this.SPECULARTERM = false;
  37527. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  37528. _this.MICROSURFACEAUTOMATIC = false;
  37529. _this.LODBASEDMICROSFURACE = false;
  37530. _this.MICROSURFACEMAP = false;
  37531. _this.MICROSURFACEMAPDIRECTUV = 0;
  37532. _this.METALLICWORKFLOW = false;
  37533. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  37534. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  37535. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  37536. _this.AOSTOREINMETALMAPRED = false;
  37537. _this.ENVIRONMENTBRDF = false;
  37538. _this.NORMAL = false;
  37539. _this.TANGENT = false;
  37540. _this.BUMP = false;
  37541. _this.BUMPDIRECTUV = 0;
  37542. _this.PARALLAX = false;
  37543. _this.PARALLAXOCCLUSION = false;
  37544. _this.NORMALXYSCALE = true;
  37545. _this.LIGHTMAP = false;
  37546. _this.LIGHTMAPDIRECTUV = 0;
  37547. _this.USELIGHTMAPASSHADOWMAP = false;
  37548. _this.REFLECTION = false;
  37549. _this.REFLECTIONMAP_3D = false;
  37550. _this.REFLECTIONMAP_SPHERICAL = false;
  37551. _this.REFLECTIONMAP_PLANAR = false;
  37552. _this.REFLECTIONMAP_CUBIC = false;
  37553. _this.REFLECTIONMAP_PROJECTION = false;
  37554. _this.REFLECTIONMAP_SKYBOX = false;
  37555. _this.REFLECTIONMAP_EXPLICIT = false;
  37556. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37557. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37558. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37559. _this.INVERTCUBICMAP = false;
  37560. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37561. _this.USESPHERICALINVERTEX = false;
  37562. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37563. _this.LODINREFLECTIONALPHA = false;
  37564. _this.GAMMAREFLECTION = false;
  37565. _this.RADIANCEOCCLUSION = false;
  37566. _this.HORIZONOCCLUSION = false;
  37567. _this.REFRACTION = false;
  37568. _this.REFRACTIONMAP_3D = false;
  37569. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37570. _this.LODINREFRACTIONALPHA = false;
  37571. _this.GAMMAREFRACTION = false;
  37572. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37573. _this.INSTANCES = false;
  37574. _this.NUM_BONE_INFLUENCERS = 0;
  37575. _this.BonesPerMesh = 0;
  37576. _this.NONUNIFORMSCALING = false;
  37577. _this.MORPHTARGETS = false;
  37578. _this.MORPHTARGETS_NORMAL = false;
  37579. _this.MORPHTARGETS_TANGENT = false;
  37580. _this.NUM_MORPH_INFLUENCERS = 0;
  37581. _this.IMAGEPROCESSING = false;
  37582. _this.VIGNETTE = false;
  37583. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37584. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37585. _this.TONEMAPPING = false;
  37586. _this.CONTRAST = false;
  37587. _this.COLORCURVES = false;
  37588. _this.COLORGRADING = false;
  37589. _this.COLORGRADING3D = false;
  37590. _this.SAMPLER3DGREENDEPTH = false;
  37591. _this.SAMPLER3DBGRMAP = false;
  37592. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37593. _this.EXPOSURE = false;
  37594. _this.USEPHYSICALLIGHTFALLOFF = false;
  37595. _this.TWOSIDEDLIGHTING = false;
  37596. _this.SHADOWFLOAT = false;
  37597. _this.CLIPPLANE = false;
  37598. _this.POINTSIZE = false;
  37599. _this.FOG = false;
  37600. _this.LOGARITHMICDEPTH = false;
  37601. _this.FORCENORMALFORWARD = false;
  37602. _this.rebuild();
  37603. return _this;
  37604. }
  37605. PBRMaterialDefines.prototype.reset = function () {
  37606. _super.prototype.reset.call(this);
  37607. this.ALPHATESTVALUE = 0.5;
  37608. this.PBR = true;
  37609. };
  37610. return PBRMaterialDefines;
  37611. }(BABYLON.MaterialDefines));
  37612. /**
  37613. * The Physically based material base class of BJS.
  37614. *
  37615. * This offers the main features of a standard PBR material.
  37616. * For more information, please refer to the documentation :
  37617. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37618. */
  37619. var PBRBaseMaterial = /** @class */ (function (_super) {
  37620. __extends(PBRBaseMaterial, _super);
  37621. /**
  37622. * Instantiates a new PBRMaterial instance.
  37623. *
  37624. * @param name The material name
  37625. * @param scene The scene the material will be use in.
  37626. */
  37627. function PBRBaseMaterial(name, scene) {
  37628. var _this = _super.call(this, name, scene) || this;
  37629. /**
  37630. * Intensity of the direct lights e.g. the four lights available in your scene.
  37631. * This impacts both the direct diffuse and specular highlights.
  37632. */
  37633. _this._directIntensity = 1.0;
  37634. /**
  37635. * Intensity of the emissive part of the material.
  37636. * This helps controlling the emissive effect without modifying the emissive color.
  37637. */
  37638. _this._emissiveIntensity = 1.0;
  37639. /**
  37640. * Intensity of the environment e.g. how much the environment will light the object
  37641. * either through harmonics for rough material or through the refelction for shiny ones.
  37642. */
  37643. _this._environmentIntensity = 1.0;
  37644. /**
  37645. * This is a special control allowing the reduction of the specular highlights coming from the
  37646. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37647. */
  37648. _this._specularIntensity = 1.0;
  37649. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  37650. /**
  37651. * Debug Control allowing disabling the bump map on this material.
  37652. */
  37653. _this._disableBumpMap = false;
  37654. /**
  37655. * AKA Occlusion Texture Intensity in other nomenclature.
  37656. */
  37657. _this._ambientTextureStrength = 1.0;
  37658. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  37659. /**
  37660. * AKA Diffuse Color in other nomenclature.
  37661. */
  37662. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  37663. /**
  37664. * AKA Specular Color in other nomenclature.
  37665. */
  37666. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37667. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37668. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37669. /**
  37670. * AKA Glossiness in other nomenclature.
  37671. */
  37672. _this._microSurface = 0.9;
  37673. /**
  37674. * source material index of refraction (IOR)' / 'destination material IOR.
  37675. */
  37676. _this._indexOfRefraction = 0.66;
  37677. /**
  37678. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37679. */
  37680. _this._invertRefractionY = false;
  37681. /**
  37682. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37683. * Materials half opaque for instance using refraction could benefit from this control.
  37684. */
  37685. _this._linkRefractionWithTransparency = false;
  37686. _this._useLightmapAsShadowmap = false;
  37687. /**
  37688. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37689. * makes the reflect vector face the model (under horizon).
  37690. */
  37691. _this._useHorizonOcclusion = true;
  37692. /**
  37693. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37694. * too much the area relying on ambient texture to define their ambient occlusion.
  37695. */
  37696. _this._useRadianceOcclusion = true;
  37697. /**
  37698. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37699. */
  37700. _this._useAlphaFromAlbedoTexture = false;
  37701. /**
  37702. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37703. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37704. */
  37705. _this._useSpecularOverAlpha = true;
  37706. /**
  37707. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37708. */
  37709. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37710. /**
  37711. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37712. */
  37713. _this._useRoughnessFromMetallicTextureAlpha = true;
  37714. /**
  37715. * Specifies if the metallic texture contains the roughness information in its green channel.
  37716. */
  37717. _this._useRoughnessFromMetallicTextureGreen = false;
  37718. /**
  37719. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37720. */
  37721. _this._useMetallnessFromMetallicTextureBlue = false;
  37722. /**
  37723. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37724. */
  37725. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37726. /**
  37727. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37728. */
  37729. _this._useAmbientInGrayScale = false;
  37730. /**
  37731. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37732. * The material will try to infer what glossiness each pixel should be.
  37733. */
  37734. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37735. /**
  37736. * BJS is using an harcoded light falloff based on a manually sets up range.
  37737. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37738. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37739. */
  37740. _this._usePhysicalLightFalloff = true;
  37741. /**
  37742. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37743. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37744. */
  37745. _this._useRadianceOverAlpha = true;
  37746. /**
  37747. * Allows using the bump map in parallax mode.
  37748. */
  37749. _this._useParallax = false;
  37750. /**
  37751. * Allows using the bump map in parallax occlusion mode.
  37752. */
  37753. _this._useParallaxOcclusion = false;
  37754. /**
  37755. * Controls the scale bias of the parallax mode.
  37756. */
  37757. _this._parallaxScaleBias = 0.05;
  37758. /**
  37759. * If sets to true, disables all the lights affecting the material.
  37760. */
  37761. _this._disableLighting = false;
  37762. /**
  37763. * Number of Simultaneous lights allowed on the material.
  37764. */
  37765. _this._maxSimultaneousLights = 4;
  37766. /**
  37767. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37768. */
  37769. _this._invertNormalMapX = false;
  37770. /**
  37771. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37772. */
  37773. _this._invertNormalMapY = false;
  37774. /**
  37775. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37776. */
  37777. _this._twoSidedLighting = false;
  37778. /**
  37779. * Defines the alpha limits in alpha test mode.
  37780. */
  37781. _this._alphaCutOff = 0.4;
  37782. /**
  37783. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37784. */
  37785. _this._forceAlphaTest = false;
  37786. /**
  37787. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37788. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37789. */
  37790. _this._useAlphaFresnel = false;
  37791. /**
  37792. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37793. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37794. */
  37795. _this._useLinearAlphaFresnel = false;
  37796. /**
  37797. * The transparency mode of the material.
  37798. */
  37799. _this._transparencyMode = null;
  37800. /**
  37801. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37802. * from cos thetav and roughness:
  37803. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37804. */
  37805. _this._environmentBRDFTexture = null;
  37806. /**
  37807. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37808. */
  37809. _this._forceIrradianceInFragment = false;
  37810. /**
  37811. * Force normal to face away from face.
  37812. */
  37813. _this._forceNormalForward = false;
  37814. /**
  37815. * Force metallic workflow.
  37816. */
  37817. _this._forceMetallicWorkflow = false;
  37818. _this._renderTargets = new BABYLON.SmartArray(16);
  37819. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37820. // Setup the default processing configuration to the scene.
  37821. _this._attachImageProcessingConfiguration(null);
  37822. _this.getRenderTargetTextures = function () {
  37823. _this._renderTargets.reset();
  37824. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37825. _this._renderTargets.push(_this._reflectionTexture);
  37826. }
  37827. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37828. _this._renderTargets.push(_this._refractionTexture);
  37829. }
  37830. return _this._renderTargets;
  37831. };
  37832. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37833. return _this;
  37834. }
  37835. /**
  37836. * Attaches a new image processing configuration to the PBR Material.
  37837. * @param configuration
  37838. */
  37839. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37840. var _this = this;
  37841. if (configuration === this._imageProcessingConfiguration) {
  37842. return;
  37843. }
  37844. // Detaches observer.
  37845. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37846. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37847. }
  37848. // Pick the scene configuration if needed.
  37849. if (!configuration) {
  37850. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37851. }
  37852. else {
  37853. this._imageProcessingConfiguration = configuration;
  37854. }
  37855. // Attaches observer.
  37856. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37857. _this._markAllSubMeshesAsImageProcessingDirty();
  37858. });
  37859. };
  37860. PBRBaseMaterial.prototype.getClassName = function () {
  37861. return "PBRBaseMaterial";
  37862. };
  37863. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37864. get: function () {
  37865. return this._useLogarithmicDepth;
  37866. },
  37867. set: function (value) {
  37868. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37869. },
  37870. enumerable: true,
  37871. configurable: true
  37872. });
  37873. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  37874. /**
  37875. * Gets the current transparency mode.
  37876. */
  37877. get: function () {
  37878. return this._transparencyMode;
  37879. },
  37880. /**
  37881. * Sets the transparency mode of the material.
  37882. */
  37883. set: function (value) {
  37884. if (this._transparencyMode === value) {
  37885. return;
  37886. }
  37887. this._transparencyMode = value;
  37888. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  37889. this._markAllSubMeshesAsTexturesDirty();
  37890. },
  37891. enumerable: true,
  37892. configurable: true
  37893. });
  37894. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  37895. /**
  37896. * Returns true if alpha blending should be disabled.
  37897. */
  37898. get: function () {
  37899. return (this._linkRefractionWithTransparency ||
  37900. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  37901. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  37902. },
  37903. enumerable: true,
  37904. configurable: true
  37905. });
  37906. /**
  37907. * Specifies whether or not this material should be rendered in alpha blend mode.
  37908. */
  37909. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37910. if (this._disableAlphaBlending) {
  37911. return false;
  37912. }
  37913. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37914. };
  37915. /**
  37916. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  37917. */
  37918. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  37919. if (this._disableAlphaBlending) {
  37920. return false;
  37921. }
  37922. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  37923. };
  37924. /**
  37925. * Specifies whether or not this material should be rendered in alpha test mode.
  37926. */
  37927. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37928. if (this._forceAlphaTest) {
  37929. return true;
  37930. }
  37931. if (this._linkRefractionWithTransparency) {
  37932. return false;
  37933. }
  37934. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  37935. };
  37936. /**
  37937. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  37938. */
  37939. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37940. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37941. };
  37942. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37943. return this._albedoTexture;
  37944. };
  37945. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37946. var _this = this;
  37947. if (subMesh.effect && this.isFrozen) {
  37948. if (this._wasPreviouslyReady) {
  37949. return true;
  37950. }
  37951. }
  37952. if (!subMesh._materialDefines) {
  37953. subMesh._materialDefines = new PBRMaterialDefines();
  37954. }
  37955. var scene = this.getScene();
  37956. var defines = subMesh._materialDefines;
  37957. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37958. if (defines._renderId === scene.getRenderId()) {
  37959. return true;
  37960. }
  37961. }
  37962. var engine = scene.getEngine();
  37963. // Lights
  37964. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37965. defines._needNormals = true;
  37966. // Textures
  37967. if (defines._areTexturesDirty) {
  37968. defines._needUVs = false;
  37969. if (scene.texturesEnabled) {
  37970. if (scene.getEngine().getCaps().textureLOD) {
  37971. defines.LODBASEDMICROSFURACE = true;
  37972. }
  37973. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37974. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  37975. return false;
  37976. }
  37977. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  37978. }
  37979. else {
  37980. defines.ALBEDO = false;
  37981. }
  37982. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37983. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37984. return false;
  37985. }
  37986. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37987. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  37988. }
  37989. else {
  37990. defines.AMBIENT = false;
  37991. }
  37992. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37993. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37994. return false;
  37995. }
  37996. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37997. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37998. }
  37999. else {
  38000. defines.OPACITY = false;
  38001. }
  38002. var reflectionTexture = this._getReflectionTexture();
  38003. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38004. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38005. return false;
  38006. }
  38007. defines.REFLECTION = true;
  38008. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38009. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38010. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38011. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38012. defines.INVERTCUBICMAP = true;
  38013. }
  38014. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38015. switch (reflectionTexture.coordinatesMode) {
  38016. case BABYLON.Texture.CUBIC_MODE:
  38017. case BABYLON.Texture.INVCUBIC_MODE:
  38018. defines.REFLECTIONMAP_CUBIC = true;
  38019. break;
  38020. case BABYLON.Texture.EXPLICIT_MODE:
  38021. defines.REFLECTIONMAP_EXPLICIT = true;
  38022. break;
  38023. case BABYLON.Texture.PLANAR_MODE:
  38024. defines.REFLECTIONMAP_PLANAR = true;
  38025. break;
  38026. case BABYLON.Texture.PROJECTION_MODE:
  38027. defines.REFLECTIONMAP_PROJECTION = true;
  38028. break;
  38029. case BABYLON.Texture.SKYBOX_MODE:
  38030. defines.REFLECTIONMAP_SKYBOX = true;
  38031. break;
  38032. case BABYLON.Texture.SPHERICAL_MODE:
  38033. defines.REFLECTIONMAP_SPHERICAL = true;
  38034. break;
  38035. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38036. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38037. break;
  38038. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38039. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38040. break;
  38041. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38042. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38043. break;
  38044. }
  38045. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38046. if (reflectionTexture.sphericalPolynomial) {
  38047. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38048. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38049. defines.USESPHERICALINVERTEX = false;
  38050. }
  38051. else {
  38052. defines.USESPHERICALINVERTEX = true;
  38053. }
  38054. }
  38055. }
  38056. }
  38057. else {
  38058. defines.REFLECTION = false;
  38059. defines.REFLECTIONMAP_3D = false;
  38060. defines.REFLECTIONMAP_SPHERICAL = false;
  38061. defines.REFLECTIONMAP_PLANAR = false;
  38062. defines.REFLECTIONMAP_CUBIC = false;
  38063. defines.REFLECTIONMAP_PROJECTION = false;
  38064. defines.REFLECTIONMAP_SKYBOX = false;
  38065. defines.REFLECTIONMAP_EXPLICIT = false;
  38066. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38067. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38068. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38069. defines.INVERTCUBICMAP = false;
  38070. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38071. defines.USESPHERICALINVERTEX = false;
  38072. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38073. defines.LODINREFLECTIONALPHA = false;
  38074. defines.GAMMAREFLECTION = false;
  38075. }
  38076. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38077. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38078. return false;
  38079. }
  38080. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38081. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38082. }
  38083. else {
  38084. defines.LIGHTMAP = false;
  38085. }
  38086. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38087. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38088. return false;
  38089. }
  38090. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38091. }
  38092. else {
  38093. defines.EMISSIVE = false;
  38094. }
  38095. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38096. if (this._metallicTexture) {
  38097. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38098. return false;
  38099. }
  38100. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38101. defines.METALLICWORKFLOW = true;
  38102. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38103. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38104. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38105. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38106. }
  38107. else if (this._reflectivityTexture) {
  38108. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38109. return false;
  38110. }
  38111. defines.METALLICWORKFLOW = false;
  38112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38113. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38114. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38115. }
  38116. else {
  38117. defines.METALLICWORKFLOW = false;
  38118. defines.REFLECTIVITY = false;
  38119. }
  38120. if (this._microSurfaceTexture) {
  38121. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38122. return false;
  38123. }
  38124. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38125. }
  38126. else {
  38127. defines.MICROSURFACEMAP = false;
  38128. }
  38129. }
  38130. else {
  38131. defines.REFLECTIVITY = false;
  38132. defines.MICROSURFACEMAP = false;
  38133. }
  38134. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38135. // Bump texure can not be none blocking.
  38136. if (!this._bumpTexture.isReady()) {
  38137. return false;
  38138. }
  38139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38140. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38141. defines.PARALLAX = true;
  38142. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38143. }
  38144. else {
  38145. defines.PARALLAX = false;
  38146. }
  38147. }
  38148. else {
  38149. defines.BUMP = false;
  38150. }
  38151. var refractionTexture = this._getRefractionTexture();
  38152. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38153. if (!refractionTexture.isReadyOrNotBlocking()) {
  38154. return false;
  38155. }
  38156. defines.REFRACTION = true;
  38157. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38158. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38159. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38160. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38161. if (this._linkRefractionWithTransparency) {
  38162. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38163. }
  38164. }
  38165. else {
  38166. defines.REFRACTION = false;
  38167. }
  38168. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38169. // This is blocking.
  38170. if (!this._environmentBRDFTexture.isReady()) {
  38171. return false;
  38172. }
  38173. defines.ENVIRONMENTBRDF = true;
  38174. }
  38175. else {
  38176. defines.ENVIRONMENTBRDF = false;
  38177. }
  38178. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38179. defines.ALPHAFROMALBEDO = true;
  38180. }
  38181. else {
  38182. defines.ALPHAFROMALBEDO = false;
  38183. }
  38184. }
  38185. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38186. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38187. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38188. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38189. defines.METALLICWORKFLOW = true;
  38190. }
  38191. else {
  38192. defines.METALLICWORKFLOW = false;
  38193. }
  38194. if (!this.backFaceCulling && this._twoSidedLighting) {
  38195. defines.TWOSIDEDLIGHTING = true;
  38196. }
  38197. else {
  38198. defines.TWOSIDEDLIGHTING = false;
  38199. }
  38200. defines.ALPHATESTVALUE = this._alphaCutOff;
  38201. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38202. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38203. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38204. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38205. }
  38206. if (defines._areImageProcessingDirty) {
  38207. if (!this._imageProcessingConfiguration.isReady()) {
  38208. return false;
  38209. }
  38210. this._imageProcessingConfiguration.prepareDefines(defines);
  38211. }
  38212. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38213. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38214. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38215. // Misc.
  38216. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  38217. // Values that need to be evaluated on every frame
  38218. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest);
  38219. // Attribs
  38220. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38221. var bufferMesh = null;
  38222. if (mesh instanceof BABYLON.InstancedMesh) {
  38223. bufferMesh = mesh.sourceMesh;
  38224. }
  38225. else if (mesh instanceof BABYLON.Mesh) {
  38226. bufferMesh = mesh;
  38227. }
  38228. if (bufferMesh) {
  38229. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38230. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38231. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38232. var normals = normalVertexBuffer.getData();
  38233. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38234. var strideSize = normalVertexBuffer.getStrideSize();
  38235. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38236. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38237. defines.NORMAL = false;
  38238. }
  38239. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38240. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38241. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38242. var tangents = tangentVertexBuffer.getData();
  38243. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38244. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38245. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38246. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38247. defines.TANGENT = false;
  38248. }
  38249. }
  38250. }
  38251. else {
  38252. if (!scene.getEngine().getCaps().standardDerivatives) {
  38253. bufferMesh.createNormals(true);
  38254. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38255. }
  38256. }
  38257. }
  38258. }
  38259. // Get correct effect
  38260. if (defines.isDirty) {
  38261. defines.markAsProcessed();
  38262. scene.resetCachedMaterial();
  38263. // Fallbacks
  38264. var fallbacks = new BABYLON.EffectFallbacks();
  38265. var fallbackRank = 0;
  38266. if (defines.USESPHERICALINVERTEX) {
  38267. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38268. }
  38269. if (defines.FOG) {
  38270. fallbacks.addFallback(fallbackRank, "FOG");
  38271. }
  38272. if (defines.POINTSIZE) {
  38273. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38274. }
  38275. if (defines.LOGARITHMICDEPTH) {
  38276. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38277. }
  38278. if (defines.PARALLAX) {
  38279. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38280. }
  38281. if (defines.PARALLAXOCCLUSION) {
  38282. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38283. }
  38284. if (defines.ENVIRONMENTBRDF) {
  38285. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38286. }
  38287. if (defines.TANGENT) {
  38288. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38289. }
  38290. if (defines.BUMP) {
  38291. fallbacks.addFallback(fallbackRank++, "BUMP");
  38292. }
  38293. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38294. if (defines.SPECULARTERM) {
  38295. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38296. }
  38297. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38298. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38299. }
  38300. if (defines.LIGHTMAP) {
  38301. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38302. }
  38303. if (defines.NORMAL) {
  38304. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38305. }
  38306. if (defines.AMBIENT) {
  38307. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38308. }
  38309. if (defines.EMISSIVE) {
  38310. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38311. }
  38312. if (defines.VERTEXCOLOR) {
  38313. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  38314. }
  38315. if (defines.NUM_BONE_INFLUENCERS > 0) {
  38316. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  38317. }
  38318. if (defines.MORPHTARGETS) {
  38319. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  38320. }
  38321. //Attributes
  38322. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38323. if (defines.NORMAL) {
  38324. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38325. }
  38326. if (defines.TANGENT) {
  38327. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38328. }
  38329. if (defines.UV1) {
  38330. attribs.push(BABYLON.VertexBuffer.UVKind);
  38331. }
  38332. if (defines.UV2) {
  38333. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38334. }
  38335. if (defines.VERTEXCOLOR) {
  38336. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38337. }
  38338. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38339. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38340. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38341. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  38342. "vFogInfos", "vFogColor", "pointSize",
  38343. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38344. "mBones",
  38345. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38346. "vLightingIntensity",
  38347. "logarithmicDepthConstant",
  38348. "vSphericalX", "vSphericalY", "vSphericalZ",
  38349. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  38350. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  38351. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  38352. "vTangentSpaceParams"
  38353. ];
  38354. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  38355. "bumpSampler", "lightmapSampler", "opacitySampler",
  38356. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  38357. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  38358. "microSurfaceSampler", "environmentBrdfSampler"];
  38359. var uniformBuffers = ["Material", "Scene"];
  38360. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38361. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38362. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38363. uniformsNames: uniforms,
  38364. uniformBuffersNames: uniformBuffers,
  38365. samplers: samplers,
  38366. defines: defines,
  38367. maxSimultaneousLights: this._maxSimultaneousLights
  38368. });
  38369. var onCompiled = function (effect) {
  38370. if (_this.onCompiled) {
  38371. _this.onCompiled(effect);
  38372. }
  38373. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  38374. };
  38375. var join = defines.toString();
  38376. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  38377. attributes: attribs,
  38378. uniformsNames: uniforms,
  38379. uniformBuffersNames: uniformBuffers,
  38380. samplers: samplers,
  38381. defines: join,
  38382. fallbacks: fallbacks,
  38383. onCompiled: onCompiled,
  38384. onError: this.onError,
  38385. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38386. }, engine), defines);
  38387. this.buildUniformLayout();
  38388. }
  38389. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38390. return false;
  38391. }
  38392. defines._renderId = scene.getRenderId();
  38393. this._wasPreviouslyReady = true;
  38394. return true;
  38395. };
  38396. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  38397. // Order is important !
  38398. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  38399. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  38400. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38401. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38402. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38403. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  38404. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  38405. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38406. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38407. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38408. this._uniformBuffer.addUniform("albedoMatrix", 16);
  38409. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38410. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38411. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38412. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38413. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  38414. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  38415. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38416. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38417. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38418. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38419. this._uniformBuffer.addUniform("vReflectionColor", 3);
  38420. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  38421. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  38422. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  38423. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  38424. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  38425. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38426. this._uniformBuffer.addUniform("pointSize", 1);
  38427. this._uniformBuffer.create();
  38428. };
  38429. PBRBaseMaterial.prototype.unbind = function () {
  38430. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38431. this._uniformBuffer.setTexture("reflectionSampler", null);
  38432. }
  38433. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38434. this._uniformBuffer.setTexture("refractionSampler", null);
  38435. }
  38436. _super.prototype.unbind.call(this);
  38437. };
  38438. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38439. this._activeEffect.setMatrix("world", world);
  38440. };
  38441. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38442. var scene = this.getScene();
  38443. var defines = subMesh._materialDefines;
  38444. if (!defines) {
  38445. return;
  38446. }
  38447. var effect = subMesh.effect;
  38448. if (!effect) {
  38449. return;
  38450. }
  38451. this._activeEffect = effect;
  38452. // Matrices
  38453. this.bindOnlyWorldMatrix(world);
  38454. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38455. // Bones
  38456. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  38457. var reflectionTexture = null;
  38458. if (mustRebind) {
  38459. this._uniformBuffer.bindToEffect(effect, "Material");
  38460. this.bindViewProjection(effect);
  38461. reflectionTexture = this._getReflectionTexture();
  38462. var refractionTexture = this._getRefractionTexture();
  38463. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38464. // Texture uniforms
  38465. if (scene.texturesEnabled) {
  38466. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38467. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  38468. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  38469. }
  38470. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38471. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  38472. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38473. }
  38474. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38475. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38476. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38477. }
  38478. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38479. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  38480. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  38481. var polynomials = reflectionTexture.sphericalPolynomial;
  38482. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  38483. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  38484. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  38485. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  38486. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  38487. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  38488. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  38489. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  38490. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  38491. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  38492. }
  38493. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  38494. }
  38495. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38496. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38497. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38498. }
  38499. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38500. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38501. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38502. }
  38503. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38504. if (this._metallicTexture) {
  38505. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  38506. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  38507. }
  38508. else if (this._reflectivityTexture) {
  38509. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  38510. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  38511. }
  38512. if (this._microSurfaceTexture) {
  38513. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  38514. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  38515. }
  38516. }
  38517. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38518. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  38519. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38520. if (scene._mirroredCameraPosition) {
  38521. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38522. }
  38523. else {
  38524. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38525. }
  38526. }
  38527. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38528. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  38529. var depth = 1.0;
  38530. if (!refractionTexture.isCube) {
  38531. if (refractionTexture.depth) {
  38532. depth = refractionTexture.depth;
  38533. }
  38534. }
  38535. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  38536. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  38537. }
  38538. }
  38539. // Point size
  38540. if (this.pointsCloud) {
  38541. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38542. }
  38543. // Colors
  38544. if (defines.METALLICWORKFLOW) {
  38545. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  38546. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  38547. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  38548. }
  38549. else {
  38550. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  38551. }
  38552. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  38553. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  38554. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  38555. // Misc
  38556. this._lightingInfos.x = this._directIntensity;
  38557. this._lightingInfos.y = this._emissiveIntensity;
  38558. this._lightingInfos.z = this._environmentIntensity;
  38559. this._lightingInfos.w = this._specularIntensity;
  38560. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  38561. }
  38562. // Textures
  38563. if (scene.texturesEnabled) {
  38564. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38565. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  38566. }
  38567. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38568. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  38569. }
  38570. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38571. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  38572. }
  38573. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38574. if (defines.LODBASEDMICROSFURACE) {
  38575. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  38576. }
  38577. else {
  38578. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  38579. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  38580. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  38581. }
  38582. }
  38583. if (defines.ENVIRONMENTBRDF) {
  38584. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  38585. }
  38586. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38587. if (defines.LODBASEDMICROSFURACE) {
  38588. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  38589. }
  38590. else {
  38591. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  38592. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  38593. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  38594. }
  38595. }
  38596. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38597. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  38598. }
  38599. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38600. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  38601. }
  38602. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38603. if (this._metallicTexture) {
  38604. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  38605. }
  38606. else if (this._reflectivityTexture) {
  38607. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  38608. }
  38609. if (this._microSurfaceTexture) {
  38610. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  38611. }
  38612. }
  38613. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38614. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  38615. }
  38616. }
  38617. // Clip plane
  38618. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  38619. // Colors
  38620. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  38621. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38622. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  38623. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  38624. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38625. }
  38626. if (mustRebind || !this.isFrozen) {
  38627. // Lights
  38628. if (scene.lightsEnabled && !this._disableLighting) {
  38629. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  38630. }
  38631. // View
  38632. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  38633. this.bindView(effect);
  38634. }
  38635. // Fog
  38636. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  38637. // Morph targets
  38638. if (defines.NUM_MORPH_INFLUENCERS) {
  38639. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  38640. }
  38641. // image processing
  38642. this._imageProcessingConfiguration.bind(this._activeEffect);
  38643. // Log. depth
  38644. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  38645. }
  38646. this._uniformBuffer.update();
  38647. this._afterBind(mesh);
  38648. };
  38649. PBRBaseMaterial.prototype.getAnimatables = function () {
  38650. var results = [];
  38651. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  38652. results.push(this._albedoTexture);
  38653. }
  38654. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38655. results.push(this._ambientTexture);
  38656. }
  38657. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38658. results.push(this._opacityTexture);
  38659. }
  38660. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38661. results.push(this._reflectionTexture);
  38662. }
  38663. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  38664. results.push(this._emissiveTexture);
  38665. }
  38666. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  38667. results.push(this._metallicTexture);
  38668. }
  38669. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  38670. results.push(this._reflectivityTexture);
  38671. }
  38672. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  38673. results.push(this._bumpTexture);
  38674. }
  38675. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  38676. results.push(this._lightmapTexture);
  38677. }
  38678. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38679. results.push(this._refractionTexture);
  38680. }
  38681. return results;
  38682. };
  38683. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  38684. if (this._reflectionTexture) {
  38685. return this._reflectionTexture;
  38686. }
  38687. return this.getScene().environmentTexture;
  38688. };
  38689. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  38690. if (this._refractionTexture) {
  38691. return this._refractionTexture;
  38692. }
  38693. if (this._linkRefractionWithTransparency) {
  38694. return this.getScene().environmentTexture;
  38695. }
  38696. return null;
  38697. };
  38698. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38699. if (forceDisposeTextures) {
  38700. if (this._albedoTexture) {
  38701. this._albedoTexture.dispose();
  38702. }
  38703. if (this._ambientTexture) {
  38704. this._ambientTexture.dispose();
  38705. }
  38706. if (this._opacityTexture) {
  38707. this._opacityTexture.dispose();
  38708. }
  38709. if (this._reflectionTexture) {
  38710. this._reflectionTexture.dispose();
  38711. }
  38712. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  38713. this._environmentBRDFTexture.dispose();
  38714. }
  38715. if (this._emissiveTexture) {
  38716. this._emissiveTexture.dispose();
  38717. }
  38718. if (this._metallicTexture) {
  38719. this._metallicTexture.dispose();
  38720. }
  38721. if (this._reflectivityTexture) {
  38722. this._reflectivityTexture.dispose();
  38723. }
  38724. if (this._bumpTexture) {
  38725. this._bumpTexture.dispose();
  38726. }
  38727. if (this._lightmapTexture) {
  38728. this._lightmapTexture.dispose();
  38729. }
  38730. if (this._refractionTexture) {
  38731. this._refractionTexture.dispose();
  38732. }
  38733. }
  38734. this._renderTargets.dispose();
  38735. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38736. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38737. }
  38738. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38739. };
  38740. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  38741. __decorate([
  38742. BABYLON.serializeAsImageProcessingConfiguration()
  38743. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  38744. __decorate([
  38745. BABYLON.serialize()
  38746. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  38747. __decorate([
  38748. BABYLON.serialize()
  38749. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  38750. return PBRBaseMaterial;
  38751. }(BABYLON.PushMaterial));
  38752. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  38753. })(BABYLON || (BABYLON = {}));
  38754. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  38755. var BABYLON;
  38756. (function (BABYLON) {
  38757. /**
  38758. * The Physically based simple base material of BJS.
  38759. *
  38760. * This enables better naming and convention enforcements on top of the pbrMaterial.
  38761. * It is used as the base class for both the specGloss and metalRough conventions.
  38762. */
  38763. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  38764. __extends(PBRBaseSimpleMaterial, _super);
  38765. /**
  38766. * Instantiates a new PBRMaterial instance.
  38767. *
  38768. * @param name The material name
  38769. * @param scene The scene the material will be use in.
  38770. */
  38771. function PBRBaseSimpleMaterial(name, scene) {
  38772. var _this = _super.call(this, name, scene) || this;
  38773. /**
  38774. * Number of Simultaneous lights allowed on the material.
  38775. */
  38776. _this.maxSimultaneousLights = 4;
  38777. /**
  38778. * If sets to true, disables all the lights affecting the material.
  38779. */
  38780. _this.disableLighting = false;
  38781. /**
  38782. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38783. */
  38784. _this.invertNormalMapX = false;
  38785. /**
  38786. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38787. */
  38788. _this.invertNormalMapY = false;
  38789. /**
  38790. * Emissivie color used to self-illuminate the model.
  38791. */
  38792. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38793. /**
  38794. * Occlusion Channel Strenght.
  38795. */
  38796. _this.occlusionStrength = 1.0;
  38797. _this.useLightmapAsShadowmap = false;
  38798. _this._useAlphaFromAlbedoTexture = true;
  38799. _this._useAmbientInGrayScale = true;
  38800. return _this;
  38801. }
  38802. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38803. /**
  38804. * Gets the current double sided mode.
  38805. */
  38806. get: function () {
  38807. return this._twoSidedLighting;
  38808. },
  38809. /**
  38810. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38811. */
  38812. set: function (value) {
  38813. if (this._twoSidedLighting === value) {
  38814. return;
  38815. }
  38816. this._twoSidedLighting = value;
  38817. this.backFaceCulling = !value;
  38818. this._markAllSubMeshesAsTexturesDirty();
  38819. },
  38820. enumerable: true,
  38821. configurable: true
  38822. });
  38823. /**
  38824. * Return the active textures of the material.
  38825. */
  38826. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38827. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38828. if (this.environmentTexture) {
  38829. activeTextures.push(this.environmentTexture);
  38830. }
  38831. if (this.normalTexture) {
  38832. activeTextures.push(this.normalTexture);
  38833. }
  38834. if (this.emissiveTexture) {
  38835. activeTextures.push(this.emissiveTexture);
  38836. }
  38837. if (this.occlusionTexture) {
  38838. activeTextures.push(this.occlusionTexture);
  38839. }
  38840. if (this.lightmapTexture) {
  38841. activeTextures.push(this.lightmapTexture);
  38842. }
  38843. return activeTextures;
  38844. };
  38845. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  38846. if (_super.prototype.hasTexture.call(this, texture)) {
  38847. return true;
  38848. }
  38849. if (this.lightmapTexture === texture) {
  38850. return true;
  38851. }
  38852. return false;
  38853. };
  38854. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  38855. return "PBRBaseSimpleMaterial";
  38856. };
  38857. __decorate([
  38858. BABYLON.serialize(),
  38859. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38860. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  38861. __decorate([
  38862. BABYLON.serialize(),
  38863. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38864. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  38865. __decorate([
  38866. BABYLON.serializeAsTexture(),
  38867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  38868. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  38869. __decorate([
  38870. BABYLON.serialize(),
  38871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38872. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  38873. __decorate([
  38874. BABYLON.serialize(),
  38875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38876. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  38877. __decorate([
  38878. BABYLON.serializeAsTexture(),
  38879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  38880. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  38881. __decorate([
  38882. BABYLON.serializeAsColor3("emissive"),
  38883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38884. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  38885. __decorate([
  38886. BABYLON.serializeAsTexture(),
  38887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38888. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  38889. __decorate([
  38890. BABYLON.serialize(),
  38891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  38892. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  38893. __decorate([
  38894. BABYLON.serializeAsTexture(),
  38895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  38896. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  38897. __decorate([
  38898. BABYLON.serialize(),
  38899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  38900. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  38901. __decorate([
  38902. BABYLON.serialize()
  38903. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  38904. __decorate([
  38905. BABYLON.serializeAsTexture(),
  38906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38907. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  38908. __decorate([
  38909. BABYLON.serialize(),
  38910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38911. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38912. return PBRBaseSimpleMaterial;
  38913. }(BABYLON.PBRBaseMaterial));
  38914. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38915. })(BABYLON || (BABYLON = {}));
  38916. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38917. var BABYLON;
  38918. (function (BABYLON) {
  38919. /**
  38920. * The Physically based material of BJS.
  38921. *
  38922. * This offers the main features of a standard PBR material.
  38923. * For more information, please refer to the documentation :
  38924. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38925. */
  38926. var PBRMaterial = /** @class */ (function (_super) {
  38927. __extends(PBRMaterial, _super);
  38928. /**
  38929. * Instantiates a new PBRMaterial instance.
  38930. *
  38931. * @param name The material name
  38932. * @param scene The scene the material will be use in.
  38933. */
  38934. function PBRMaterial(name, scene) {
  38935. var _this = _super.call(this, name, scene) || this;
  38936. /**
  38937. * Intensity of the direct lights e.g. the four lights available in your scene.
  38938. * This impacts both the direct diffuse and specular highlights.
  38939. */
  38940. _this.directIntensity = 1.0;
  38941. /**
  38942. * Intensity of the emissive part of the material.
  38943. * This helps controlling the emissive effect without modifying the emissive color.
  38944. */
  38945. _this.emissiveIntensity = 1.0;
  38946. /**
  38947. * Intensity of the environment e.g. how much the environment will light the object
  38948. * either through harmonics for rough material or through the refelction for shiny ones.
  38949. */
  38950. _this.environmentIntensity = 1.0;
  38951. /**
  38952. * This is a special control allowing the reduction of the specular highlights coming from the
  38953. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38954. */
  38955. _this.specularIntensity = 1.0;
  38956. /**
  38957. * Debug Control allowing disabling the bump map on this material.
  38958. */
  38959. _this.disableBumpMap = false;
  38960. /**
  38961. * AKA Occlusion Texture Intensity in other nomenclature.
  38962. */
  38963. _this.ambientTextureStrength = 1.0;
  38964. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38965. /**
  38966. * AKA Diffuse Color in other nomenclature.
  38967. */
  38968. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  38969. /**
  38970. * AKA Specular Color in other nomenclature.
  38971. */
  38972. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38973. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  38974. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38975. /**
  38976. * AKA Glossiness in other nomenclature.
  38977. */
  38978. _this.microSurface = 1.0;
  38979. /**
  38980. * source material index of refraction (IOR)' / 'destination material IOR.
  38981. */
  38982. _this.indexOfRefraction = 0.66;
  38983. /**
  38984. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38985. */
  38986. _this.invertRefractionY = false;
  38987. /**
  38988. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38989. * Materials half opaque for instance using refraction could benefit from this control.
  38990. */
  38991. _this.linkRefractionWithTransparency = false;
  38992. _this.useLightmapAsShadowmap = false;
  38993. /**
  38994. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38995. */
  38996. _this.useAlphaFromAlbedoTexture = false;
  38997. /**
  38998. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38999. */
  39000. _this.forceAlphaTest = false;
  39001. /**
  39002. * Defines the alpha limits in alpha test mode.
  39003. */
  39004. _this.alphaCutOff = 0.4;
  39005. /**
  39006. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39007. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39008. */
  39009. _this.useSpecularOverAlpha = true;
  39010. /**
  39011. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39012. */
  39013. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39014. /**
  39015. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39016. */
  39017. _this.useRoughnessFromMetallicTextureAlpha = true;
  39018. /**
  39019. * Specifies if the metallic texture contains the roughness information in its green channel.
  39020. */
  39021. _this.useRoughnessFromMetallicTextureGreen = false;
  39022. /**
  39023. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39024. */
  39025. _this.useMetallnessFromMetallicTextureBlue = false;
  39026. /**
  39027. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39028. */
  39029. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39030. /**
  39031. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39032. */
  39033. _this.useAmbientInGrayScale = false;
  39034. /**
  39035. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39036. * The material will try to infer what glossiness each pixel should be.
  39037. */
  39038. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39039. /**
  39040. * BJS is using an harcoded light falloff based on a manually sets up range.
  39041. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39042. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39043. */
  39044. _this.usePhysicalLightFalloff = true;
  39045. /**
  39046. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39047. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39048. */
  39049. _this.useRadianceOverAlpha = true;
  39050. /**
  39051. * Allows using the bump map in parallax mode.
  39052. */
  39053. _this.useParallax = false;
  39054. /**
  39055. * Allows using the bump map in parallax occlusion mode.
  39056. */
  39057. _this.useParallaxOcclusion = false;
  39058. /**
  39059. * Controls the scale bias of the parallax mode.
  39060. */
  39061. _this.parallaxScaleBias = 0.05;
  39062. /**
  39063. * If sets to true, disables all the lights affecting the material.
  39064. */
  39065. _this.disableLighting = false;
  39066. /**
  39067. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39068. */
  39069. _this.forceIrradianceInFragment = false;
  39070. /**
  39071. * Number of Simultaneous lights allowed on the material.
  39072. */
  39073. _this.maxSimultaneousLights = 4;
  39074. /**
  39075. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39076. */
  39077. _this.invertNormalMapX = false;
  39078. /**
  39079. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39080. */
  39081. _this.invertNormalMapY = false;
  39082. /**
  39083. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39084. */
  39085. _this.twoSidedLighting = false;
  39086. /**
  39087. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39088. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39089. */
  39090. _this.useAlphaFresnel = false;
  39091. /**
  39092. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39093. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39094. */
  39095. _this.useLinearAlphaFresnel = false;
  39096. /**
  39097. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39098. * And/Or occlude the blended part.
  39099. */
  39100. _this.environmentBRDFTexture = null;
  39101. /**
  39102. * Force normal to face away from face.
  39103. */
  39104. _this.forceNormalForward = false;
  39105. /**
  39106. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39107. * makes the reflect vector face the model (under horizon).
  39108. */
  39109. _this.useHorizonOcclusion = true;
  39110. /**
  39111. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39112. * too much the area relying on ambient texture to define their ambient occlusion.
  39113. */
  39114. _this.useRadianceOcclusion = true;
  39115. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39116. return _this;
  39117. }
  39118. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39119. /**
  39120. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39121. */
  39122. get: function () {
  39123. return this._PBRMATERIAL_OPAQUE;
  39124. },
  39125. enumerable: true,
  39126. configurable: true
  39127. });
  39128. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39129. /**
  39130. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39131. */
  39132. get: function () {
  39133. return this._PBRMATERIAL_ALPHATEST;
  39134. },
  39135. enumerable: true,
  39136. configurable: true
  39137. });
  39138. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39139. /**
  39140. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39141. */
  39142. get: function () {
  39143. return this._PBRMATERIAL_ALPHABLEND;
  39144. },
  39145. enumerable: true,
  39146. configurable: true
  39147. });
  39148. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39149. /**
  39150. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39151. * They are also discarded below the alpha cutoff threshold to improve performances.
  39152. */
  39153. get: function () {
  39154. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39155. },
  39156. enumerable: true,
  39157. configurable: true
  39158. });
  39159. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39160. /**
  39161. * Gets the image processing configuration used either in this material.
  39162. */
  39163. get: function () {
  39164. return this._imageProcessingConfiguration;
  39165. },
  39166. /**
  39167. * Sets the Default image processing configuration used either in the this material.
  39168. *
  39169. * If sets to null, the scene one is in use.
  39170. */
  39171. set: function (value) {
  39172. this._attachImageProcessingConfiguration(value);
  39173. // Ensure the effect will be rebuilt.
  39174. this._markAllSubMeshesAsTexturesDirty();
  39175. },
  39176. enumerable: true,
  39177. configurable: true
  39178. });
  39179. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39180. /**
  39181. * Gets wether the color curves effect is enabled.
  39182. */
  39183. get: function () {
  39184. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39185. },
  39186. /**
  39187. * Sets wether the color curves effect is enabled.
  39188. */
  39189. set: function (value) {
  39190. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39191. },
  39192. enumerable: true,
  39193. configurable: true
  39194. });
  39195. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39196. /**
  39197. * Gets wether the color grading effect is enabled.
  39198. */
  39199. get: function () {
  39200. return this.imageProcessingConfiguration.colorGradingEnabled;
  39201. },
  39202. /**
  39203. * Gets wether the color grading effect is enabled.
  39204. */
  39205. set: function (value) {
  39206. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39207. },
  39208. enumerable: true,
  39209. configurable: true
  39210. });
  39211. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39212. /**
  39213. * Gets wether tonemapping is enabled or not.
  39214. */
  39215. get: function () {
  39216. return this._imageProcessingConfiguration.toneMappingEnabled;
  39217. },
  39218. /**
  39219. * Sets wether tonemapping is enabled or not
  39220. */
  39221. set: function (value) {
  39222. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39223. },
  39224. enumerable: true,
  39225. configurable: true
  39226. });
  39227. ;
  39228. ;
  39229. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39230. /**
  39231. * The camera exposure used on this material.
  39232. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39233. * This corresponds to a photographic exposure.
  39234. */
  39235. get: function () {
  39236. return this._imageProcessingConfiguration.exposure;
  39237. },
  39238. /**
  39239. * The camera exposure used on this material.
  39240. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39241. * This corresponds to a photographic exposure.
  39242. */
  39243. set: function (value) {
  39244. this._imageProcessingConfiguration.exposure = value;
  39245. },
  39246. enumerable: true,
  39247. configurable: true
  39248. });
  39249. ;
  39250. ;
  39251. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39252. /**
  39253. * Gets The camera contrast used on this material.
  39254. */
  39255. get: function () {
  39256. return this._imageProcessingConfiguration.contrast;
  39257. },
  39258. /**
  39259. * Sets The camera contrast used on this material.
  39260. */
  39261. set: function (value) {
  39262. this._imageProcessingConfiguration.contrast = value;
  39263. },
  39264. enumerable: true,
  39265. configurable: true
  39266. });
  39267. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39268. /**
  39269. * Gets the Color Grading 2D Lookup Texture.
  39270. */
  39271. get: function () {
  39272. return this._imageProcessingConfiguration.colorGradingTexture;
  39273. },
  39274. /**
  39275. * Sets the Color Grading 2D Lookup Texture.
  39276. */
  39277. set: function (value) {
  39278. this._imageProcessingConfiguration.colorGradingTexture = value;
  39279. },
  39280. enumerable: true,
  39281. configurable: true
  39282. });
  39283. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39284. /**
  39285. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39286. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39287. * 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;
  39288. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39289. */
  39290. get: function () {
  39291. return this._imageProcessingConfiguration.colorCurves;
  39292. },
  39293. /**
  39294. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39295. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39296. * 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;
  39297. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39298. */
  39299. set: function (value) {
  39300. this._imageProcessingConfiguration.colorCurves = value;
  39301. },
  39302. enumerable: true,
  39303. configurable: true
  39304. });
  39305. PBRMaterial.prototype.getClassName = function () {
  39306. return "PBRMaterial";
  39307. };
  39308. PBRMaterial.prototype.getActiveTextures = function () {
  39309. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39310. if (this._albedoTexture) {
  39311. activeTextures.push(this._albedoTexture);
  39312. }
  39313. if (this._ambientTexture) {
  39314. activeTextures.push(this._ambientTexture);
  39315. }
  39316. if (this._opacityTexture) {
  39317. activeTextures.push(this._opacityTexture);
  39318. }
  39319. if (this._reflectionTexture) {
  39320. activeTextures.push(this._reflectionTexture);
  39321. }
  39322. if (this._emissiveTexture) {
  39323. activeTextures.push(this._emissiveTexture);
  39324. }
  39325. if (this._reflectivityTexture) {
  39326. activeTextures.push(this._reflectivityTexture);
  39327. }
  39328. if (this._metallicTexture) {
  39329. activeTextures.push(this._metallicTexture);
  39330. }
  39331. if (this._microSurfaceTexture) {
  39332. activeTextures.push(this._microSurfaceTexture);
  39333. }
  39334. if (this._bumpTexture) {
  39335. activeTextures.push(this._bumpTexture);
  39336. }
  39337. if (this._lightmapTexture) {
  39338. activeTextures.push(this._lightmapTexture);
  39339. }
  39340. if (this._refractionTexture) {
  39341. activeTextures.push(this._refractionTexture);
  39342. }
  39343. return activeTextures;
  39344. };
  39345. PBRMaterial.prototype.hasTexture = function (texture) {
  39346. if (_super.prototype.hasTexture.call(this, texture)) {
  39347. return true;
  39348. }
  39349. if (this._albedoTexture === texture) {
  39350. return true;
  39351. }
  39352. if (this._ambientTexture === texture) {
  39353. return true;
  39354. }
  39355. if (this._opacityTexture === texture) {
  39356. return true;
  39357. }
  39358. if (this._reflectionTexture === texture) {
  39359. return true;
  39360. }
  39361. if (this._reflectivityTexture === texture) {
  39362. return true;
  39363. }
  39364. if (this._metallicTexture === texture) {
  39365. return true;
  39366. }
  39367. if (this._microSurfaceTexture === texture) {
  39368. return true;
  39369. }
  39370. if (this._bumpTexture === texture) {
  39371. return true;
  39372. }
  39373. if (this._lightmapTexture === texture) {
  39374. return true;
  39375. }
  39376. if (this._refractionTexture === texture) {
  39377. return true;
  39378. }
  39379. return false;
  39380. };
  39381. PBRMaterial.prototype.clone = function (name) {
  39382. var _this = this;
  39383. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39384. clone.id = name;
  39385. clone.name = name;
  39386. return clone;
  39387. };
  39388. PBRMaterial.prototype.serialize = function () {
  39389. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39390. serializationObject.customType = "BABYLON.PBRMaterial";
  39391. return serializationObject;
  39392. };
  39393. // Statics
  39394. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39395. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39396. };
  39397. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39398. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39399. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39400. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39401. __decorate([
  39402. BABYLON.serialize(),
  39403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39404. ], PBRMaterial.prototype, "directIntensity", void 0);
  39405. __decorate([
  39406. BABYLON.serialize(),
  39407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39408. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39409. __decorate([
  39410. BABYLON.serialize(),
  39411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39412. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39413. __decorate([
  39414. BABYLON.serialize(),
  39415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39416. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39417. __decorate([
  39418. BABYLON.serialize(),
  39419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39420. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39421. __decorate([
  39422. BABYLON.serializeAsTexture(),
  39423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39424. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39425. __decorate([
  39426. BABYLON.serializeAsTexture(),
  39427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39428. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39429. __decorate([
  39430. BABYLON.serialize(),
  39431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39432. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39433. __decorate([
  39434. BABYLON.serializeAsTexture(),
  39435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39436. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39437. __decorate([
  39438. BABYLON.serializeAsTexture(),
  39439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39440. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39441. __decorate([
  39442. BABYLON.serializeAsTexture(),
  39443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39444. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39445. __decorate([
  39446. BABYLON.serializeAsTexture(),
  39447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39448. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39449. __decorate([
  39450. BABYLON.serializeAsTexture(),
  39451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39452. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39453. __decorate([
  39454. BABYLON.serialize(),
  39455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39456. ], PBRMaterial.prototype, "metallic", void 0);
  39457. __decorate([
  39458. BABYLON.serialize(),
  39459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39460. ], PBRMaterial.prototype, "roughness", void 0);
  39461. __decorate([
  39462. BABYLON.serializeAsTexture(),
  39463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39464. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39465. __decorate([
  39466. BABYLON.serializeAsTexture(),
  39467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39468. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39469. __decorate([
  39470. BABYLON.serializeAsTexture(),
  39471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39472. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39473. __decorate([
  39474. BABYLON.serializeAsTexture(),
  39475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39476. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39477. __decorate([
  39478. BABYLON.serializeAsColor3("ambient"),
  39479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39480. ], PBRMaterial.prototype, "ambientColor", void 0);
  39481. __decorate([
  39482. BABYLON.serializeAsColor3("albedo"),
  39483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39484. ], PBRMaterial.prototype, "albedoColor", void 0);
  39485. __decorate([
  39486. BABYLON.serializeAsColor3("reflectivity"),
  39487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39488. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39489. __decorate([
  39490. BABYLON.serializeAsColor3("reflection"),
  39491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39492. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39493. __decorate([
  39494. BABYLON.serializeAsColor3("emissive"),
  39495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39496. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39497. __decorate([
  39498. BABYLON.serialize(),
  39499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39500. ], PBRMaterial.prototype, "microSurface", void 0);
  39501. __decorate([
  39502. BABYLON.serialize(),
  39503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39504. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39505. __decorate([
  39506. BABYLON.serialize(),
  39507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39508. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39509. __decorate([
  39510. BABYLON.serialize(),
  39511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39512. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39513. __decorate([
  39514. BABYLON.serialize(),
  39515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39516. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39517. __decorate([
  39518. BABYLON.serialize(),
  39519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39520. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39521. __decorate([
  39522. BABYLON.serialize(),
  39523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39524. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  39525. __decorate([
  39526. BABYLON.serialize(),
  39527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39528. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  39529. __decorate([
  39530. BABYLON.serialize(),
  39531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39532. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  39533. __decorate([
  39534. BABYLON.serialize(),
  39535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39536. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  39537. __decorate([
  39538. BABYLON.serialize(),
  39539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39540. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  39541. __decorate([
  39542. BABYLON.serialize(),
  39543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39544. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  39545. __decorate([
  39546. BABYLON.serialize(),
  39547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39548. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  39549. __decorate([
  39550. BABYLON.serialize(),
  39551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39552. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  39553. __decorate([
  39554. BABYLON.serialize(),
  39555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39556. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  39557. __decorate([
  39558. BABYLON.serialize(),
  39559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39560. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  39561. __decorate([
  39562. BABYLON.serialize(),
  39563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39564. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  39565. __decorate([
  39566. BABYLON.serialize(),
  39567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39568. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  39569. __decorate([
  39570. BABYLON.serialize(),
  39571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39572. ], PBRMaterial.prototype, "useParallax", void 0);
  39573. __decorate([
  39574. BABYLON.serialize(),
  39575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39576. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  39577. __decorate([
  39578. BABYLON.serialize(),
  39579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39580. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  39581. __decorate([
  39582. BABYLON.serialize(),
  39583. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39584. ], PBRMaterial.prototype, "disableLighting", void 0);
  39585. __decorate([
  39586. BABYLON.serialize(),
  39587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39588. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  39589. __decorate([
  39590. BABYLON.serialize(),
  39591. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39592. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  39593. __decorate([
  39594. BABYLON.serialize(),
  39595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39596. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  39597. __decorate([
  39598. BABYLON.serialize(),
  39599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39600. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  39601. __decorate([
  39602. BABYLON.serialize(),
  39603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39604. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  39605. __decorate([
  39606. BABYLON.serialize(),
  39607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39608. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  39609. __decorate([
  39610. BABYLON.serialize(),
  39611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39612. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  39613. __decorate([
  39614. BABYLON.serializeAsTexture(),
  39615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39616. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  39617. __decorate([
  39618. BABYLON.serialize(),
  39619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39620. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  39621. __decorate([
  39622. BABYLON.serialize(),
  39623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39624. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  39625. __decorate([
  39626. BABYLON.serialize(),
  39627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39628. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  39629. return PBRMaterial;
  39630. }(BABYLON.PBRBaseMaterial));
  39631. BABYLON.PBRMaterial = PBRMaterial;
  39632. })(BABYLON || (BABYLON = {}));
  39633. //# sourceMappingURL=babylon.pbrMaterial.js.map
  39634. var BABYLON;
  39635. (function (BABYLON) {
  39636. /**
  39637. * The PBR material of BJS following the metal roughness convention.
  39638. *
  39639. * This fits to the PBR convention in the GLTF definition:
  39640. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  39641. */
  39642. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  39643. __extends(PBRMetallicRoughnessMaterial, _super);
  39644. /**
  39645. * Instantiates a new PBRMetalRoughnessMaterial instance.
  39646. *
  39647. * @param name The material name
  39648. * @param scene The scene the material will be use in.
  39649. */
  39650. function PBRMetallicRoughnessMaterial(name, scene) {
  39651. var _this = _super.call(this, name, scene) || this;
  39652. _this._useRoughnessFromMetallicTextureAlpha = false;
  39653. _this._useRoughnessFromMetallicTextureGreen = true;
  39654. _this._useMetallnessFromMetallicTextureBlue = true;
  39655. _this._forceMetallicWorkflow = true;
  39656. return _this;
  39657. }
  39658. /**
  39659. * Return the currrent class name of the material.
  39660. */
  39661. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  39662. return "PBRMetallicRoughnessMaterial";
  39663. };
  39664. /**
  39665. * Return the active textures of the material.
  39666. */
  39667. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  39668. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39669. if (this.baseTexture) {
  39670. activeTextures.push(this.baseTexture);
  39671. }
  39672. if (this.metallicRoughnessTexture) {
  39673. activeTextures.push(this.metallicRoughnessTexture);
  39674. }
  39675. return activeTextures;
  39676. };
  39677. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  39678. if (_super.prototype.hasTexture.call(this, texture)) {
  39679. return true;
  39680. }
  39681. if (this.baseTexture === texture) {
  39682. return true;
  39683. }
  39684. if (this.metallicRoughnessTexture === texture) {
  39685. return true;
  39686. }
  39687. return false;
  39688. };
  39689. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  39690. var _this = this;
  39691. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  39692. clone.id = name;
  39693. clone.name = name;
  39694. return clone;
  39695. };
  39696. /**
  39697. * Serialize the material to a parsable JSON object.
  39698. */
  39699. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39700. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39701. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39702. return serializationObject;
  39703. };
  39704. /**
  39705. * Parses a JSON object correponding to the serialize function.
  39706. */
  39707. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39708. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39709. };
  39710. __decorate([
  39711. BABYLON.serializeAsColor3(),
  39712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39713. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39714. __decorate([
  39715. BABYLON.serializeAsTexture(),
  39716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39717. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39718. __decorate([
  39719. BABYLON.serialize(),
  39720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39721. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  39722. __decorate([
  39723. BABYLON.serialize(),
  39724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39725. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  39726. __decorate([
  39727. BABYLON.serializeAsTexture(),
  39728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  39729. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  39730. return PBRMetallicRoughnessMaterial;
  39731. }(BABYLON.PBRBaseSimpleMaterial));
  39732. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  39733. })(BABYLON || (BABYLON = {}));
  39734. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  39735. var BABYLON;
  39736. (function (BABYLON) {
  39737. /**
  39738. * The PBR material of BJS following the specular glossiness convention.
  39739. *
  39740. * This fits to the PBR convention in the GLTF definition:
  39741. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  39742. */
  39743. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  39744. __extends(PBRSpecularGlossinessMaterial, _super);
  39745. /**
  39746. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  39747. *
  39748. * @param name The material name
  39749. * @param scene The scene the material will be use in.
  39750. */
  39751. function PBRSpecularGlossinessMaterial(name, scene) {
  39752. var _this = _super.call(this, name, scene) || this;
  39753. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  39754. return _this;
  39755. }
  39756. /**
  39757. * Return the currrent class name of the material.
  39758. */
  39759. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  39760. return "PBRSpecularGlossinessMaterial";
  39761. };
  39762. /**
  39763. * Return the active textures of the material.
  39764. */
  39765. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  39766. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39767. if (this.diffuseTexture) {
  39768. activeTextures.push(this.diffuseTexture);
  39769. }
  39770. if (this.specularGlossinessTexture) {
  39771. activeTextures.push(this.specularGlossinessTexture);
  39772. }
  39773. return activeTextures;
  39774. };
  39775. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  39776. if (_super.prototype.hasTexture.call(this, texture)) {
  39777. return true;
  39778. }
  39779. if (this.diffuseTexture === texture) {
  39780. return true;
  39781. }
  39782. if (this.specularGlossinessTexture === texture) {
  39783. return true;
  39784. }
  39785. return false;
  39786. };
  39787. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39788. var _this = this;
  39789. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39790. clone.id = name;
  39791. clone.name = name;
  39792. return clone;
  39793. };
  39794. /**
  39795. * Serialize the material to a parsable JSON object.
  39796. */
  39797. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39798. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39799. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39800. return serializationObject;
  39801. };
  39802. /**
  39803. * Parses a JSON object correponding to the serialize function.
  39804. */
  39805. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39806. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39807. };
  39808. __decorate([
  39809. BABYLON.serializeAsColor3("diffuse"),
  39810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39811. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39812. __decorate([
  39813. BABYLON.serializeAsTexture(),
  39814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39815. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39816. __decorate([
  39817. BABYLON.serializeAsColor3("specular"),
  39818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39819. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39820. __decorate([
  39821. BABYLON.serialize(),
  39822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39823. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39824. __decorate([
  39825. BABYLON.serializeAsTexture(),
  39826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39827. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39828. return PBRSpecularGlossinessMaterial;
  39829. }(BABYLON.PBRBaseSimpleMaterial));
  39830. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39831. })(BABYLON || (BABYLON = {}));
  39832. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  39833. var BABYLON;
  39834. (function (BABYLON) {
  39835. BABYLON.CameraInputTypes = {};
  39836. var CameraInputsManager = /** @class */ (function () {
  39837. function CameraInputsManager(camera) {
  39838. this.attached = {};
  39839. this.camera = camera;
  39840. this.checkInputs = function () { };
  39841. }
  39842. /**
  39843. * Add an input method to a camera.
  39844. * builtin inputs example: camera.inputs.addGamepad();
  39845. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  39846. * @param input camera input method
  39847. */
  39848. CameraInputsManager.prototype.add = function (input) {
  39849. var type = input.getSimpleName();
  39850. if (this.attached[type]) {
  39851. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  39852. return;
  39853. }
  39854. this.attached[type] = input;
  39855. input.camera = this.camera;
  39856. //for checkInputs, we are dynamically creating a function
  39857. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  39858. if (input.checkInputs) {
  39859. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  39860. }
  39861. if (this.attachedElement) {
  39862. input.attachControl(this.attachedElement);
  39863. }
  39864. };
  39865. /**
  39866. * Remove a specific input method from a camera
  39867. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  39868. * @param inputToRemove camera input method
  39869. */
  39870. CameraInputsManager.prototype.remove = function (inputToRemove) {
  39871. for (var cam in this.attached) {
  39872. var input = this.attached[cam];
  39873. if (input === inputToRemove) {
  39874. input.detachControl(this.attachedElement);
  39875. input.camera = null;
  39876. delete this.attached[cam];
  39877. this.rebuildInputCheck();
  39878. }
  39879. }
  39880. };
  39881. CameraInputsManager.prototype.removeByType = function (inputType) {
  39882. for (var cam in this.attached) {
  39883. var input = this.attached[cam];
  39884. if (input.getClassName() === inputType) {
  39885. input.detachControl(this.attachedElement);
  39886. input.camera = null;
  39887. delete this.attached[cam];
  39888. this.rebuildInputCheck();
  39889. }
  39890. }
  39891. };
  39892. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  39893. var current = this.checkInputs;
  39894. return function () {
  39895. current();
  39896. fn();
  39897. };
  39898. };
  39899. CameraInputsManager.prototype.attachInput = function (input) {
  39900. if (this.attachedElement) {
  39901. input.attachControl(this.attachedElement, this.noPreventDefault);
  39902. }
  39903. };
  39904. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  39905. if (noPreventDefault === void 0) { noPreventDefault = false; }
  39906. if (this.attachedElement) {
  39907. return;
  39908. }
  39909. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  39910. this.attachedElement = element;
  39911. this.noPreventDefault = noPreventDefault;
  39912. for (var cam in this.attached) {
  39913. this.attached[cam].attachControl(element, noPreventDefault);
  39914. }
  39915. };
  39916. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  39917. if (disconnect === void 0) { disconnect = false; }
  39918. if (this.attachedElement !== element) {
  39919. return;
  39920. }
  39921. for (var cam in this.attached) {
  39922. this.attached[cam].detachControl(element);
  39923. if (disconnect) {
  39924. this.attached[cam].camera = null;
  39925. }
  39926. }
  39927. this.attachedElement = null;
  39928. };
  39929. CameraInputsManager.prototype.rebuildInputCheck = function () {
  39930. this.checkInputs = function () { };
  39931. for (var cam in this.attached) {
  39932. var input = this.attached[cam];
  39933. if (input.checkInputs) {
  39934. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  39935. }
  39936. }
  39937. };
  39938. /**
  39939. * Remove all attached input methods from a camera
  39940. */
  39941. CameraInputsManager.prototype.clear = function () {
  39942. if (this.attachedElement) {
  39943. this.detachElement(this.attachedElement, true);
  39944. }
  39945. this.attached = {};
  39946. this.attachedElement = null;
  39947. this.checkInputs = function () { };
  39948. };
  39949. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  39950. var inputs = {};
  39951. for (var cam in this.attached) {
  39952. var input = this.attached[cam];
  39953. var res = BABYLON.SerializationHelper.Serialize(input);
  39954. inputs[input.getClassName()] = res;
  39955. }
  39956. serializedCamera.inputsmgr = inputs;
  39957. };
  39958. CameraInputsManager.prototype.parse = function (parsedCamera) {
  39959. var parsedInputs = parsedCamera.inputsmgr;
  39960. if (parsedInputs) {
  39961. this.clear();
  39962. for (var n in parsedInputs) {
  39963. var construct = BABYLON.CameraInputTypes[n];
  39964. if (construct) {
  39965. var parsedinput = parsedInputs[n];
  39966. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  39967. this.add(input);
  39968. }
  39969. }
  39970. }
  39971. else {
  39972. //2016-03-08 this part is for managing backward compatibility
  39973. for (var n in this.attached) {
  39974. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  39975. if (construct) {
  39976. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  39977. this.remove(this.attached[n]);
  39978. this.add(input);
  39979. }
  39980. }
  39981. }
  39982. };
  39983. return CameraInputsManager;
  39984. }());
  39985. BABYLON.CameraInputsManager = CameraInputsManager;
  39986. })(BABYLON || (BABYLON = {}));
  39987. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  39988. var BABYLON;
  39989. (function (BABYLON) {
  39990. var TargetCamera = /** @class */ (function (_super) {
  39991. __extends(TargetCamera, _super);
  39992. function TargetCamera(name, position, scene) {
  39993. var _this = _super.call(this, name, position, scene) || this;
  39994. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39995. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  39996. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  39997. _this.speed = 2.0;
  39998. _this.noRotationConstraint = false;
  39999. _this.lockedTarget = null;
  40000. _this._currentTarget = BABYLON.Vector3.Zero();
  40001. _this._viewMatrix = BABYLON.Matrix.Zero();
  40002. _this._camMatrix = BABYLON.Matrix.Zero();
  40003. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40004. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40005. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40006. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40007. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40008. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40009. _this._tempMatrix = BABYLON.Matrix.Zero();
  40010. return _this;
  40011. }
  40012. TargetCamera.prototype.getFrontPosition = function (distance) {
  40013. this.getWorldMatrix();
  40014. var direction = this.getTarget().subtract(this.position);
  40015. direction.normalize();
  40016. direction.scaleInPlace(distance);
  40017. return this.globalPosition.add(direction);
  40018. };
  40019. TargetCamera.prototype._getLockedTargetPosition = function () {
  40020. if (!this.lockedTarget) {
  40021. return null;
  40022. }
  40023. if (this.lockedTarget.absolutePosition) {
  40024. this.lockedTarget.computeWorldMatrix();
  40025. }
  40026. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40027. };
  40028. TargetCamera.prototype.storeState = function () {
  40029. this._storedPosition = this.position.clone();
  40030. this._storedRotation = this.rotation.clone();
  40031. if (this.rotationQuaternion) {
  40032. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40033. }
  40034. return _super.prototype.storeState.call(this);
  40035. };
  40036. /**
  40037. * Restored camera state. You must call storeState() first
  40038. */
  40039. TargetCamera.prototype._restoreStateValues = function () {
  40040. if (!_super.prototype._restoreStateValues.call(this)) {
  40041. return false;
  40042. }
  40043. this.position = this._storedPosition.clone();
  40044. this.rotation = this._storedRotation.clone();
  40045. if (this.rotationQuaternion) {
  40046. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40047. }
  40048. this.cameraDirection.copyFromFloats(0, 0, 0);
  40049. this.cameraRotation.copyFromFloats(0, 0);
  40050. return true;
  40051. };
  40052. // Cache
  40053. TargetCamera.prototype._initCache = function () {
  40054. _super.prototype._initCache.call(this);
  40055. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40056. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40057. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40058. };
  40059. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40060. if (!ignoreParentClass) {
  40061. _super.prototype._updateCache.call(this);
  40062. }
  40063. var lockedTargetPosition = this._getLockedTargetPosition();
  40064. if (!lockedTargetPosition) {
  40065. this._cache.lockedTarget = null;
  40066. }
  40067. else {
  40068. if (!this._cache.lockedTarget) {
  40069. this._cache.lockedTarget = lockedTargetPosition.clone();
  40070. }
  40071. else {
  40072. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40073. }
  40074. }
  40075. this._cache.rotation.copyFrom(this.rotation);
  40076. if (this.rotationQuaternion)
  40077. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40078. };
  40079. // Synchronized
  40080. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40081. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40082. return false;
  40083. }
  40084. var lockedTargetPosition = this._getLockedTargetPosition();
  40085. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40086. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40087. };
  40088. // Methods
  40089. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40090. var engine = this.getEngine();
  40091. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40092. };
  40093. // Target
  40094. TargetCamera.prototype.setTarget = function (target) {
  40095. this.upVector.normalize();
  40096. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40097. this._camMatrix.invert();
  40098. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40099. var vDir = target.subtract(this.position);
  40100. if (vDir.x >= 0.0) {
  40101. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40102. }
  40103. else {
  40104. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40105. }
  40106. this.rotation.z = 0;
  40107. if (isNaN(this.rotation.x)) {
  40108. this.rotation.x = 0;
  40109. }
  40110. if (isNaN(this.rotation.y)) {
  40111. this.rotation.y = 0;
  40112. }
  40113. if (isNaN(this.rotation.z)) {
  40114. this.rotation.z = 0;
  40115. }
  40116. if (this.rotationQuaternion) {
  40117. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40118. }
  40119. };
  40120. /**
  40121. * Return the current target position of the camera. This value is expressed in local space.
  40122. */
  40123. TargetCamera.prototype.getTarget = function () {
  40124. return this._currentTarget;
  40125. };
  40126. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40127. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40128. };
  40129. TargetCamera.prototype._updatePosition = function () {
  40130. if (this.parent) {
  40131. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40132. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40133. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40134. return;
  40135. }
  40136. this.position.addInPlace(this.cameraDirection);
  40137. };
  40138. TargetCamera.prototype._checkInputs = function () {
  40139. var needToMove = this._decideIfNeedsToMove();
  40140. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40141. // Move
  40142. if (needToMove) {
  40143. this._updatePosition();
  40144. }
  40145. // Rotate
  40146. if (needToRotate) {
  40147. this.rotation.x += this.cameraRotation.x;
  40148. this.rotation.y += this.cameraRotation.y;
  40149. //rotate, if quaternion is set and rotation was used
  40150. if (this.rotationQuaternion) {
  40151. var len = this.rotation.lengthSquared();
  40152. if (len) {
  40153. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40154. }
  40155. }
  40156. if (!this.noRotationConstraint) {
  40157. var limit = (Math.PI / 2) * 0.95;
  40158. if (this.rotation.x > limit)
  40159. this.rotation.x = limit;
  40160. if (this.rotation.x < -limit)
  40161. this.rotation.x = -limit;
  40162. }
  40163. }
  40164. // Inertia
  40165. if (needToMove) {
  40166. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40167. this.cameraDirection.x = 0;
  40168. }
  40169. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40170. this.cameraDirection.y = 0;
  40171. }
  40172. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40173. this.cameraDirection.z = 0;
  40174. }
  40175. this.cameraDirection.scaleInPlace(this.inertia);
  40176. }
  40177. if (needToRotate) {
  40178. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40179. this.cameraRotation.x = 0;
  40180. }
  40181. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40182. this.cameraRotation.y = 0;
  40183. }
  40184. this.cameraRotation.scaleInPlace(this.inertia);
  40185. }
  40186. _super.prototype._checkInputs.call(this);
  40187. };
  40188. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40189. if (this.rotationQuaternion) {
  40190. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40191. }
  40192. else {
  40193. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40194. }
  40195. //update the up vector!
  40196. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40197. };
  40198. TargetCamera.prototype._getViewMatrix = function () {
  40199. if (this.lockedTarget) {
  40200. this.setTarget(this._getLockedTargetPosition());
  40201. }
  40202. // Compute
  40203. this._updateCameraRotationMatrix();
  40204. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40205. // Computing target and final matrix
  40206. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40207. if (this.getScene().useRightHandedSystem) {
  40208. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40209. }
  40210. else {
  40211. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40212. }
  40213. return this._viewMatrix;
  40214. };
  40215. /**
  40216. * @override
  40217. * Override Camera.createRigCamera
  40218. */
  40219. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40220. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40221. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40222. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40223. if (!this.rotationQuaternion) {
  40224. this.rotationQuaternion = new BABYLON.Quaternion();
  40225. }
  40226. rigCamera._cameraRigParams = {};
  40227. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40228. }
  40229. return rigCamera;
  40230. }
  40231. return null;
  40232. };
  40233. /**
  40234. * @override
  40235. * Override Camera._updateRigCameras
  40236. */
  40237. TargetCamera.prototype._updateRigCameras = function () {
  40238. var camLeft = this._rigCameras[0];
  40239. var camRight = this._rigCameras[1];
  40240. switch (this.cameraRigMode) {
  40241. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40242. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40243. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40245. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40246. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40247. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40248. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40249. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40250. camLeft.setTarget(this.getTarget());
  40251. camRight.setTarget(this.getTarget());
  40252. break;
  40253. case BABYLON.Camera.RIG_MODE_VR:
  40254. if (camLeft.rotationQuaternion) {
  40255. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40256. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40257. }
  40258. else {
  40259. camLeft.rotation.copyFrom(this.rotation);
  40260. camRight.rotation.copyFrom(this.rotation);
  40261. }
  40262. camLeft.position.copyFrom(this.position);
  40263. camRight.position.copyFrom(this.position);
  40264. break;
  40265. }
  40266. _super.prototype._updateRigCameras.call(this);
  40267. };
  40268. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40269. if (!this._rigCamTransformMatrix) {
  40270. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40271. }
  40272. var target = this.getTarget();
  40273. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40274. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40275. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40276. };
  40277. TargetCamera.prototype.getClassName = function () {
  40278. return "TargetCamera";
  40279. };
  40280. __decorate([
  40281. BABYLON.serializeAsVector3()
  40282. ], TargetCamera.prototype, "rotation", void 0);
  40283. __decorate([
  40284. BABYLON.serialize()
  40285. ], TargetCamera.prototype, "speed", void 0);
  40286. __decorate([
  40287. BABYLON.serializeAsMeshReference("lockedTargetId")
  40288. ], TargetCamera.prototype, "lockedTarget", void 0);
  40289. return TargetCamera;
  40290. }(BABYLON.Camera));
  40291. BABYLON.TargetCamera = TargetCamera;
  40292. })(BABYLON || (BABYLON = {}));
  40293. //# sourceMappingURL=babylon.targetCamera.js.map
  40294. var BABYLON;
  40295. (function (BABYLON) {
  40296. var FreeCameraMouseInput = /** @class */ (function () {
  40297. function FreeCameraMouseInput(touchEnabled) {
  40298. if (touchEnabled === void 0) { touchEnabled = true; }
  40299. this.touchEnabled = touchEnabled;
  40300. this.buttons = [0, 1, 2];
  40301. this.angularSensibility = 2000.0;
  40302. this.previousPosition = null;
  40303. }
  40304. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40305. var _this = this;
  40306. var engine = this.camera.getEngine();
  40307. if (!this._pointerInput) {
  40308. this._pointerInput = function (p, s) {
  40309. var evt = p.event;
  40310. if (engine.isInVRExclusivePointerMode) {
  40311. return;
  40312. }
  40313. if (!_this.touchEnabled && evt.pointerType === "touch") {
  40314. return;
  40315. }
  40316. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40317. return;
  40318. }
  40319. var srcElement = (evt.srcElement || evt.target);
  40320. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40321. try {
  40322. srcElement.setPointerCapture(evt.pointerId);
  40323. }
  40324. catch (e) {
  40325. //Nothing to do with the error. Execution will continue.
  40326. }
  40327. _this.previousPosition = {
  40328. x: evt.clientX,
  40329. y: evt.clientY
  40330. };
  40331. if (!noPreventDefault) {
  40332. evt.preventDefault();
  40333. element.focus();
  40334. }
  40335. }
  40336. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40337. try {
  40338. srcElement.releasePointerCapture(evt.pointerId);
  40339. }
  40340. catch (e) {
  40341. //Nothing to do with the error.
  40342. }
  40343. _this.previousPosition = null;
  40344. if (!noPreventDefault) {
  40345. evt.preventDefault();
  40346. }
  40347. }
  40348. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40349. if (!_this.previousPosition || engine.isPointerLock) {
  40350. return;
  40351. }
  40352. var offsetX = evt.clientX - _this.previousPosition.x;
  40353. var offsetY = evt.clientY - _this.previousPosition.y;
  40354. if (_this.camera.getScene().useRightHandedSystem) {
  40355. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40356. }
  40357. else {
  40358. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40359. }
  40360. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40361. _this.previousPosition = {
  40362. x: evt.clientX,
  40363. y: evt.clientY
  40364. };
  40365. if (!noPreventDefault) {
  40366. evt.preventDefault();
  40367. }
  40368. }
  40369. };
  40370. }
  40371. this._onMouseMove = function (evt) {
  40372. if (!engine.isPointerLock) {
  40373. return;
  40374. }
  40375. if (engine.isInVRExclusivePointerMode) {
  40376. return;
  40377. }
  40378. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40379. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40380. if (_this.camera.getScene().useRightHandedSystem) {
  40381. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40382. }
  40383. else {
  40384. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40385. }
  40386. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40387. _this.previousPosition = null;
  40388. if (!noPreventDefault) {
  40389. evt.preventDefault();
  40390. }
  40391. };
  40392. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  40393. element.addEventListener("mousemove", this._onMouseMove, false);
  40394. };
  40395. FreeCameraMouseInput.prototype.detachControl = function (element) {
  40396. if (this._observer && element) {
  40397. this.camera.getScene().onPointerObservable.remove(this._observer);
  40398. if (this._onMouseMove) {
  40399. element.removeEventListener("mousemove", this._onMouseMove);
  40400. }
  40401. this._observer = null;
  40402. this._onMouseMove = null;
  40403. this.previousPosition = null;
  40404. }
  40405. };
  40406. FreeCameraMouseInput.prototype.getClassName = function () {
  40407. return "FreeCameraMouseInput";
  40408. };
  40409. FreeCameraMouseInput.prototype.getSimpleName = function () {
  40410. return "mouse";
  40411. };
  40412. __decorate([
  40413. BABYLON.serialize()
  40414. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  40415. __decorate([
  40416. BABYLON.serialize()
  40417. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  40418. return FreeCameraMouseInput;
  40419. }());
  40420. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  40421. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  40422. })(BABYLON || (BABYLON = {}));
  40423. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  40424. var BABYLON;
  40425. (function (BABYLON) {
  40426. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  40427. function FreeCameraKeyboardMoveInput() {
  40428. this._keys = new Array();
  40429. this.keysUp = [38];
  40430. this.keysDown = [40];
  40431. this.keysLeft = [37];
  40432. this.keysRight = [39];
  40433. }
  40434. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40435. var _this = this;
  40436. if (this._onCanvasBlurObserver) {
  40437. return;
  40438. }
  40439. this._scene = this.camera.getScene();
  40440. this._engine = this._scene.getEngine();
  40441. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40442. _this._keys = [];
  40443. });
  40444. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40445. var evt = info.event;
  40446. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40447. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40448. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40449. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40450. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40451. var index = _this._keys.indexOf(evt.keyCode);
  40452. if (index === -1) {
  40453. _this._keys.push(evt.keyCode);
  40454. }
  40455. if (!noPreventDefault) {
  40456. evt.preventDefault();
  40457. }
  40458. }
  40459. }
  40460. else {
  40461. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40462. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40463. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40464. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40465. var index = _this._keys.indexOf(evt.keyCode);
  40466. if (index >= 0) {
  40467. _this._keys.splice(index, 1);
  40468. }
  40469. if (!noPreventDefault) {
  40470. evt.preventDefault();
  40471. }
  40472. }
  40473. }
  40474. });
  40475. };
  40476. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40477. if (this._scene) {
  40478. if (this._onKeyboardObserver) {
  40479. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40480. }
  40481. if (this._onCanvasBlurObserver) {
  40482. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40483. }
  40484. this._onKeyboardObserver = null;
  40485. this._onCanvasBlurObserver = null;
  40486. }
  40487. this._keys = [];
  40488. };
  40489. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40490. if (this._onKeyboardObserver) {
  40491. var camera = this.camera;
  40492. // Keyboard
  40493. for (var index = 0; index < this._keys.length; index++) {
  40494. var keyCode = this._keys[index];
  40495. var speed = camera._computeLocalCameraSpeed();
  40496. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40497. camera._localDirection.copyFromFloats(-speed, 0, 0);
  40498. }
  40499. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40500. camera._localDirection.copyFromFloats(0, 0, speed);
  40501. }
  40502. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40503. camera._localDirection.copyFromFloats(speed, 0, 0);
  40504. }
  40505. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40506. camera._localDirection.copyFromFloats(0, 0, -speed);
  40507. }
  40508. if (camera.getScene().useRightHandedSystem) {
  40509. camera._localDirection.z *= -1;
  40510. }
  40511. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  40512. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  40513. camera.cameraDirection.addInPlace(camera._transformedDirection);
  40514. }
  40515. }
  40516. };
  40517. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  40518. return "FreeCameraKeyboardMoveInput";
  40519. };
  40520. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  40521. this._keys = [];
  40522. };
  40523. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40524. return "keyboard";
  40525. };
  40526. __decorate([
  40527. BABYLON.serialize()
  40528. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40529. __decorate([
  40530. BABYLON.serialize()
  40531. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40532. __decorate([
  40533. BABYLON.serialize()
  40534. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40535. __decorate([
  40536. BABYLON.serialize()
  40537. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40538. return FreeCameraKeyboardMoveInput;
  40539. }());
  40540. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  40541. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  40542. })(BABYLON || (BABYLON = {}));
  40543. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  40544. var BABYLON;
  40545. (function (BABYLON) {
  40546. var FreeCameraInputsManager = /** @class */ (function (_super) {
  40547. __extends(FreeCameraInputsManager, _super);
  40548. function FreeCameraInputsManager(camera) {
  40549. return _super.call(this, camera) || this;
  40550. }
  40551. FreeCameraInputsManager.prototype.addKeyboard = function () {
  40552. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  40553. return this;
  40554. };
  40555. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  40556. if (touchEnabled === void 0) { touchEnabled = true; }
  40557. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  40558. return this;
  40559. };
  40560. FreeCameraInputsManager.prototype.addGamepad = function () {
  40561. this.add(new BABYLON.FreeCameraGamepadInput());
  40562. return this;
  40563. };
  40564. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  40565. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  40566. return this;
  40567. };
  40568. FreeCameraInputsManager.prototype.addTouch = function () {
  40569. this.add(new BABYLON.FreeCameraTouchInput());
  40570. return this;
  40571. };
  40572. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  40573. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  40574. return this;
  40575. };
  40576. return FreeCameraInputsManager;
  40577. }(BABYLON.CameraInputsManager));
  40578. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  40579. })(BABYLON || (BABYLON = {}));
  40580. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  40581. var BABYLON;
  40582. (function (BABYLON) {
  40583. var FreeCamera = /** @class */ (function (_super) {
  40584. __extends(FreeCamera, _super);
  40585. function FreeCamera(name, position, scene) {
  40586. var _this = _super.call(this, name, position, scene) || this;
  40587. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  40588. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  40589. _this.checkCollisions = false;
  40590. _this.applyGravity = false;
  40591. _this._needMoveForGravity = false;
  40592. _this._oldPosition = BABYLON.Vector3.Zero();
  40593. _this._diffPosition = BABYLON.Vector3.Zero();
  40594. _this._newPosition = BABYLON.Vector3.Zero();
  40595. // Collisions
  40596. _this._collisionMask = -1;
  40597. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40598. if (collidedMesh === void 0) { collidedMesh = null; }
  40599. //TODO move this to the collision coordinator!
  40600. if (_this.getScene().workerCollisions)
  40601. newPosition.multiplyInPlace(_this._collider._radius);
  40602. var updatePosition = function (newPos) {
  40603. _this._newPosition.copyFrom(newPos);
  40604. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  40605. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  40606. _this.position.addInPlace(_this._diffPosition);
  40607. if (_this.onCollide && collidedMesh) {
  40608. _this.onCollide(collidedMesh);
  40609. }
  40610. }
  40611. };
  40612. updatePosition(newPosition);
  40613. };
  40614. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  40615. _this.inputs.addKeyboard().addMouse();
  40616. return _this;
  40617. }
  40618. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  40619. //-- begin properties for backward compatibility for inputs
  40620. /**
  40621. * Gets the input sensibility for a mouse input. (default is 2000.0)
  40622. * Higher values reduce sensitivity.
  40623. */
  40624. get: function () {
  40625. var mouse = this.inputs.attached["mouse"];
  40626. if (mouse)
  40627. return mouse.angularSensibility;
  40628. return 0;
  40629. },
  40630. /**
  40631. * Sets the input sensibility for a mouse input. (default is 2000.0)
  40632. * Higher values reduce sensitivity.
  40633. */
  40634. set: function (value) {
  40635. var mouse = this.inputs.attached["mouse"];
  40636. if (mouse)
  40637. mouse.angularSensibility = value;
  40638. },
  40639. enumerable: true,
  40640. configurable: true
  40641. });
  40642. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  40643. get: function () {
  40644. var keyboard = this.inputs.attached["keyboard"];
  40645. if (keyboard)
  40646. return keyboard.keysUp;
  40647. return [];
  40648. },
  40649. set: function (value) {
  40650. var keyboard = this.inputs.attached["keyboard"];
  40651. if (keyboard)
  40652. keyboard.keysUp = value;
  40653. },
  40654. enumerable: true,
  40655. configurable: true
  40656. });
  40657. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  40658. get: function () {
  40659. var keyboard = this.inputs.attached["keyboard"];
  40660. if (keyboard)
  40661. return keyboard.keysDown;
  40662. return [];
  40663. },
  40664. set: function (value) {
  40665. var keyboard = this.inputs.attached["keyboard"];
  40666. if (keyboard)
  40667. keyboard.keysDown = value;
  40668. },
  40669. enumerable: true,
  40670. configurable: true
  40671. });
  40672. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  40673. get: function () {
  40674. var keyboard = this.inputs.attached["keyboard"];
  40675. if (keyboard)
  40676. return keyboard.keysLeft;
  40677. return [];
  40678. },
  40679. set: function (value) {
  40680. var keyboard = this.inputs.attached["keyboard"];
  40681. if (keyboard)
  40682. keyboard.keysLeft = value;
  40683. },
  40684. enumerable: true,
  40685. configurable: true
  40686. });
  40687. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  40688. get: function () {
  40689. var keyboard = this.inputs.attached["keyboard"];
  40690. if (keyboard)
  40691. return keyboard.keysRight;
  40692. return [];
  40693. },
  40694. set: function (value) {
  40695. var keyboard = this.inputs.attached["keyboard"];
  40696. if (keyboard)
  40697. keyboard.keysRight = value;
  40698. },
  40699. enumerable: true,
  40700. configurable: true
  40701. });
  40702. // Controls
  40703. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  40704. this.inputs.attachElement(element, noPreventDefault);
  40705. };
  40706. FreeCamera.prototype.detachControl = function (element) {
  40707. this.inputs.detachElement(element);
  40708. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40709. this.cameraRotation = new BABYLON.Vector2(0, 0);
  40710. };
  40711. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  40712. get: function () {
  40713. return this._collisionMask;
  40714. },
  40715. set: function (mask) {
  40716. this._collisionMask = !isNaN(mask) ? mask : -1;
  40717. },
  40718. enumerable: true,
  40719. configurable: true
  40720. });
  40721. FreeCamera.prototype._collideWithWorld = function (displacement) {
  40722. var globalPosition;
  40723. if (this.parent) {
  40724. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  40725. }
  40726. else {
  40727. globalPosition = this.position;
  40728. }
  40729. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  40730. this._oldPosition.addInPlace(this.ellipsoidOffset);
  40731. if (!this._collider) {
  40732. this._collider = new BABYLON.Collider();
  40733. }
  40734. this._collider._radius = this.ellipsoid;
  40735. this._collider.collisionMask = this._collisionMask;
  40736. //no need for clone, as long as gravity is not on.
  40737. var actualDisplacement = displacement;
  40738. //add gravity to the direction to prevent the dual-collision checking
  40739. if (this.applyGravity) {
  40740. //this prevents mending with cameraDirection, a global variable of the free camera class.
  40741. actualDisplacement = displacement.add(this.getScene().gravity);
  40742. }
  40743. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40744. };
  40745. FreeCamera.prototype._checkInputs = function () {
  40746. if (!this._localDirection) {
  40747. this._localDirection = BABYLON.Vector3.Zero();
  40748. this._transformedDirection = BABYLON.Vector3.Zero();
  40749. }
  40750. this.inputs.checkInputs();
  40751. _super.prototype._checkInputs.call(this);
  40752. };
  40753. FreeCamera.prototype._decideIfNeedsToMove = function () {
  40754. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40755. };
  40756. FreeCamera.prototype._updatePosition = function () {
  40757. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  40758. this._collideWithWorld(this.cameraDirection);
  40759. }
  40760. else {
  40761. _super.prototype._updatePosition.call(this);
  40762. }
  40763. };
  40764. FreeCamera.prototype.dispose = function () {
  40765. this.inputs.clear();
  40766. _super.prototype.dispose.call(this);
  40767. };
  40768. FreeCamera.prototype.getClassName = function () {
  40769. return "FreeCamera";
  40770. };
  40771. __decorate([
  40772. BABYLON.serializeAsVector3()
  40773. ], FreeCamera.prototype, "ellipsoid", void 0);
  40774. __decorate([
  40775. BABYLON.serializeAsVector3()
  40776. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  40777. __decorate([
  40778. BABYLON.serialize()
  40779. ], FreeCamera.prototype, "checkCollisions", void 0);
  40780. __decorate([
  40781. BABYLON.serialize()
  40782. ], FreeCamera.prototype, "applyGravity", void 0);
  40783. return FreeCamera;
  40784. }(BABYLON.TargetCamera));
  40785. BABYLON.FreeCamera = FreeCamera;
  40786. })(BABYLON || (BABYLON = {}));
  40787. //# sourceMappingURL=babylon.freeCamera.js.map
  40788. var BABYLON;
  40789. (function (BABYLON) {
  40790. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  40791. function ArcRotateCameraKeyboardMoveInput() {
  40792. this._keys = new Array();
  40793. this.keysUp = [38];
  40794. this.keysDown = [40];
  40795. this.keysLeft = [37];
  40796. this.keysRight = [39];
  40797. this.keysReset = [220];
  40798. this.panningSensibility = 50.0;
  40799. this.zoomingSensibility = 25.0;
  40800. this.useAltToZoom = true;
  40801. }
  40802. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40803. var _this = this;
  40804. if (this._onCanvasBlurObserver) {
  40805. return;
  40806. }
  40807. this._scene = this.camera.getScene();
  40808. this._engine = this._scene.getEngine();
  40809. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40810. _this._keys = [];
  40811. });
  40812. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40813. var evt = info.event;
  40814. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40815. _this._ctrlPressed = evt.ctrlKey;
  40816. _this._altPressed = evt.altKey;
  40817. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40818. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40819. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40820. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40821. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40822. var index = _this._keys.indexOf(evt.keyCode);
  40823. if (index === -1) {
  40824. _this._keys.push(evt.keyCode);
  40825. }
  40826. if (evt.preventDefault) {
  40827. if (!noPreventDefault) {
  40828. evt.preventDefault();
  40829. }
  40830. }
  40831. }
  40832. }
  40833. else {
  40834. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40835. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40836. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40837. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40838. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40839. var index = _this._keys.indexOf(evt.keyCode);
  40840. if (index >= 0) {
  40841. _this._keys.splice(index, 1);
  40842. }
  40843. if (evt.preventDefault) {
  40844. if (!noPreventDefault) {
  40845. evt.preventDefault();
  40846. }
  40847. }
  40848. }
  40849. }
  40850. });
  40851. };
  40852. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40853. if (this._scene) {
  40854. if (this._onKeyboardObserver) {
  40855. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40856. }
  40857. if (this._onCanvasBlurObserver) {
  40858. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40859. }
  40860. this._onKeyboardObserver = null;
  40861. this._onCanvasBlurObserver = null;
  40862. }
  40863. this._keys = [];
  40864. };
  40865. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40866. if (this._onKeyboardObserver) {
  40867. var camera = this.camera;
  40868. for (var index = 0; index < this._keys.length; index++) {
  40869. var keyCode = this._keys[index];
  40870. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40871. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40872. camera.inertialPanningX -= 1 / this.panningSensibility;
  40873. }
  40874. else {
  40875. camera.inertialAlphaOffset -= 0.01;
  40876. }
  40877. }
  40878. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40879. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40880. camera.inertialPanningY += 1 / this.panningSensibility;
  40881. }
  40882. else if (this._altPressed && this.useAltToZoom) {
  40883. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  40884. }
  40885. else {
  40886. camera.inertialBetaOffset -= 0.01;
  40887. }
  40888. }
  40889. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40890. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40891. camera.inertialPanningX += 1 / this.panningSensibility;
  40892. }
  40893. else {
  40894. camera.inertialAlphaOffset += 0.01;
  40895. }
  40896. }
  40897. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40898. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40899. camera.inertialPanningY -= 1 / this.panningSensibility;
  40900. }
  40901. else if (this._altPressed && this.useAltToZoom) {
  40902. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  40903. }
  40904. else {
  40905. camera.inertialBetaOffset += 0.01;
  40906. }
  40907. }
  40908. else if (this.keysReset.indexOf(keyCode) !== -1) {
  40909. camera.restoreState();
  40910. }
  40911. }
  40912. }
  40913. };
  40914. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  40915. return "ArcRotateCameraKeyboardMoveInput";
  40916. };
  40917. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40918. return "keyboard";
  40919. };
  40920. __decorate([
  40921. BABYLON.serialize()
  40922. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40923. __decorate([
  40924. BABYLON.serialize()
  40925. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40926. __decorate([
  40927. BABYLON.serialize()
  40928. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40929. __decorate([
  40930. BABYLON.serialize()
  40931. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40932. __decorate([
  40933. BABYLON.serialize()
  40934. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  40935. __decorate([
  40936. BABYLON.serialize()
  40937. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  40938. __decorate([
  40939. BABYLON.serialize()
  40940. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  40941. __decorate([
  40942. BABYLON.serialize()
  40943. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  40944. return ArcRotateCameraKeyboardMoveInput;
  40945. }());
  40946. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  40947. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  40948. })(BABYLON || (BABYLON = {}));
  40949. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  40950. var BABYLON;
  40951. (function (BABYLON) {
  40952. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  40953. function ArcRotateCameraMouseWheelInput() {
  40954. this.wheelPrecision = 3.0;
  40955. /**
  40956. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  40957. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  40958. */
  40959. this.wheelDeltaPercentage = 0;
  40960. }
  40961. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  40962. var _this = this;
  40963. this._wheel = function (p, s) {
  40964. //sanity check - this should be a PointerWheel event.
  40965. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  40966. return;
  40967. var event = p.event;
  40968. var delta = 0;
  40969. if (event.wheelDelta) {
  40970. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  40971. }
  40972. else if (event.detail) {
  40973. delta = -event.detail / _this.wheelPrecision;
  40974. }
  40975. if (delta)
  40976. _this.camera.inertialRadiusOffset += delta;
  40977. if (event.preventDefault) {
  40978. if (!noPreventDefault) {
  40979. event.preventDefault();
  40980. }
  40981. }
  40982. };
  40983. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  40984. };
  40985. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  40986. if (this._observer && element) {
  40987. this.camera.getScene().onPointerObservable.remove(this._observer);
  40988. this._observer = null;
  40989. this._wheel = null;
  40990. }
  40991. };
  40992. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  40993. return "ArcRotateCameraMouseWheelInput";
  40994. };
  40995. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  40996. return "mousewheel";
  40997. };
  40998. __decorate([
  40999. BABYLON.serialize()
  41000. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41001. __decorate([
  41002. BABYLON.serialize()
  41003. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41004. return ArcRotateCameraMouseWheelInput;
  41005. }());
  41006. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41007. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41008. })(BABYLON || (BABYLON = {}));
  41009. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41010. var BABYLON;
  41011. (function (BABYLON) {
  41012. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41013. function ArcRotateCameraPointersInput() {
  41014. this.buttons = [0, 1, 2];
  41015. this.angularSensibilityX = 1000.0;
  41016. this.angularSensibilityY = 1000.0;
  41017. this.pinchPrecision = 12.0;
  41018. /**
  41019. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41020. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41021. */
  41022. this.pinchDeltaPercentage = 0;
  41023. this.panningSensibility = 1000.0;
  41024. this.multiTouchPanning = true;
  41025. this.multiTouchPanAndZoom = true;
  41026. this._isPanClick = false;
  41027. this.pinchInwards = true;
  41028. }
  41029. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41030. var _this = this;
  41031. var engine = this.camera.getEngine();
  41032. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41033. var pointA = null;
  41034. var pointB = null;
  41035. var previousPinchSquaredDistance = 0;
  41036. var initialDistance = 0;
  41037. var twoFingerActivityCount = 0;
  41038. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41039. this._pointerInput = function (p, s) {
  41040. var evt = p.event;
  41041. var isTouch = p.event.pointerType === "touch";
  41042. if (engine.isInVRExclusivePointerMode) {
  41043. return;
  41044. }
  41045. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41046. return;
  41047. }
  41048. var srcElement = (evt.srcElement || evt.target);
  41049. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41050. try {
  41051. srcElement.setPointerCapture(evt.pointerId);
  41052. }
  41053. catch (e) {
  41054. //Nothing to do with the error. Execution will continue.
  41055. }
  41056. // Manage panning with pan button click
  41057. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41058. // manage pointers
  41059. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41060. if (pointA === null) {
  41061. pointA = cacheSoloPointer;
  41062. }
  41063. else if (pointB === null) {
  41064. pointB = cacheSoloPointer;
  41065. }
  41066. if (!noPreventDefault) {
  41067. evt.preventDefault();
  41068. element.focus();
  41069. }
  41070. }
  41071. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41072. _this.camera.restoreState();
  41073. }
  41074. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41075. try {
  41076. srcElement.releasePointerCapture(evt.pointerId);
  41077. }
  41078. catch (e) {
  41079. //Nothing to do with the error.
  41080. }
  41081. cacheSoloPointer = null;
  41082. previousPinchSquaredDistance = 0;
  41083. previousMultiTouchPanPosition.isPaning = false;
  41084. previousMultiTouchPanPosition.isPinching = false;
  41085. twoFingerActivityCount = 0;
  41086. initialDistance = 0;
  41087. if (!isTouch) {
  41088. pointB = null; // Mouse and pen are mono pointer
  41089. }
  41090. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41091. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41092. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41093. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41094. if (engine.badOS) {
  41095. pointA = pointB = null;
  41096. }
  41097. else {
  41098. //only remove the impacted pointer in case of multitouch allowing on most
  41099. //platforms switching from rotate to zoom and pan seamlessly.
  41100. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41101. pointA = pointB;
  41102. pointB = null;
  41103. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41104. }
  41105. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41106. pointB = null;
  41107. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41108. }
  41109. else {
  41110. pointA = pointB = null;
  41111. }
  41112. }
  41113. if (!noPreventDefault) {
  41114. evt.preventDefault();
  41115. }
  41116. }
  41117. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41118. if (!noPreventDefault) {
  41119. evt.preventDefault();
  41120. }
  41121. // One button down
  41122. if (pointA && pointB === null && cacheSoloPointer) {
  41123. if (_this.panningSensibility !== 0 &&
  41124. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41125. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41126. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41127. }
  41128. else {
  41129. var offsetX = evt.clientX - cacheSoloPointer.x;
  41130. var offsetY = evt.clientY - cacheSoloPointer.y;
  41131. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41132. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41133. }
  41134. cacheSoloPointer.x = evt.clientX;
  41135. cacheSoloPointer.y = evt.clientY;
  41136. }
  41137. else if (pointA && pointB) {
  41138. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41139. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41140. ed.x = evt.clientX;
  41141. ed.y = evt.clientY;
  41142. var direction = _this.pinchInwards ? 1 : -1;
  41143. var distX = pointA.x - pointB.x;
  41144. var distY = pointA.y - pointB.y;
  41145. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41146. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41147. if (previousPinchSquaredDistance === 0) {
  41148. initialDistance = pinchDistance;
  41149. previousPinchSquaredDistance = pinchSquaredDistance;
  41150. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41151. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41152. return;
  41153. }
  41154. if (_this.multiTouchPanAndZoom) {
  41155. if (_this.pinchDeltaPercentage) {
  41156. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41157. }
  41158. else {
  41159. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41160. (_this.pinchPrecision *
  41161. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41162. direction);
  41163. }
  41164. if (_this.panningSensibility !== 0) {
  41165. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41166. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41167. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41168. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41169. previousMultiTouchPanPosition.x = pointersCenterX;
  41170. previousMultiTouchPanPosition.y = pointersCenterY;
  41171. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41172. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41173. }
  41174. }
  41175. else {
  41176. twoFingerActivityCount++;
  41177. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41178. if (_this.pinchDeltaPercentage) {
  41179. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41180. }
  41181. else {
  41182. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41183. (_this.pinchPrecision *
  41184. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41185. direction);
  41186. }
  41187. previousMultiTouchPanPosition.isPaning = false;
  41188. previousMultiTouchPanPosition.isPinching = true;
  41189. }
  41190. else {
  41191. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41192. if (!previousMultiTouchPanPosition.isPaning) {
  41193. previousMultiTouchPanPosition.isPaning = true;
  41194. previousMultiTouchPanPosition.isPinching = false;
  41195. previousMultiTouchPanPosition.x = ed.x;
  41196. previousMultiTouchPanPosition.y = ed.y;
  41197. return;
  41198. }
  41199. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41200. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41201. }
  41202. }
  41203. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41204. previousMultiTouchPanPosition.x = ed.x;
  41205. previousMultiTouchPanPosition.y = ed.y;
  41206. }
  41207. }
  41208. previousPinchSquaredDistance = pinchSquaredDistance;
  41209. }
  41210. }
  41211. };
  41212. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41213. this._onContextMenu = function (evt) {
  41214. evt.preventDefault();
  41215. };
  41216. if (!this.camera._useCtrlForPanning) {
  41217. element.addEventListener("contextmenu", this._onContextMenu, false);
  41218. }
  41219. this._onLostFocus = function () {
  41220. //this._keys = [];
  41221. pointA = pointB = null;
  41222. previousPinchSquaredDistance = 0;
  41223. previousMultiTouchPanPosition.isPaning = false;
  41224. previousMultiTouchPanPosition.isPinching = false;
  41225. twoFingerActivityCount = 0;
  41226. cacheSoloPointer = null;
  41227. initialDistance = 0;
  41228. };
  41229. this._onMouseMove = function (evt) {
  41230. if (!engine.isPointerLock) {
  41231. return;
  41232. }
  41233. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41234. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41235. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41236. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41237. if (!noPreventDefault) {
  41238. evt.preventDefault();
  41239. }
  41240. };
  41241. this._onGestureStart = function (e) {
  41242. if (window.MSGesture === undefined) {
  41243. return;
  41244. }
  41245. if (!_this._MSGestureHandler) {
  41246. _this._MSGestureHandler = new MSGesture();
  41247. _this._MSGestureHandler.target = element;
  41248. }
  41249. _this._MSGestureHandler.addPointer(e.pointerId);
  41250. };
  41251. this._onGesture = function (e) {
  41252. _this.camera.radius *= e.scale;
  41253. if (e.preventDefault) {
  41254. if (!noPreventDefault) {
  41255. e.stopPropagation();
  41256. e.preventDefault();
  41257. }
  41258. }
  41259. };
  41260. element.addEventListener("mousemove", this._onMouseMove, false);
  41261. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41262. element.addEventListener("MSGestureChange", this._onGesture, false);
  41263. BABYLON.Tools.RegisterTopRootEvents([
  41264. { name: "blur", handler: this._onLostFocus }
  41265. ]);
  41266. };
  41267. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41268. if (this._onLostFocus) {
  41269. BABYLON.Tools.UnregisterTopRootEvents([
  41270. { name: "blur", handler: this._onLostFocus }
  41271. ]);
  41272. }
  41273. if (element && this._observer) {
  41274. this.camera.getScene().onPointerObservable.remove(this._observer);
  41275. this._observer = null;
  41276. if (this._onContextMenu) {
  41277. element.removeEventListener("contextmenu", this._onContextMenu);
  41278. }
  41279. if (this._onMouseMove) {
  41280. element.removeEventListener("mousemove", this._onMouseMove);
  41281. }
  41282. if (this._onGestureStart) {
  41283. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41284. }
  41285. if (this._onGesture) {
  41286. element.removeEventListener("MSGestureChange", this._onGesture);
  41287. }
  41288. this._isPanClick = false;
  41289. this.pinchInwards = true;
  41290. this._onMouseMove = null;
  41291. this._onGestureStart = null;
  41292. this._onGesture = null;
  41293. this._MSGestureHandler = null;
  41294. this._onLostFocus = null;
  41295. this._onContextMenu = null;
  41296. }
  41297. };
  41298. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41299. return "ArcRotateCameraPointersInput";
  41300. };
  41301. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41302. return "pointers";
  41303. };
  41304. __decorate([
  41305. BABYLON.serialize()
  41306. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41307. __decorate([
  41308. BABYLON.serialize()
  41309. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41310. __decorate([
  41311. BABYLON.serialize()
  41312. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41313. __decorate([
  41314. BABYLON.serialize()
  41315. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  41316. __decorate([
  41317. BABYLON.serialize()
  41318. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  41319. __decorate([
  41320. BABYLON.serialize()
  41321. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  41322. __decorate([
  41323. BABYLON.serialize()
  41324. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  41325. __decorate([
  41326. BABYLON.serialize()
  41327. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  41328. return ArcRotateCameraPointersInput;
  41329. }());
  41330. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  41331. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  41332. })(BABYLON || (BABYLON = {}));
  41333. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  41334. var BABYLON;
  41335. (function (BABYLON) {
  41336. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  41337. __extends(ArcRotateCameraInputsManager, _super);
  41338. function ArcRotateCameraInputsManager(camera) {
  41339. return _super.call(this, camera) || this;
  41340. }
  41341. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  41342. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  41343. return this;
  41344. };
  41345. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  41346. this.add(new BABYLON.ArcRotateCameraPointersInput());
  41347. return this;
  41348. };
  41349. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  41350. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  41351. return this;
  41352. };
  41353. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  41354. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  41355. return this;
  41356. };
  41357. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  41358. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  41359. return this;
  41360. };
  41361. return ArcRotateCameraInputsManager;
  41362. }(BABYLON.CameraInputsManager));
  41363. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  41364. })(BABYLON || (BABYLON = {}));
  41365. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  41366. var BABYLON;
  41367. (function (BABYLON) {
  41368. var ArcRotateCamera = /** @class */ (function (_super) {
  41369. __extends(ArcRotateCamera, _super);
  41370. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  41371. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  41372. _this.inertialAlphaOffset = 0;
  41373. _this.inertialBetaOffset = 0;
  41374. _this.inertialRadiusOffset = 0;
  41375. _this.lowerAlphaLimit = null;
  41376. _this.upperAlphaLimit = null;
  41377. _this.lowerBetaLimit = 0.01;
  41378. _this.upperBetaLimit = Math.PI;
  41379. _this.lowerRadiusLimit = null;
  41380. _this.upperRadiusLimit = null;
  41381. _this.inertialPanningX = 0;
  41382. _this.inertialPanningY = 0;
  41383. _this.pinchToPanMaxDistance = 20;
  41384. _this.panningDistanceLimit = null;
  41385. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  41386. _this.panningInertia = 0.9;
  41387. //-- end properties for backward compatibility for inputs
  41388. _this.zoomOnFactor = 1;
  41389. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  41390. _this.allowUpsideDown = true;
  41391. _this._viewMatrix = new BABYLON.Matrix();
  41392. // Panning
  41393. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  41394. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  41395. _this.checkCollisions = false;
  41396. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  41397. _this._previousPosition = BABYLON.Vector3.Zero();
  41398. _this._collisionVelocity = BABYLON.Vector3.Zero();
  41399. _this._newPosition = BABYLON.Vector3.Zero();
  41400. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41401. if (collidedMesh === void 0) { collidedMesh = null; }
  41402. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  41403. newPosition.multiplyInPlace(_this._collider._radius);
  41404. }
  41405. if (!collidedMesh) {
  41406. _this._previousPosition.copyFrom(_this.position);
  41407. }
  41408. else {
  41409. _this.setPosition(newPosition);
  41410. if (_this.onCollide) {
  41411. _this.onCollide(collidedMesh);
  41412. }
  41413. }
  41414. // Recompute because of constraints
  41415. var cosa = Math.cos(_this.alpha);
  41416. var sina = Math.sin(_this.alpha);
  41417. var cosb = Math.cos(_this.beta);
  41418. var sinb = Math.sin(_this.beta);
  41419. if (sinb === 0) {
  41420. sinb = 0.0001;
  41421. }
  41422. var target = _this._getTargetPosition();
  41423. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  41424. _this.position.copyFrom(_this._newPosition);
  41425. var up = _this.upVector;
  41426. if (_this.allowUpsideDown && _this.beta < 0) {
  41427. up = up.clone();
  41428. up = up.negate();
  41429. }
  41430. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  41431. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  41432. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  41433. _this._collisionTriggered = false;
  41434. };
  41435. _this._target = BABYLON.Vector3.Zero();
  41436. if (target) {
  41437. _this.setTarget(target);
  41438. }
  41439. _this.alpha = alpha;
  41440. _this.beta = beta;
  41441. _this.radius = radius;
  41442. _this.getViewMatrix();
  41443. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  41444. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  41445. return _this;
  41446. }
  41447. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  41448. get: function () {
  41449. return this._target;
  41450. },
  41451. set: function (value) {
  41452. this.setTarget(value);
  41453. },
  41454. enumerable: true,
  41455. configurable: true
  41456. });
  41457. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  41458. //-- begin properties for backward compatibility for inputs
  41459. get: function () {
  41460. var pointers = this.inputs.attached["pointers"];
  41461. if (pointers)
  41462. return pointers.angularSensibilityX;
  41463. return 0;
  41464. },
  41465. set: function (value) {
  41466. var pointers = this.inputs.attached["pointers"];
  41467. if (pointers) {
  41468. pointers.angularSensibilityX = value;
  41469. }
  41470. },
  41471. enumerable: true,
  41472. configurable: true
  41473. });
  41474. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  41475. get: function () {
  41476. var pointers = this.inputs.attached["pointers"];
  41477. if (pointers)
  41478. return pointers.angularSensibilityY;
  41479. return 0;
  41480. },
  41481. set: function (value) {
  41482. var pointers = this.inputs.attached["pointers"];
  41483. if (pointers) {
  41484. pointers.angularSensibilityY = value;
  41485. }
  41486. },
  41487. enumerable: true,
  41488. configurable: true
  41489. });
  41490. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  41491. get: function () {
  41492. var pointers = this.inputs.attached["pointers"];
  41493. if (pointers)
  41494. return pointers.pinchPrecision;
  41495. return 0;
  41496. },
  41497. set: function (value) {
  41498. var pointers = this.inputs.attached["pointers"];
  41499. if (pointers) {
  41500. pointers.pinchPrecision = value;
  41501. }
  41502. },
  41503. enumerable: true,
  41504. configurable: true
  41505. });
  41506. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  41507. get: function () {
  41508. var pointers = this.inputs.attached["pointers"];
  41509. if (pointers)
  41510. return pointers.pinchDeltaPercentage;
  41511. return 0;
  41512. },
  41513. set: function (value) {
  41514. var pointers = this.inputs.attached["pointers"];
  41515. if (pointers) {
  41516. pointers.pinchDeltaPercentage = value;
  41517. }
  41518. },
  41519. enumerable: true,
  41520. configurable: true
  41521. });
  41522. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  41523. get: function () {
  41524. var pointers = this.inputs.attached["pointers"];
  41525. if (pointers)
  41526. return pointers.panningSensibility;
  41527. return 0;
  41528. },
  41529. set: function (value) {
  41530. var pointers = this.inputs.attached["pointers"];
  41531. if (pointers) {
  41532. pointers.panningSensibility = value;
  41533. }
  41534. },
  41535. enumerable: true,
  41536. configurable: true
  41537. });
  41538. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  41539. get: function () {
  41540. var keyboard = this.inputs.attached["keyboard"];
  41541. if (keyboard)
  41542. return keyboard.keysUp;
  41543. return [];
  41544. },
  41545. set: function (value) {
  41546. var keyboard = this.inputs.attached["keyboard"];
  41547. if (keyboard)
  41548. keyboard.keysUp = value;
  41549. },
  41550. enumerable: true,
  41551. configurable: true
  41552. });
  41553. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  41554. get: function () {
  41555. var keyboard = this.inputs.attached["keyboard"];
  41556. if (keyboard)
  41557. return keyboard.keysDown;
  41558. return [];
  41559. },
  41560. set: function (value) {
  41561. var keyboard = this.inputs.attached["keyboard"];
  41562. if (keyboard)
  41563. keyboard.keysDown = value;
  41564. },
  41565. enumerable: true,
  41566. configurable: true
  41567. });
  41568. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  41569. get: function () {
  41570. var keyboard = this.inputs.attached["keyboard"];
  41571. if (keyboard)
  41572. return keyboard.keysLeft;
  41573. return [];
  41574. },
  41575. set: function (value) {
  41576. var keyboard = this.inputs.attached["keyboard"];
  41577. if (keyboard)
  41578. keyboard.keysLeft = value;
  41579. },
  41580. enumerable: true,
  41581. configurable: true
  41582. });
  41583. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  41584. get: function () {
  41585. var keyboard = this.inputs.attached["keyboard"];
  41586. if (keyboard)
  41587. return keyboard.keysRight;
  41588. return [];
  41589. },
  41590. set: function (value) {
  41591. var keyboard = this.inputs.attached["keyboard"];
  41592. if (keyboard)
  41593. keyboard.keysRight = value;
  41594. },
  41595. enumerable: true,
  41596. configurable: true
  41597. });
  41598. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  41599. get: function () {
  41600. var mousewheel = this.inputs.attached["mousewheel"];
  41601. if (mousewheel)
  41602. return mousewheel.wheelPrecision;
  41603. return 0;
  41604. },
  41605. set: function (value) {
  41606. var mousewheel = this.inputs.attached["mousewheel"];
  41607. if (mousewheel)
  41608. mousewheel.wheelPrecision = value;
  41609. },
  41610. enumerable: true,
  41611. configurable: true
  41612. });
  41613. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  41614. get: function () {
  41615. var mousewheel = this.inputs.attached["mousewheel"];
  41616. if (mousewheel)
  41617. return mousewheel.wheelDeltaPercentage;
  41618. return 0;
  41619. },
  41620. set: function (value) {
  41621. var mousewheel = this.inputs.attached["mousewheel"];
  41622. if (mousewheel)
  41623. mousewheel.wheelDeltaPercentage = value;
  41624. },
  41625. enumerable: true,
  41626. configurable: true
  41627. });
  41628. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  41629. get: function () {
  41630. return this._bouncingBehavior;
  41631. },
  41632. enumerable: true,
  41633. configurable: true
  41634. });
  41635. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  41636. get: function () {
  41637. return this._bouncingBehavior != null;
  41638. },
  41639. set: function (value) {
  41640. if (value === this.useBouncingBehavior) {
  41641. return;
  41642. }
  41643. if (value) {
  41644. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  41645. this.addBehavior(this._bouncingBehavior);
  41646. }
  41647. else if (this._bouncingBehavior) {
  41648. this.removeBehavior(this._bouncingBehavior);
  41649. this._bouncingBehavior = null;
  41650. }
  41651. },
  41652. enumerable: true,
  41653. configurable: true
  41654. });
  41655. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  41656. get: function () {
  41657. return this._framingBehavior;
  41658. },
  41659. enumerable: true,
  41660. configurable: true
  41661. });
  41662. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  41663. get: function () {
  41664. return this._framingBehavior != null;
  41665. },
  41666. set: function (value) {
  41667. if (value === this.useFramingBehavior) {
  41668. return;
  41669. }
  41670. if (value) {
  41671. this._framingBehavior = new BABYLON.FramingBehavior();
  41672. this.addBehavior(this._framingBehavior);
  41673. }
  41674. else if (this._framingBehavior) {
  41675. this.removeBehavior(this._framingBehavior);
  41676. this._framingBehavior = null;
  41677. }
  41678. },
  41679. enumerable: true,
  41680. configurable: true
  41681. });
  41682. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  41683. get: function () {
  41684. return this._autoRotationBehavior;
  41685. },
  41686. enumerable: true,
  41687. configurable: true
  41688. });
  41689. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  41690. get: function () {
  41691. return this._autoRotationBehavior != null;
  41692. },
  41693. set: function (value) {
  41694. if (value === this.useAutoRotationBehavior) {
  41695. return;
  41696. }
  41697. if (value) {
  41698. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  41699. this.addBehavior(this._autoRotationBehavior);
  41700. }
  41701. else if (this._autoRotationBehavior) {
  41702. this.removeBehavior(this._autoRotationBehavior);
  41703. this._autoRotationBehavior = null;
  41704. }
  41705. },
  41706. enumerable: true,
  41707. configurable: true
  41708. });
  41709. // Cache
  41710. ArcRotateCamera.prototype._initCache = function () {
  41711. _super.prototype._initCache.call(this);
  41712. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  41713. this._cache.alpha = undefined;
  41714. this._cache.beta = undefined;
  41715. this._cache.radius = undefined;
  41716. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  41717. };
  41718. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  41719. if (!ignoreParentClass) {
  41720. _super.prototype._updateCache.call(this);
  41721. }
  41722. this._cache._target.copyFrom(this._getTargetPosition());
  41723. this._cache.alpha = this.alpha;
  41724. this._cache.beta = this.beta;
  41725. this._cache.radius = this.radius;
  41726. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  41727. };
  41728. ArcRotateCamera.prototype._getTargetPosition = function () {
  41729. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  41730. var pos = this._targetHost.getAbsolutePosition();
  41731. if (this._targetBoundingCenter) {
  41732. pos.addToRef(this._targetBoundingCenter, this._target);
  41733. }
  41734. else {
  41735. this._target.copyFrom(pos);
  41736. }
  41737. }
  41738. var lockedTargetPosition = this._getLockedTargetPosition();
  41739. if (lockedTargetPosition) {
  41740. return lockedTargetPosition;
  41741. }
  41742. return this._target;
  41743. };
  41744. ArcRotateCamera.prototype.storeState = function () {
  41745. this._storedAlpha = this.alpha;
  41746. this._storedBeta = this.beta;
  41747. this._storedRadius = this.radius;
  41748. this._storedTarget = this._getTargetPosition().clone();
  41749. return _super.prototype.storeState.call(this);
  41750. };
  41751. /**
  41752. * Restored camera state. You must call storeState() first
  41753. */
  41754. ArcRotateCamera.prototype._restoreStateValues = function () {
  41755. if (!_super.prototype._restoreStateValues.call(this)) {
  41756. return false;
  41757. }
  41758. this.alpha = this._storedAlpha;
  41759. this.beta = this._storedBeta;
  41760. this.radius = this._storedRadius;
  41761. this.setTarget(this._storedTarget.clone());
  41762. this.inertialAlphaOffset = 0;
  41763. this.inertialBetaOffset = 0;
  41764. this.inertialRadiusOffset = 0;
  41765. this.inertialPanningX = 0;
  41766. this.inertialPanningY = 0;
  41767. return true;
  41768. };
  41769. // Synchronized
  41770. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  41771. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  41772. return false;
  41773. return this._cache._target.equals(this._getTargetPosition())
  41774. && this._cache.alpha === this.alpha
  41775. && this._cache.beta === this.beta
  41776. && this._cache.radius === this.radius
  41777. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  41778. };
  41779. // Methods
  41780. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  41781. var _this = this;
  41782. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  41783. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  41784. this._useCtrlForPanning = useCtrlForPanning;
  41785. this._panningMouseButton = panningMouseButton;
  41786. this.inputs.attachElement(element, noPreventDefault);
  41787. this._reset = function () {
  41788. _this.inertialAlphaOffset = 0;
  41789. _this.inertialBetaOffset = 0;
  41790. _this.inertialRadiusOffset = 0;
  41791. _this.inertialPanningX = 0;
  41792. _this.inertialPanningY = 0;
  41793. };
  41794. };
  41795. ArcRotateCamera.prototype.detachControl = function (element) {
  41796. this.inputs.detachElement(element);
  41797. if (this._reset) {
  41798. this._reset();
  41799. }
  41800. };
  41801. ArcRotateCamera.prototype._checkInputs = function () {
  41802. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  41803. if (this._collisionTriggered) {
  41804. return;
  41805. }
  41806. this.inputs.checkInputs();
  41807. // Inertia
  41808. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  41809. if (this.getScene().useRightHandedSystem) {
  41810. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41811. }
  41812. else {
  41813. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41814. }
  41815. this.beta += this.inertialBetaOffset;
  41816. this.radius -= this.inertialRadiusOffset;
  41817. this.inertialAlphaOffset *= this.inertia;
  41818. this.inertialBetaOffset *= this.inertia;
  41819. this.inertialRadiusOffset *= this.inertia;
  41820. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  41821. this.inertialAlphaOffset = 0;
  41822. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  41823. this.inertialBetaOffset = 0;
  41824. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  41825. this.inertialRadiusOffset = 0;
  41826. }
  41827. // Panning inertia
  41828. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  41829. if (!this._localDirection) {
  41830. this._localDirection = BABYLON.Vector3.Zero();
  41831. this._transformedDirection = BABYLON.Vector3.Zero();
  41832. }
  41833. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  41834. this._localDirection.multiplyInPlace(this.panningAxis);
  41835. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  41836. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  41837. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  41838. if (!this.panningAxis.y) {
  41839. this._transformedDirection.y = 0;
  41840. }
  41841. if (!this._targetHost) {
  41842. if (this.panningDistanceLimit) {
  41843. this._transformedDirection.addInPlace(this._target);
  41844. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  41845. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  41846. this._target.copyFrom(this._transformedDirection);
  41847. }
  41848. }
  41849. else {
  41850. this._target.addInPlace(this._transformedDirection);
  41851. }
  41852. }
  41853. this.inertialPanningX *= this.panningInertia;
  41854. this.inertialPanningY *= this.panningInertia;
  41855. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  41856. this.inertialPanningX = 0;
  41857. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  41858. this.inertialPanningY = 0;
  41859. }
  41860. // Limits
  41861. this._checkLimits();
  41862. _super.prototype._checkInputs.call(this);
  41863. };
  41864. ArcRotateCamera.prototype._checkLimits = function () {
  41865. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  41866. if (this.allowUpsideDown && this.beta > Math.PI) {
  41867. this.beta = this.beta - (2 * Math.PI);
  41868. }
  41869. }
  41870. else {
  41871. if (this.beta < this.lowerBetaLimit) {
  41872. this.beta = this.lowerBetaLimit;
  41873. }
  41874. }
  41875. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  41876. if (this.allowUpsideDown && this.beta < -Math.PI) {
  41877. this.beta = this.beta + (2 * Math.PI);
  41878. }
  41879. }
  41880. else {
  41881. if (this.beta > this.upperBetaLimit) {
  41882. this.beta = this.upperBetaLimit;
  41883. }
  41884. }
  41885. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  41886. this.alpha = this.lowerAlphaLimit;
  41887. }
  41888. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  41889. this.alpha = this.upperAlphaLimit;
  41890. }
  41891. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  41892. this.radius = this.lowerRadiusLimit;
  41893. }
  41894. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  41895. this.radius = this.upperRadiusLimit;
  41896. }
  41897. };
  41898. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  41899. var radiusv3 = this.position.subtract(this._getTargetPosition());
  41900. this.radius = radiusv3.length();
  41901. if (this.radius === 0) {
  41902. this.radius = 0.0001; // Just to avoid division by zero
  41903. }
  41904. // Alpha
  41905. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  41906. if (radiusv3.z < 0) {
  41907. this.alpha = 2 * Math.PI - this.alpha;
  41908. }
  41909. // Beta
  41910. this.beta = Math.acos(radiusv3.y / this.radius);
  41911. this._checkLimits();
  41912. };
  41913. ArcRotateCamera.prototype.setPosition = function (position) {
  41914. if (this.position.equals(position)) {
  41915. return;
  41916. }
  41917. this.position.copyFrom(position);
  41918. this.rebuildAnglesAndRadius();
  41919. };
  41920. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  41921. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  41922. if (allowSamePosition === void 0) { allowSamePosition = false; }
  41923. if (target.getBoundingInfo) {
  41924. if (toBoundingCenter) {
  41925. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  41926. }
  41927. else {
  41928. this._targetBoundingCenter = null;
  41929. }
  41930. this._targetHost = target;
  41931. this._target = this._getTargetPosition();
  41932. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  41933. }
  41934. else {
  41935. var newTarget = target;
  41936. var currentTarget = this._getTargetPosition();
  41937. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  41938. return;
  41939. }
  41940. this._targetHost = null;
  41941. this._target = newTarget;
  41942. this._targetBoundingCenter = null;
  41943. this.onMeshTargetChangedObservable.notifyObservers(null);
  41944. }
  41945. this.rebuildAnglesAndRadius();
  41946. };
  41947. ArcRotateCamera.prototype._getViewMatrix = function () {
  41948. // Compute
  41949. var cosa = Math.cos(this.alpha);
  41950. var sina = Math.sin(this.alpha);
  41951. var cosb = Math.cos(this.beta);
  41952. var sinb = Math.sin(this.beta);
  41953. if (sinb === 0) {
  41954. sinb = 0.0001;
  41955. }
  41956. var target = this._getTargetPosition();
  41957. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  41958. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  41959. if (!this._collider) {
  41960. this._collider = new BABYLON.Collider();
  41961. }
  41962. this._collider._radius = this.collisionRadius;
  41963. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  41964. this._collisionTriggered = true;
  41965. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41966. }
  41967. else {
  41968. this.position.copyFrom(this._newPosition);
  41969. var up = this.upVector;
  41970. if (this.allowUpsideDown && sinb < 0) {
  41971. up = up.clone();
  41972. up = up.negate();
  41973. }
  41974. if (this.getScene().useRightHandedSystem) {
  41975. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  41976. }
  41977. else {
  41978. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  41979. }
  41980. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  41981. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  41982. }
  41983. this._currentTarget = target;
  41984. return this._viewMatrix;
  41985. };
  41986. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  41987. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  41988. meshes = meshes || this.getScene().meshes;
  41989. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  41990. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  41991. this.radius = distance * this.zoomOnFactor;
  41992. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  41993. };
  41994. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  41995. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  41996. var meshesOrMinMaxVector;
  41997. var distance;
  41998. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  41999. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42000. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42001. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42002. }
  42003. else {
  42004. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42005. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42006. distance = minMaxVectorAndDistance.distance;
  42007. }
  42008. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42009. if (!doNotUpdateMaxZ) {
  42010. this.maxZ = distance * 2;
  42011. }
  42012. };
  42013. /**
  42014. * @override
  42015. * Override Camera.createRigCamera
  42016. */
  42017. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42018. var alphaShift = 0;
  42019. switch (this.cameraRigMode) {
  42020. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42021. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42022. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42023. case BABYLON.Camera.RIG_MODE_VR:
  42024. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42025. break;
  42026. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42027. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42028. break;
  42029. }
  42030. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42031. rigCam._cameraRigParams = {};
  42032. return rigCam;
  42033. };
  42034. /**
  42035. * @override
  42036. * Override Camera._updateRigCameras
  42037. */
  42038. ArcRotateCamera.prototype._updateRigCameras = function () {
  42039. var camLeft = this._rigCameras[0];
  42040. var camRight = this._rigCameras[1];
  42041. camLeft.beta = camRight.beta = this.beta;
  42042. camLeft.radius = camRight.radius = this.radius;
  42043. switch (this.cameraRigMode) {
  42044. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42045. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42046. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42047. case BABYLON.Camera.RIG_MODE_VR:
  42048. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42049. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42050. break;
  42051. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42052. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42053. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42054. break;
  42055. }
  42056. _super.prototype._updateRigCameras.call(this);
  42057. };
  42058. ArcRotateCamera.prototype.dispose = function () {
  42059. this.inputs.clear();
  42060. _super.prototype.dispose.call(this);
  42061. };
  42062. ArcRotateCamera.prototype.getClassName = function () {
  42063. return "ArcRotateCamera";
  42064. };
  42065. __decorate([
  42066. BABYLON.serialize()
  42067. ], ArcRotateCamera.prototype, "alpha", void 0);
  42068. __decorate([
  42069. BABYLON.serialize()
  42070. ], ArcRotateCamera.prototype, "beta", void 0);
  42071. __decorate([
  42072. BABYLON.serialize()
  42073. ], ArcRotateCamera.prototype, "radius", void 0);
  42074. __decorate([
  42075. BABYLON.serializeAsVector3("target")
  42076. ], ArcRotateCamera.prototype, "_target", void 0);
  42077. __decorate([
  42078. BABYLON.serialize()
  42079. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42080. __decorate([
  42081. BABYLON.serialize()
  42082. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42083. __decorate([
  42084. BABYLON.serialize()
  42085. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42086. __decorate([
  42087. BABYLON.serialize()
  42088. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42089. __decorate([
  42090. BABYLON.serialize()
  42091. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42092. __decorate([
  42093. BABYLON.serialize()
  42094. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42095. __decorate([
  42096. BABYLON.serialize()
  42097. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42098. __decorate([
  42099. BABYLON.serialize()
  42100. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42101. __decorate([
  42102. BABYLON.serialize()
  42103. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42104. __decorate([
  42105. BABYLON.serialize()
  42106. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42107. __decorate([
  42108. BABYLON.serialize()
  42109. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42110. __decorate([
  42111. BABYLON.serialize()
  42112. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42113. __decorate([
  42114. BABYLON.serialize()
  42115. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42116. __decorate([
  42117. BABYLON.serializeAsVector3()
  42118. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42119. __decorate([
  42120. BABYLON.serialize()
  42121. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42122. __decorate([
  42123. BABYLON.serialize()
  42124. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42125. __decorate([
  42126. BABYLON.serialize()
  42127. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42128. return ArcRotateCamera;
  42129. }(BABYLON.TargetCamera));
  42130. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42131. })(BABYLON || (BABYLON = {}));
  42132. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42133. var BABYLON;
  42134. (function (BABYLON) {
  42135. var HemisphericLight = /** @class */ (function (_super) {
  42136. __extends(HemisphericLight, _super);
  42137. /**
  42138. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42139. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42140. * The HemisphericLight can't cast shadows.
  42141. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42142. */
  42143. function HemisphericLight(name, direction, scene) {
  42144. var _this = _super.call(this, name, scene) || this;
  42145. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42146. _this.direction = direction || BABYLON.Vector3.Up();
  42147. return _this;
  42148. }
  42149. HemisphericLight.prototype._buildUniformLayout = function () {
  42150. this._uniformBuffer.addUniform("vLightData", 4);
  42151. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42152. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42153. this._uniformBuffer.addUniform("vLightGround", 3);
  42154. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42155. this._uniformBuffer.addUniform("depthValues", 2);
  42156. this._uniformBuffer.create();
  42157. };
  42158. /**
  42159. * Returns the string "HemisphericLight".
  42160. */
  42161. HemisphericLight.prototype.getClassName = function () {
  42162. return "HemisphericLight";
  42163. };
  42164. /**
  42165. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42166. * Returns the updated direction.
  42167. */
  42168. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42169. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42170. return this.direction;
  42171. };
  42172. HemisphericLight.prototype.getShadowGenerator = function () {
  42173. return null;
  42174. };
  42175. /**
  42176. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42177. * Returns the HemisphericLight.
  42178. */
  42179. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42180. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42181. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42182. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42183. return this;
  42184. };
  42185. HemisphericLight.prototype._getWorldMatrix = function () {
  42186. if (!this._worldMatrix) {
  42187. this._worldMatrix = BABYLON.Matrix.Identity();
  42188. }
  42189. return this._worldMatrix;
  42190. };
  42191. /**
  42192. * Returns the integer 3.
  42193. */
  42194. HemisphericLight.prototype.getTypeID = function () {
  42195. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42196. };
  42197. __decorate([
  42198. BABYLON.serializeAsColor3()
  42199. ], HemisphericLight.prototype, "groundColor", void 0);
  42200. __decorate([
  42201. BABYLON.serializeAsVector3()
  42202. ], HemisphericLight.prototype, "direction", void 0);
  42203. return HemisphericLight;
  42204. }(BABYLON.Light));
  42205. BABYLON.HemisphericLight = HemisphericLight;
  42206. })(BABYLON || (BABYLON = {}));
  42207. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42208. var BABYLON;
  42209. (function (BABYLON) {
  42210. var ShadowLight = /** @class */ (function (_super) {
  42211. __extends(ShadowLight, _super);
  42212. function ShadowLight() {
  42213. var _this = _super !== null && _super.apply(this, arguments) || this;
  42214. _this._needProjectionMatrixCompute = true;
  42215. return _this;
  42216. }
  42217. Object.defineProperty(ShadowLight.prototype, "direction", {
  42218. get: function () {
  42219. return this._direction;
  42220. },
  42221. set: function (value) {
  42222. this._direction = value;
  42223. },
  42224. enumerable: true,
  42225. configurable: true
  42226. });
  42227. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42228. get: function () {
  42229. return this._shadowMinZ;
  42230. },
  42231. set: function (value) {
  42232. this._shadowMinZ = value;
  42233. this.forceProjectionMatrixCompute();
  42234. },
  42235. enumerable: true,
  42236. configurable: true
  42237. });
  42238. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42239. get: function () {
  42240. return this._shadowMaxZ;
  42241. },
  42242. set: function (value) {
  42243. this._shadowMaxZ = value;
  42244. this.forceProjectionMatrixCompute();
  42245. },
  42246. enumerable: true,
  42247. configurable: true
  42248. });
  42249. /**
  42250. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  42251. */
  42252. ShadowLight.prototype.computeTransformedInformation = function () {
  42253. if (this.parent && this.parent.getWorldMatrix) {
  42254. if (!this.transformedPosition) {
  42255. this.transformedPosition = BABYLON.Vector3.Zero();
  42256. }
  42257. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42258. // In case the direction is present.
  42259. if (this.direction) {
  42260. if (!this.transformedDirection) {
  42261. this.transformedDirection = BABYLON.Vector3.Zero();
  42262. }
  42263. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42264. }
  42265. return true;
  42266. }
  42267. return false;
  42268. };
  42269. /**
  42270. * Return the depth scale used for the shadow map.
  42271. */
  42272. ShadowLight.prototype.getDepthScale = function () {
  42273. return 50.0;
  42274. };
  42275. /**
  42276. * Returns the light direction (Vector3) for any passed face index.
  42277. */
  42278. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  42279. return this.transformedDirection ? this.transformedDirection : this.direction;
  42280. };
  42281. /**
  42282. * Returns the ShadowLight absolute position in the World.
  42283. */
  42284. ShadowLight.prototype.getAbsolutePosition = function () {
  42285. return this.transformedPosition ? this.transformedPosition : this.position;
  42286. };
  42287. /**
  42288. * Sets the ShadowLight direction toward the passed target (Vector3).
  42289. * Returns the updated ShadowLight direction (Vector3).
  42290. */
  42291. ShadowLight.prototype.setDirectionToTarget = function (target) {
  42292. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  42293. return this.direction;
  42294. };
  42295. /**
  42296. * Returns the light rotation (Vector3).
  42297. */
  42298. ShadowLight.prototype.getRotation = function () {
  42299. this.direction.normalize();
  42300. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  42301. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  42302. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  42303. };
  42304. /**
  42305. * Boolean : false by default.
  42306. */
  42307. ShadowLight.prototype.needCube = function () {
  42308. return false;
  42309. };
  42310. /**
  42311. * Specifies wether or not the projection matrix should be recomputed this frame.
  42312. */
  42313. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  42314. return this._needProjectionMatrixCompute;
  42315. };
  42316. /**
  42317. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  42318. */
  42319. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  42320. this._needProjectionMatrixCompute = true;
  42321. };
  42322. /**
  42323. * Get the world matrix of the sahdow lights.
  42324. */
  42325. ShadowLight.prototype._getWorldMatrix = function () {
  42326. if (!this._worldMatrix) {
  42327. this._worldMatrix = BABYLON.Matrix.Identity();
  42328. }
  42329. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  42330. return this._worldMatrix;
  42331. };
  42332. /**
  42333. * Gets the minZ used for shadow according to both the scene and the light.
  42334. * @param activeCamera
  42335. */
  42336. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  42337. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  42338. };
  42339. /**
  42340. * Gets the maxZ used for shadow according to both the scene and the light.
  42341. * @param activeCamera
  42342. */
  42343. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  42344. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  42345. };
  42346. /**
  42347. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  42348. * Returns the light.
  42349. */
  42350. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42351. if (this.customProjectionMatrixBuilder) {
  42352. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  42353. }
  42354. else {
  42355. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42356. }
  42357. return this;
  42358. };
  42359. __decorate([
  42360. BABYLON.serializeAsVector3()
  42361. ], ShadowLight.prototype, "position", void 0);
  42362. __decorate([
  42363. BABYLON.serializeAsVector3()
  42364. ], ShadowLight.prototype, "direction", null);
  42365. __decorate([
  42366. BABYLON.serialize()
  42367. ], ShadowLight.prototype, "shadowMinZ", null);
  42368. __decorate([
  42369. BABYLON.serialize()
  42370. ], ShadowLight.prototype, "shadowMaxZ", null);
  42371. return ShadowLight;
  42372. }(BABYLON.Light));
  42373. BABYLON.ShadowLight = ShadowLight;
  42374. })(BABYLON || (BABYLON = {}));
  42375. //# sourceMappingURL=babylon.shadowLight.js.map
  42376. var BABYLON;
  42377. (function (BABYLON) {
  42378. var PointLight = /** @class */ (function (_super) {
  42379. __extends(PointLight, _super);
  42380. /**
  42381. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  42382. * A PointLight emits the light in every direction.
  42383. * It can cast shadows.
  42384. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  42385. * ```javascript
  42386. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  42387. * ```
  42388. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42389. */
  42390. function PointLight(name, position, scene) {
  42391. var _this = _super.call(this, name, scene) || this;
  42392. _this._shadowAngle = Math.PI / 2;
  42393. _this.position = position;
  42394. return _this;
  42395. }
  42396. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  42397. /**
  42398. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42399. * This specifies what angle the shadow will use to be created.
  42400. *
  42401. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42402. */
  42403. get: function () {
  42404. return this._shadowAngle;
  42405. },
  42406. /**
  42407. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42408. * This specifies what angle the shadow will use to be created.
  42409. *
  42410. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42411. */
  42412. set: function (value) {
  42413. this._shadowAngle = value;
  42414. this.forceProjectionMatrixCompute();
  42415. },
  42416. enumerable: true,
  42417. configurable: true
  42418. });
  42419. Object.defineProperty(PointLight.prototype, "direction", {
  42420. get: function () {
  42421. return this._direction;
  42422. },
  42423. /**
  42424. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42425. */
  42426. set: function (value) {
  42427. var previousNeedCube = this.needCube();
  42428. this._direction = value;
  42429. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  42430. this._shadowGenerator.recreateShadowMap();
  42431. }
  42432. },
  42433. enumerable: true,
  42434. configurable: true
  42435. });
  42436. /**
  42437. * Returns the string "PointLight"
  42438. */
  42439. PointLight.prototype.getClassName = function () {
  42440. return "PointLight";
  42441. };
  42442. /**
  42443. * Returns the integer 0.
  42444. */
  42445. PointLight.prototype.getTypeID = function () {
  42446. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  42447. };
  42448. /**
  42449. * Specifies wether or not the shadowmap should be a cube texture.
  42450. */
  42451. PointLight.prototype.needCube = function () {
  42452. return !this.direction;
  42453. };
  42454. /**
  42455. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  42456. */
  42457. PointLight.prototype.getShadowDirection = function (faceIndex) {
  42458. if (this.direction) {
  42459. return _super.prototype.getShadowDirection.call(this, faceIndex);
  42460. }
  42461. else {
  42462. switch (faceIndex) {
  42463. case 0:
  42464. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  42465. case 1:
  42466. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  42467. case 2:
  42468. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  42469. case 3:
  42470. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  42471. case 4:
  42472. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  42473. case 5:
  42474. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  42475. }
  42476. }
  42477. return BABYLON.Vector3.Zero();
  42478. };
  42479. /**
  42480. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  42481. * - fov = PI / 2
  42482. * - aspect ratio : 1.0
  42483. * - z-near and far equal to the active camera minZ and maxZ.
  42484. * Returns the PointLight.
  42485. */
  42486. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42487. var activeCamera = this.getScene().activeCamera;
  42488. if (!activeCamera) {
  42489. return;
  42490. }
  42491. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42492. };
  42493. PointLight.prototype._buildUniformLayout = function () {
  42494. this._uniformBuffer.addUniform("vLightData", 4);
  42495. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42496. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42497. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42498. this._uniformBuffer.addUniform("depthValues", 2);
  42499. this._uniformBuffer.create();
  42500. };
  42501. /**
  42502. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  42503. * Returns the PointLight.
  42504. */
  42505. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  42506. if (this.computeTransformedInformation()) {
  42507. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  42508. return this;
  42509. }
  42510. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  42511. return this;
  42512. };
  42513. __decorate([
  42514. BABYLON.serialize()
  42515. ], PointLight.prototype, "shadowAngle", null);
  42516. return PointLight;
  42517. }(BABYLON.ShadowLight));
  42518. BABYLON.PointLight = PointLight;
  42519. })(BABYLON || (BABYLON = {}));
  42520. //# sourceMappingURL=babylon.pointLight.js.map
  42521. var BABYLON;
  42522. (function (BABYLON) {
  42523. var DirectionalLight = /** @class */ (function (_super) {
  42524. __extends(DirectionalLight, _super);
  42525. /**
  42526. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  42527. * The directional light is emitted from everywhere in the given direction.
  42528. * It can cast shawdows.
  42529. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42530. */
  42531. function DirectionalLight(name, direction, scene) {
  42532. var _this = _super.call(this, name, scene) || this;
  42533. _this._shadowFrustumSize = 0;
  42534. _this._shadowOrthoScale = 0.5;
  42535. _this.autoUpdateExtends = true;
  42536. // Cache
  42537. _this._orthoLeft = Number.MAX_VALUE;
  42538. _this._orthoRight = Number.MIN_VALUE;
  42539. _this._orthoTop = Number.MIN_VALUE;
  42540. _this._orthoBottom = Number.MAX_VALUE;
  42541. _this.position = direction.scale(-1.0);
  42542. _this.direction = direction;
  42543. return _this;
  42544. }
  42545. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  42546. /**
  42547. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  42548. */
  42549. get: function () {
  42550. return this._shadowFrustumSize;
  42551. },
  42552. /**
  42553. * Specifies a fix frustum size for the shadow generation.
  42554. */
  42555. set: function (value) {
  42556. this._shadowFrustumSize = value;
  42557. this.forceProjectionMatrixCompute();
  42558. },
  42559. enumerable: true,
  42560. configurable: true
  42561. });
  42562. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  42563. get: function () {
  42564. return this._shadowOrthoScale;
  42565. },
  42566. set: function (value) {
  42567. this._shadowOrthoScale = value;
  42568. this.forceProjectionMatrixCompute();
  42569. },
  42570. enumerable: true,
  42571. configurable: true
  42572. });
  42573. /**
  42574. * Returns the string "DirectionalLight".
  42575. */
  42576. DirectionalLight.prototype.getClassName = function () {
  42577. return "DirectionalLight";
  42578. };
  42579. /**
  42580. * Returns the integer 1.
  42581. */
  42582. DirectionalLight.prototype.getTypeID = function () {
  42583. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  42584. };
  42585. /**
  42586. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  42587. * Returns the DirectionalLight Shadow projection matrix.
  42588. */
  42589. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42590. if (this.shadowFrustumSize > 0) {
  42591. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  42592. }
  42593. else {
  42594. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42595. }
  42596. };
  42597. /**
  42598. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  42599. * Returns the DirectionalLight Shadow projection matrix.
  42600. */
  42601. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  42602. var activeCamera = this.getScene().activeCamera;
  42603. if (!activeCamera) {
  42604. return;
  42605. }
  42606. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  42607. };
  42608. /**
  42609. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  42610. * Returns the DirectionalLight Shadow projection matrix.
  42611. */
  42612. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42613. var activeCamera = this.getScene().activeCamera;
  42614. if (!activeCamera) {
  42615. return;
  42616. }
  42617. // Check extends
  42618. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  42619. var tempVector3 = BABYLON.Vector3.Zero();
  42620. this._orthoLeft = Number.MAX_VALUE;
  42621. this._orthoRight = Number.MIN_VALUE;
  42622. this._orthoTop = Number.MIN_VALUE;
  42623. this._orthoBottom = Number.MAX_VALUE;
  42624. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  42625. var mesh = renderList[meshIndex];
  42626. if (!mesh) {
  42627. continue;
  42628. }
  42629. var boundingInfo = mesh.getBoundingInfo();
  42630. var boundingBox = boundingInfo.boundingBox;
  42631. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  42632. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  42633. if (tempVector3.x < this._orthoLeft)
  42634. this._orthoLeft = tempVector3.x;
  42635. if (tempVector3.y < this._orthoBottom)
  42636. this._orthoBottom = tempVector3.y;
  42637. if (tempVector3.x > this._orthoRight)
  42638. this._orthoRight = tempVector3.x;
  42639. if (tempVector3.y > this._orthoTop)
  42640. this._orthoTop = tempVector3.y;
  42641. }
  42642. }
  42643. }
  42644. var xOffset = this._orthoRight - this._orthoLeft;
  42645. var yOffset = this._orthoTop - this._orthoBottom;
  42646. 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);
  42647. };
  42648. DirectionalLight.prototype._buildUniformLayout = function () {
  42649. this._uniformBuffer.addUniform("vLightData", 4);
  42650. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42651. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42652. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42653. this._uniformBuffer.addUniform("depthValues", 2);
  42654. this._uniformBuffer.create();
  42655. };
  42656. /**
  42657. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  42658. * Returns the DirectionalLight.
  42659. */
  42660. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  42661. if (this.computeTransformedInformation()) {
  42662. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  42663. return this;
  42664. }
  42665. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  42666. return this;
  42667. };
  42668. /**
  42669. * Gets the minZ used for shadow according to both the scene and the light.
  42670. *
  42671. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42672. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42673. * @param activeCamera
  42674. */
  42675. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  42676. return 1;
  42677. };
  42678. /**
  42679. * Gets the maxZ used for shadow according to both the scene and the light.
  42680. *
  42681. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42682. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42683. * @param activeCamera
  42684. */
  42685. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  42686. return 1;
  42687. };
  42688. __decorate([
  42689. BABYLON.serialize()
  42690. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  42691. __decorate([
  42692. BABYLON.serialize()
  42693. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  42694. __decorate([
  42695. BABYLON.serialize()
  42696. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  42697. return DirectionalLight;
  42698. }(BABYLON.ShadowLight));
  42699. BABYLON.DirectionalLight = DirectionalLight;
  42700. })(BABYLON || (BABYLON = {}));
  42701. //# sourceMappingURL=babylon.directionalLight.js.map
  42702. var BABYLON;
  42703. (function (BABYLON) {
  42704. var SpotLight = /** @class */ (function (_super) {
  42705. __extends(SpotLight, _super);
  42706. /**
  42707. * Creates a SpotLight object in the scene with the passed parameters :
  42708. * - `position` (Vector3) is the initial SpotLight position,
  42709. * - `direction` (Vector3) is the initial SpotLight direction,
  42710. * - `angle` (float, in radians) is the spot light cone angle,
  42711. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  42712. * A spot light is a simply light oriented cone.
  42713. * It can cast shadows.
  42714. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42715. */
  42716. function SpotLight(name, position, direction, angle, exponent, scene) {
  42717. var _this = _super.call(this, name, scene) || this;
  42718. _this.position = position;
  42719. _this.direction = direction;
  42720. _this.angle = angle;
  42721. _this.exponent = exponent;
  42722. return _this;
  42723. }
  42724. Object.defineProperty(SpotLight.prototype, "angle", {
  42725. get: function () {
  42726. return this._angle;
  42727. },
  42728. set: function (value) {
  42729. this._angle = value;
  42730. this.forceProjectionMatrixCompute();
  42731. },
  42732. enumerable: true,
  42733. configurable: true
  42734. });
  42735. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  42736. get: function () {
  42737. return this._shadowAngleScale;
  42738. },
  42739. /**
  42740. * Allows scaling the angle of the light for shadow generation only.
  42741. */
  42742. set: function (value) {
  42743. this._shadowAngleScale = value;
  42744. this.forceProjectionMatrixCompute();
  42745. },
  42746. enumerable: true,
  42747. configurable: true
  42748. });
  42749. /**
  42750. * Returns the string "SpotLight".
  42751. */
  42752. SpotLight.prototype.getClassName = function () {
  42753. return "SpotLight";
  42754. };
  42755. /**
  42756. * Returns the integer 2.
  42757. */
  42758. SpotLight.prototype.getTypeID = function () {
  42759. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  42760. };
  42761. /**
  42762. * 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.
  42763. * Returns the SpotLight.
  42764. */
  42765. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42766. var activeCamera = this.getScene().activeCamera;
  42767. if (!activeCamera) {
  42768. return;
  42769. }
  42770. this._shadowAngleScale = this._shadowAngleScale || 1;
  42771. var angle = this._shadowAngleScale * this._angle;
  42772. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42773. };
  42774. SpotLight.prototype._buildUniformLayout = function () {
  42775. this._uniformBuffer.addUniform("vLightData", 4);
  42776. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42777. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42778. this._uniformBuffer.addUniform("vLightDirection", 3);
  42779. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42780. this._uniformBuffer.addUniform("depthValues", 2);
  42781. this._uniformBuffer.create();
  42782. };
  42783. /**
  42784. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  42785. * Return the SpotLight.
  42786. */
  42787. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  42788. var normalizeDirection;
  42789. if (this.computeTransformedInformation()) {
  42790. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  42791. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  42792. }
  42793. else {
  42794. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  42795. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42796. }
  42797. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  42798. return this;
  42799. };
  42800. __decorate([
  42801. BABYLON.serialize()
  42802. ], SpotLight.prototype, "angle", null);
  42803. __decorate([
  42804. BABYLON.serialize()
  42805. /**
  42806. * Allows scaling the angle of the light for shadow generation only.
  42807. */
  42808. ], SpotLight.prototype, "shadowAngleScale", null);
  42809. __decorate([
  42810. BABYLON.serialize()
  42811. ], SpotLight.prototype, "exponent", void 0);
  42812. return SpotLight;
  42813. }(BABYLON.ShadowLight));
  42814. BABYLON.SpotLight = SpotLight;
  42815. })(BABYLON || (BABYLON = {}));
  42816. //# sourceMappingURL=babylon.spotLight.js.map
  42817. var BABYLON;
  42818. (function (BABYLON) {
  42819. var AnimationRange = /** @class */ (function () {
  42820. function AnimationRange(name, from, to) {
  42821. this.name = name;
  42822. this.from = from;
  42823. this.to = to;
  42824. }
  42825. AnimationRange.prototype.clone = function () {
  42826. return new AnimationRange(this.name, this.from, this.to);
  42827. };
  42828. return AnimationRange;
  42829. }());
  42830. BABYLON.AnimationRange = AnimationRange;
  42831. /**
  42832. * Composed of a frame, and an action function
  42833. */
  42834. var AnimationEvent = /** @class */ (function () {
  42835. function AnimationEvent(frame, action, onlyOnce) {
  42836. this.frame = frame;
  42837. this.action = action;
  42838. this.onlyOnce = onlyOnce;
  42839. this.isDone = false;
  42840. }
  42841. return AnimationEvent;
  42842. }());
  42843. BABYLON.AnimationEvent = AnimationEvent;
  42844. var PathCursor = /** @class */ (function () {
  42845. function PathCursor(path) {
  42846. this.path = path;
  42847. this._onchange = new Array();
  42848. this.value = 0;
  42849. this.animations = new Array();
  42850. }
  42851. PathCursor.prototype.getPoint = function () {
  42852. var point = this.path.getPointAtLengthPosition(this.value);
  42853. return new BABYLON.Vector3(point.x, 0, point.y);
  42854. };
  42855. PathCursor.prototype.moveAhead = function (step) {
  42856. if (step === void 0) { step = 0.002; }
  42857. this.move(step);
  42858. return this;
  42859. };
  42860. PathCursor.prototype.moveBack = function (step) {
  42861. if (step === void 0) { step = 0.002; }
  42862. this.move(-step);
  42863. return this;
  42864. };
  42865. PathCursor.prototype.move = function (step) {
  42866. if (Math.abs(step) > 1) {
  42867. throw "step size should be less than 1.";
  42868. }
  42869. this.value += step;
  42870. this.ensureLimits();
  42871. this.raiseOnChange();
  42872. return this;
  42873. };
  42874. PathCursor.prototype.ensureLimits = function () {
  42875. while (this.value > 1) {
  42876. this.value -= 1;
  42877. }
  42878. while (this.value < 0) {
  42879. this.value += 1;
  42880. }
  42881. return this;
  42882. };
  42883. // used by animation engine
  42884. PathCursor.prototype.raiseOnChange = function () {
  42885. var _this = this;
  42886. this._onchange.forEach(function (f) { return f(_this); });
  42887. return this;
  42888. };
  42889. PathCursor.prototype.onchange = function (f) {
  42890. this._onchange.push(f);
  42891. return this;
  42892. };
  42893. return PathCursor;
  42894. }());
  42895. BABYLON.PathCursor = PathCursor;
  42896. var AnimationKeyInterpolation;
  42897. (function (AnimationKeyInterpolation) {
  42898. /**
  42899. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  42900. */
  42901. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  42902. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  42903. var Animation = /** @class */ (function () {
  42904. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  42905. this.name = name;
  42906. this.targetProperty = targetProperty;
  42907. this.framePerSecond = framePerSecond;
  42908. this.dataType = dataType;
  42909. this.loopMode = loopMode;
  42910. this.enableBlending = enableBlending;
  42911. this._runtimeAnimations = new Array();
  42912. // The set of event that will be linked to this animation
  42913. this._events = new Array();
  42914. this.blendingSpeed = 0.01;
  42915. this._ranges = {};
  42916. this.targetPropertyPath = targetProperty.split(".");
  42917. this.dataType = dataType;
  42918. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  42919. }
  42920. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  42921. var dataType = undefined;
  42922. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  42923. dataType = Animation.ANIMATIONTYPE_FLOAT;
  42924. }
  42925. else if (from instanceof BABYLON.Quaternion) {
  42926. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  42927. }
  42928. else if (from instanceof BABYLON.Vector3) {
  42929. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  42930. }
  42931. else if (from instanceof BABYLON.Vector2) {
  42932. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  42933. }
  42934. else if (from instanceof BABYLON.Color3) {
  42935. dataType = Animation.ANIMATIONTYPE_COLOR3;
  42936. }
  42937. else if (from instanceof BABYLON.Size) {
  42938. dataType = Animation.ANIMATIONTYPE_SIZE;
  42939. }
  42940. if (dataType == undefined) {
  42941. return null;
  42942. }
  42943. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  42944. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  42945. animation.setKeys(keys);
  42946. if (easingFunction !== undefined) {
  42947. animation.setEasingFunction(easingFunction);
  42948. }
  42949. return animation;
  42950. };
  42951. /**
  42952. * Sets up an animation.
  42953. * @param property the property to animate
  42954. * @param animationType the animation type to apply
  42955. * @param easingFunction the easing function used in the animation
  42956. * @returns The created animation
  42957. */
  42958. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  42959. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  42960. animation.setEasingFunction(easingFunction);
  42961. return animation;
  42962. };
  42963. /**
  42964. * Create and start an animation on a node
  42965. * @param {string} name defines the name of the global animation that will be run on all nodes
  42966. * @param {BABYLON.Node} node defines the root node where the animation will take place
  42967. * @param {string} targetProperty defines property to animate
  42968. * @param {number} framePerSecond defines the number of frame per second yo use
  42969. * @param {number} totalFrame defines the number of frames in total
  42970. * @param {any} from defines the initial value
  42971. * @param {any} to defines the final value
  42972. * @param {number} loopMode defines which loop mode you want to use (off by default)
  42973. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  42974. * @param onAnimationEnd defines the callback to call when animation end
  42975. * @returns the animatable created for this animation
  42976. */
  42977. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  42978. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  42979. if (!animation) {
  42980. return null;
  42981. }
  42982. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  42983. };
  42984. /**
  42985. * Create and start an animation on a node and its descendants
  42986. * @param {string} name defines the name of the global animation that will be run on all nodes
  42987. * @param {BABYLON.Node} node defines the root node where the animation will take place
  42988. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  42989. * @param {string} targetProperty defines property to animate
  42990. * @param {number} framePerSecond defines the number of frame per second yo use
  42991. * @param {number} totalFrame defines the number of frames in total
  42992. * @param {any} from defines the initial value
  42993. * @param {any} to defines the final value
  42994. * @param {number} loopMode defines which loop mode you want to use (off by default)
  42995. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  42996. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  42997. * @returns the list of animatables created for all nodes
  42998. * @example https://www.babylonjs-playground.com/#MH0VLI
  42999. */
  43000. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43001. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43002. if (!animation) {
  43003. return null;
  43004. }
  43005. var scene = node.getScene();
  43006. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43007. };
  43008. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43009. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43010. if (!animation) {
  43011. return null;
  43012. }
  43013. node.animations.push(animation);
  43014. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43015. };
  43016. /**
  43017. * Transition property of the Camera to the target Value.
  43018. * @param property The property to transition
  43019. * @param targetValue The target Value of the property
  43020. * @param host The object where the property to animate belongs
  43021. * @param scene Scene used to run the animation
  43022. * @param frameRate Framerate (in frame/s) to use
  43023. * @param transition The transition type we want to use
  43024. * @param duration The duration of the animation, in milliseconds
  43025. * @param onAnimationEnd Call back trigger at the end of the animation.
  43026. */
  43027. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  43028. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  43029. if (duration <= 0) {
  43030. host[property] = targetValue;
  43031. if (onAnimationEnd) {
  43032. onAnimationEnd();
  43033. }
  43034. return null;
  43035. }
  43036. var endFrame = frameRate * (duration / 1000);
  43037. transition.setKeys([{
  43038. frame: 0,
  43039. value: host[property].clone ? host[property].clone() : host[property]
  43040. },
  43041. {
  43042. frame: endFrame,
  43043. value: targetValue
  43044. }]);
  43045. if (!host.animations) {
  43046. host.animations = [];
  43047. }
  43048. host.animations.push(transition);
  43049. var animation = scene.beginAnimation(host, 0, endFrame, false);
  43050. animation.onAnimationEnd = onAnimationEnd;
  43051. return animation;
  43052. };
  43053. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  43054. /**
  43055. * Return the array of runtime animations currently using this animation
  43056. */
  43057. get: function () {
  43058. return this._runtimeAnimations;
  43059. },
  43060. enumerable: true,
  43061. configurable: true
  43062. });
  43063. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  43064. get: function () {
  43065. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  43066. var runtimeAnimation = _a[_i];
  43067. if (!runtimeAnimation.isStopped) {
  43068. return true;
  43069. }
  43070. }
  43071. return false;
  43072. },
  43073. enumerable: true,
  43074. configurable: true
  43075. });
  43076. // Methods
  43077. /**
  43078. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  43079. */
  43080. Animation.prototype.toString = function (fullDetails) {
  43081. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  43082. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  43083. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  43084. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  43085. if (fullDetails) {
  43086. ret += ", Ranges: {";
  43087. var first = true;
  43088. for (var name in this._ranges) {
  43089. if (first) {
  43090. ret += ", ";
  43091. first = false;
  43092. }
  43093. ret += name;
  43094. }
  43095. ret += "}";
  43096. }
  43097. return ret;
  43098. };
  43099. /**
  43100. * Add an event to this animation.
  43101. */
  43102. Animation.prototype.addEvent = function (event) {
  43103. this._events.push(event);
  43104. };
  43105. /**
  43106. * Remove all events found at the given frame
  43107. * @param frame
  43108. */
  43109. Animation.prototype.removeEvents = function (frame) {
  43110. for (var index = 0; index < this._events.length; index++) {
  43111. if (this._events[index].frame === frame) {
  43112. this._events.splice(index, 1);
  43113. index--;
  43114. }
  43115. }
  43116. };
  43117. Animation.prototype.getEvents = function () {
  43118. return this._events;
  43119. };
  43120. Animation.prototype.createRange = function (name, from, to) {
  43121. // check name not already in use; could happen for bones after serialized
  43122. if (!this._ranges[name]) {
  43123. this._ranges[name] = new AnimationRange(name, from, to);
  43124. }
  43125. };
  43126. Animation.prototype.deleteRange = function (name, deleteFrames) {
  43127. if (deleteFrames === void 0) { deleteFrames = true; }
  43128. var range = this._ranges[name];
  43129. if (!range) {
  43130. return;
  43131. }
  43132. if (deleteFrames) {
  43133. var from = range.from;
  43134. var to = range.to;
  43135. // this loop MUST go high to low for multiple splices to work
  43136. for (var key = this._keys.length - 1; key >= 0; key--) {
  43137. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  43138. this._keys.splice(key, 1);
  43139. }
  43140. }
  43141. }
  43142. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  43143. };
  43144. Animation.prototype.getRange = function (name) {
  43145. return this._ranges[name];
  43146. };
  43147. Animation.prototype.getKeys = function () {
  43148. return this._keys;
  43149. };
  43150. Animation.prototype.getHighestFrame = function () {
  43151. var ret = 0;
  43152. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  43153. if (ret < this._keys[key].frame) {
  43154. ret = this._keys[key].frame;
  43155. }
  43156. }
  43157. return ret;
  43158. };
  43159. Animation.prototype.getEasingFunction = function () {
  43160. return this._easingFunction;
  43161. };
  43162. Animation.prototype.setEasingFunction = function (easingFunction) {
  43163. this._easingFunction = easingFunction;
  43164. };
  43165. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  43166. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  43167. };
  43168. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43169. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43170. };
  43171. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  43172. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  43173. };
  43174. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43175. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  43176. };
  43177. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  43178. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  43179. };
  43180. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43181. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43182. };
  43183. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  43184. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  43185. };
  43186. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43187. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43188. };
  43189. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  43190. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  43191. };
  43192. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  43193. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  43194. };
  43195. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  43196. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  43197. };
  43198. Animation.prototype.clone = function () {
  43199. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  43200. clone.enableBlending = this.enableBlending;
  43201. clone.blendingSpeed = this.blendingSpeed;
  43202. if (this._keys) {
  43203. clone.setKeys(this._keys);
  43204. }
  43205. if (this._ranges) {
  43206. clone._ranges = {};
  43207. for (var name in this._ranges) {
  43208. var range = this._ranges[name];
  43209. if (!range) {
  43210. continue;
  43211. }
  43212. clone._ranges[name] = range.clone();
  43213. }
  43214. }
  43215. return clone;
  43216. };
  43217. Animation.prototype.setKeys = function (values) {
  43218. this._keys = values.slice(0);
  43219. };
  43220. Animation.prototype.serialize = function () {
  43221. var serializationObject = {};
  43222. serializationObject.name = this.name;
  43223. serializationObject.property = this.targetProperty;
  43224. serializationObject.framePerSecond = this.framePerSecond;
  43225. serializationObject.dataType = this.dataType;
  43226. serializationObject.loopBehavior = this.loopMode;
  43227. serializationObject.enableBlending = this.enableBlending;
  43228. serializationObject.blendingSpeed = this.blendingSpeed;
  43229. var dataType = this.dataType;
  43230. serializationObject.keys = [];
  43231. var keys = this.getKeys();
  43232. for (var index = 0; index < keys.length; index++) {
  43233. var animationKey = keys[index];
  43234. var key = {};
  43235. key.frame = animationKey.frame;
  43236. switch (dataType) {
  43237. case Animation.ANIMATIONTYPE_FLOAT:
  43238. key.values = [animationKey.value];
  43239. break;
  43240. case Animation.ANIMATIONTYPE_QUATERNION:
  43241. case Animation.ANIMATIONTYPE_MATRIX:
  43242. case Animation.ANIMATIONTYPE_VECTOR3:
  43243. case Animation.ANIMATIONTYPE_COLOR3:
  43244. key.values = animationKey.value.asArray();
  43245. break;
  43246. }
  43247. serializationObject.keys.push(key);
  43248. }
  43249. serializationObject.ranges = [];
  43250. for (var name in this._ranges) {
  43251. var source = this._ranges[name];
  43252. if (!source) {
  43253. continue;
  43254. }
  43255. var range = {};
  43256. range.name = name;
  43257. range.from = source.from;
  43258. range.to = source.to;
  43259. serializationObject.ranges.push(range);
  43260. }
  43261. return serializationObject;
  43262. };
  43263. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  43264. get: function () {
  43265. return Animation._ANIMATIONTYPE_FLOAT;
  43266. },
  43267. enumerable: true,
  43268. configurable: true
  43269. });
  43270. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  43271. get: function () {
  43272. return Animation._ANIMATIONTYPE_VECTOR3;
  43273. },
  43274. enumerable: true,
  43275. configurable: true
  43276. });
  43277. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  43278. get: function () {
  43279. return Animation._ANIMATIONTYPE_VECTOR2;
  43280. },
  43281. enumerable: true,
  43282. configurable: true
  43283. });
  43284. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  43285. get: function () {
  43286. return Animation._ANIMATIONTYPE_SIZE;
  43287. },
  43288. enumerable: true,
  43289. configurable: true
  43290. });
  43291. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  43292. get: function () {
  43293. return Animation._ANIMATIONTYPE_QUATERNION;
  43294. },
  43295. enumerable: true,
  43296. configurable: true
  43297. });
  43298. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  43299. get: function () {
  43300. return Animation._ANIMATIONTYPE_MATRIX;
  43301. },
  43302. enumerable: true,
  43303. configurable: true
  43304. });
  43305. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  43306. get: function () {
  43307. return Animation._ANIMATIONTYPE_COLOR3;
  43308. },
  43309. enumerable: true,
  43310. configurable: true
  43311. });
  43312. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  43313. get: function () {
  43314. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  43315. },
  43316. enumerable: true,
  43317. configurable: true
  43318. });
  43319. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  43320. get: function () {
  43321. return Animation._ANIMATIONLOOPMODE_CYCLE;
  43322. },
  43323. enumerable: true,
  43324. configurable: true
  43325. });
  43326. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  43327. get: function () {
  43328. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  43329. },
  43330. enumerable: true,
  43331. configurable: true
  43332. });
  43333. Animation.Parse = function (parsedAnimation) {
  43334. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  43335. var dataType = parsedAnimation.dataType;
  43336. var keys = [];
  43337. var data;
  43338. var index;
  43339. if (parsedAnimation.enableBlending) {
  43340. animation.enableBlending = parsedAnimation.enableBlending;
  43341. }
  43342. if (parsedAnimation.blendingSpeed) {
  43343. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  43344. }
  43345. for (index = 0; index < parsedAnimation.keys.length; index++) {
  43346. var key = parsedAnimation.keys[index];
  43347. var inTangent;
  43348. var outTangent;
  43349. switch (dataType) {
  43350. case Animation.ANIMATIONTYPE_FLOAT:
  43351. data = key.values[0];
  43352. if (key.values.length >= 1) {
  43353. inTangent = key.values[1];
  43354. }
  43355. if (key.values.length >= 2) {
  43356. outTangent = key.values[2];
  43357. }
  43358. break;
  43359. case Animation.ANIMATIONTYPE_QUATERNION:
  43360. data = BABYLON.Quaternion.FromArray(key.values);
  43361. if (key.values.length >= 8) {
  43362. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  43363. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  43364. inTangent = _inTangent;
  43365. }
  43366. }
  43367. if (key.values.length >= 12) {
  43368. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  43369. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  43370. outTangent = _outTangent;
  43371. }
  43372. }
  43373. break;
  43374. case Animation.ANIMATIONTYPE_MATRIX:
  43375. data = BABYLON.Matrix.FromArray(key.values);
  43376. break;
  43377. case Animation.ANIMATIONTYPE_COLOR3:
  43378. data = BABYLON.Color3.FromArray(key.values);
  43379. break;
  43380. case Animation.ANIMATIONTYPE_VECTOR3:
  43381. default:
  43382. data = BABYLON.Vector3.FromArray(key.values);
  43383. break;
  43384. }
  43385. var keyData = {};
  43386. keyData.frame = key.frame;
  43387. keyData.value = data;
  43388. if (inTangent != undefined) {
  43389. keyData.inTangent = inTangent;
  43390. }
  43391. if (outTangent != undefined) {
  43392. keyData.outTangent = outTangent;
  43393. }
  43394. keys.push(keyData);
  43395. }
  43396. animation.setKeys(keys);
  43397. if (parsedAnimation.ranges) {
  43398. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  43399. data = parsedAnimation.ranges[index];
  43400. animation.createRange(data.name, data.from, data.to);
  43401. }
  43402. }
  43403. return animation;
  43404. };
  43405. Animation.AppendSerializedAnimations = function (source, destination) {
  43406. if (source.animations) {
  43407. destination.animations = [];
  43408. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  43409. var animation = source.animations[animationIndex];
  43410. destination.animations.push(animation.serialize());
  43411. }
  43412. }
  43413. };
  43414. Animation.AllowMatricesInterpolation = false;
  43415. // Statics
  43416. Animation._ANIMATIONTYPE_FLOAT = 0;
  43417. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  43418. Animation._ANIMATIONTYPE_QUATERNION = 2;
  43419. Animation._ANIMATIONTYPE_MATRIX = 3;
  43420. Animation._ANIMATIONTYPE_COLOR3 = 4;
  43421. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  43422. Animation._ANIMATIONTYPE_SIZE = 6;
  43423. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  43424. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  43425. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  43426. return Animation;
  43427. }());
  43428. BABYLON.Animation = Animation;
  43429. })(BABYLON || (BABYLON = {}));
  43430. //# sourceMappingURL=babylon.animation.js.map
  43431. var BABYLON;
  43432. (function (BABYLON) {
  43433. /**
  43434. * This class defines the direct association between an animation and a target
  43435. */
  43436. var TargetedAnimation = /** @class */ (function () {
  43437. function TargetedAnimation() {
  43438. }
  43439. return TargetedAnimation;
  43440. }());
  43441. BABYLON.TargetedAnimation = TargetedAnimation;
  43442. /**
  43443. * Use this class to create coordinated animations on multiple targets
  43444. */
  43445. var AnimationGroup = /** @class */ (function () {
  43446. function AnimationGroup(name, scene) {
  43447. if (scene === void 0) { scene = null; }
  43448. this.name = name;
  43449. this._targetedAnimations = new Array();
  43450. this._animatables = new Array();
  43451. this._from = Number.MAX_VALUE;
  43452. this._to = -Number.MAX_VALUE;
  43453. this._speedRatio = 1;
  43454. this.onAnimationEndObservable = new BABYLON.Observable();
  43455. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43456. this._scene.animationGroups.push(this);
  43457. }
  43458. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  43459. /**
  43460. * Define if the animations are started
  43461. */
  43462. get: function () {
  43463. return this._isStarted;
  43464. },
  43465. enumerable: true,
  43466. configurable: true
  43467. });
  43468. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  43469. /**
  43470. * Gets or sets the speed ratio to use for all animations
  43471. */
  43472. get: function () {
  43473. return this._speedRatio;
  43474. },
  43475. /**
  43476. * Gets or sets the speed ratio to use for all animations
  43477. */
  43478. set: function (value) {
  43479. if (this._speedRatio === value) {
  43480. return;
  43481. }
  43482. this._speedRatio = value;
  43483. for (var index = 0; index < this._animatables.length; index++) {
  43484. var animatable = this._animatables[index];
  43485. animatable.speedRatio = this._speedRatio;
  43486. }
  43487. },
  43488. enumerable: true,
  43489. configurable: true
  43490. });
  43491. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  43492. /**
  43493. * Gets the targeted animations for this animation group
  43494. */
  43495. get: function () {
  43496. return this._targetedAnimations;
  43497. },
  43498. enumerable: true,
  43499. configurable: true
  43500. });
  43501. /**
  43502. * Add an animation (with its target) in the group
  43503. * @param animation defines the animation we want to add
  43504. * @param target defines the target of the animation
  43505. * @returns the {BABYLON.TargetedAnimation} object
  43506. */
  43507. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  43508. var targetedAnimation = {
  43509. animation: animation,
  43510. target: target
  43511. };
  43512. var keys = animation.getKeys();
  43513. if (this._from > keys[0].frame) {
  43514. this._from = keys[0].frame;
  43515. }
  43516. if (this._to < keys[keys.length - 1].frame) {
  43517. this._to = keys[keys.length - 1].frame;
  43518. }
  43519. this._targetedAnimations.push(targetedAnimation);
  43520. return targetedAnimation;
  43521. };
  43522. /**
  43523. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  43524. * It can add constant keys at begin or end
  43525. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  43526. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  43527. */
  43528. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  43529. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  43530. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  43531. beginFrame = Math.max(beginFrame, this._from);
  43532. endFrame = Math.min(endFrame, this._to);
  43533. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43534. var targetedAnimation = this._targetedAnimations[index];
  43535. var keys = targetedAnimation.animation.getKeys();
  43536. var startKey = keys[0];
  43537. var endKey = keys[keys.length - 1];
  43538. if (startKey.frame > beginFrame) {
  43539. var newKey = {
  43540. frame: beginFrame,
  43541. value: startKey.value,
  43542. inTangent: startKey.inTangent,
  43543. outTangent: startKey.outTangent,
  43544. interpolation: startKey.interpolation
  43545. };
  43546. keys.splice(0, 0, newKey);
  43547. }
  43548. if (endKey.frame < endFrame) {
  43549. var newKey = {
  43550. frame: endFrame,
  43551. value: endKey.value,
  43552. inTangent: endKey.outTangent,
  43553. outTangent: endKey.outTangent,
  43554. interpolation: endKey.interpolation
  43555. };
  43556. keys.push(newKey);
  43557. }
  43558. }
  43559. return this;
  43560. };
  43561. /**
  43562. * Start all animations on given targets
  43563. * @param loop defines if animations must loop
  43564. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  43565. */
  43566. AnimationGroup.prototype.start = function (loop, speedRatio) {
  43567. var _this = this;
  43568. if (loop === void 0) { loop = false; }
  43569. if (speedRatio === void 0) { speedRatio = 1; }
  43570. if (this._isStarted || this._targetedAnimations.length === 0) {
  43571. return this;
  43572. }
  43573. var _loop_1 = function () {
  43574. var targetedAnimation = this_1._targetedAnimations[index];
  43575. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  43576. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  43577. }));
  43578. };
  43579. var this_1 = this;
  43580. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43581. _loop_1();
  43582. }
  43583. this._speedRatio = speedRatio;
  43584. this._isStarted = true;
  43585. return this;
  43586. };
  43587. /**
  43588. * Pause all animations
  43589. */
  43590. AnimationGroup.prototype.pause = function () {
  43591. if (!this._isStarted) {
  43592. return this;
  43593. }
  43594. for (var index = 0; index < this._animatables.length; index++) {
  43595. var animatable = this._animatables[index];
  43596. animatable.pause();
  43597. }
  43598. return this;
  43599. };
  43600. /**
  43601. * Play all animations to initial state
  43602. * This function will start() the animations if they were not started or will restart() them if they were paused
  43603. * @param loop defines if animations must loop
  43604. */
  43605. AnimationGroup.prototype.play = function (loop) {
  43606. if (this.isStarted) {
  43607. if (loop !== undefined) {
  43608. for (var index = 0; index < this._animatables.length; index++) {
  43609. var animatable = this._animatables[index];
  43610. animatable.loopAnimation = loop;
  43611. }
  43612. }
  43613. this.restart();
  43614. }
  43615. else {
  43616. this.start(loop, this._speedRatio);
  43617. }
  43618. return this;
  43619. };
  43620. /**
  43621. * Reset all animations to initial state
  43622. */
  43623. AnimationGroup.prototype.reset = function () {
  43624. if (!this._isStarted) {
  43625. return this;
  43626. }
  43627. for (var index = 0; index < this._animatables.length; index++) {
  43628. var animatable = this._animatables[index];
  43629. animatable.reset();
  43630. }
  43631. return this;
  43632. };
  43633. /**
  43634. * Restart animations from key 0
  43635. */
  43636. AnimationGroup.prototype.restart = function () {
  43637. if (!this._isStarted) {
  43638. return this;
  43639. }
  43640. for (var index = 0; index < this._animatables.length; index++) {
  43641. var animatable = this._animatables[index];
  43642. animatable.restart();
  43643. }
  43644. return this;
  43645. };
  43646. /**
  43647. * Stop all animations
  43648. */
  43649. AnimationGroup.prototype.stop = function () {
  43650. if (!this._isStarted) {
  43651. return this;
  43652. }
  43653. for (var index = 0; index < this._animatables.length; index++) {
  43654. var animatable = this._animatables[index];
  43655. animatable.stop();
  43656. }
  43657. this._isStarted = false;
  43658. return this;
  43659. };
  43660. /**
  43661. * Dispose all associated resources
  43662. */
  43663. AnimationGroup.prototype.dispose = function () {
  43664. this._targetedAnimations = [];
  43665. this._animatables = [];
  43666. var index = this._scene.animationGroups.indexOf(this);
  43667. if (index > -1) {
  43668. this._scene.animationGroups.splice(index, 1);
  43669. }
  43670. };
  43671. return AnimationGroup;
  43672. }());
  43673. BABYLON.AnimationGroup = AnimationGroup;
  43674. })(BABYLON || (BABYLON = {}));
  43675. //# sourceMappingURL=babylon.animationGroup.js.map
  43676. var BABYLON;
  43677. (function (BABYLON) {
  43678. var RuntimeAnimation = /** @class */ (function () {
  43679. function RuntimeAnimation(target, animation) {
  43680. this._offsetsCache = {};
  43681. this._highLimitsCache = {};
  43682. this._stopped = false;
  43683. this._blendingFactor = 0;
  43684. this._ratioOffset = 0;
  43685. this._animation = animation;
  43686. this._target = target;
  43687. animation._runtimeAnimations.push(this);
  43688. }
  43689. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  43690. get: function () {
  43691. return this._animation;
  43692. },
  43693. enumerable: true,
  43694. configurable: true
  43695. });
  43696. RuntimeAnimation.prototype.reset = function () {
  43697. this._offsetsCache = {};
  43698. this._highLimitsCache = {};
  43699. this.currentFrame = 0;
  43700. this._blendingFactor = 0;
  43701. this._originalBlendValue = null;
  43702. };
  43703. RuntimeAnimation.prototype.isStopped = function () {
  43704. return this._stopped;
  43705. };
  43706. RuntimeAnimation.prototype.dispose = function () {
  43707. var index = this._animation.runtimeAnimations.indexOf(this);
  43708. if (index > -1) {
  43709. this._animation.runtimeAnimations.splice(index, 1);
  43710. }
  43711. };
  43712. RuntimeAnimation.prototype._getKeyValue = function (value) {
  43713. if (typeof value === "function") {
  43714. return value();
  43715. }
  43716. return value;
  43717. };
  43718. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  43719. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  43720. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  43721. }
  43722. this.currentFrame = currentFrame;
  43723. var keys = this._animation.getKeys();
  43724. // Try to get a hash to find the right key
  43725. 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));
  43726. if (keys[startKeyIndex].frame >= currentFrame) {
  43727. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  43728. startKeyIndex--;
  43729. }
  43730. }
  43731. for (var key = startKeyIndex; key < keys.length; key++) {
  43732. var endKey = keys[key + 1];
  43733. if (endKey.frame >= currentFrame) {
  43734. var startKey = keys[key];
  43735. var startValue = this._getKeyValue(startKey.value);
  43736. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  43737. return startValue;
  43738. }
  43739. var endValue = this._getKeyValue(endKey.value);
  43740. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  43741. var frameDelta = endKey.frame - startKey.frame;
  43742. // gradient : percent of currentFrame between the frame inf and the frame sup
  43743. var gradient = (currentFrame - startKey.frame) / frameDelta;
  43744. // check for easingFunction and correction of gradient
  43745. var easingFunction = this._animation.getEasingFunction();
  43746. if (easingFunction != null) {
  43747. gradient = easingFunction.ease(gradient);
  43748. }
  43749. switch (this._animation.dataType) {
  43750. // Float
  43751. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43752. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  43753. switch (loopMode) {
  43754. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43755. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43756. return floatValue;
  43757. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43758. return offsetValue * repeatCount + floatValue;
  43759. }
  43760. break;
  43761. // Quaternion
  43762. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43763. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  43764. switch (loopMode) {
  43765. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43766. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43767. return quatValue;
  43768. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43769. return quatValue.add(offsetValue.scale(repeatCount));
  43770. }
  43771. return quatValue;
  43772. // Vector3
  43773. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43774. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  43775. switch (loopMode) {
  43776. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43777. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43778. return vec3Value;
  43779. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43780. return vec3Value.add(offsetValue.scale(repeatCount));
  43781. }
  43782. // Vector2
  43783. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43784. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  43785. switch (loopMode) {
  43786. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43787. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43788. return vec2Value;
  43789. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43790. return vec2Value.add(offsetValue.scale(repeatCount));
  43791. }
  43792. // Size
  43793. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43794. switch (loopMode) {
  43795. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43796. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43797. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  43798. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43799. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43800. }
  43801. // Color3
  43802. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43803. switch (loopMode) {
  43804. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43805. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43806. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  43807. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43808. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43809. }
  43810. // Matrix
  43811. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  43812. switch (loopMode) {
  43813. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43814. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43815. if (BABYLON.Animation.AllowMatricesInterpolation) {
  43816. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  43817. }
  43818. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43819. return startValue;
  43820. }
  43821. default:
  43822. break;
  43823. }
  43824. break;
  43825. }
  43826. }
  43827. return this._getKeyValue(keys[keys.length - 1].value);
  43828. };
  43829. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  43830. if (blend === void 0) { blend = false; }
  43831. // Set value
  43832. var path;
  43833. var destination;
  43834. var targetPropertyPath = this._animation.targetPropertyPath;
  43835. if (targetPropertyPath.length > 1) {
  43836. var property = this._target[targetPropertyPath[0]];
  43837. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  43838. property = property[targetPropertyPath[index]];
  43839. }
  43840. path = targetPropertyPath[targetPropertyPath.length - 1];
  43841. destination = property;
  43842. }
  43843. else {
  43844. path = targetPropertyPath[0];
  43845. destination = this._target;
  43846. }
  43847. // Blending
  43848. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  43849. if (!this._originalBlendValue) {
  43850. if (destination[path].clone) {
  43851. this._originalBlendValue = destination[path].clone();
  43852. }
  43853. else {
  43854. this._originalBlendValue = destination[path];
  43855. }
  43856. }
  43857. if (this._originalBlendValue.prototype) {
  43858. if (this._originalBlendValue.prototype.Lerp) {
  43859. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  43860. }
  43861. else {
  43862. destination[path] = currentValue;
  43863. }
  43864. }
  43865. else if (this._originalBlendValue.m) {
  43866. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  43867. }
  43868. else {
  43869. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  43870. }
  43871. this._blendingFactor += this._animation.blendingSpeed;
  43872. }
  43873. else {
  43874. destination[path] = currentValue;
  43875. }
  43876. if (this._target.markAsDirty) {
  43877. this._target.markAsDirty(this._animation.targetProperty);
  43878. }
  43879. };
  43880. RuntimeAnimation.prototype.goToFrame = function (frame) {
  43881. var keys = this._animation.getKeys();
  43882. if (frame < keys[0].frame) {
  43883. frame = keys[0].frame;
  43884. }
  43885. else if (frame > keys[keys.length - 1].frame) {
  43886. frame = keys[keys.length - 1].frame;
  43887. }
  43888. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  43889. this.setValue(currentValue);
  43890. };
  43891. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  43892. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  43893. this._ratioOffset = this._previousRatio - newRatio;
  43894. };
  43895. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  43896. if (blend === void 0) { blend = false; }
  43897. var targetPropertyPath = this._animation.targetPropertyPath;
  43898. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  43899. this._stopped = true;
  43900. return false;
  43901. }
  43902. var returnValue = true;
  43903. var keys = this._animation.getKeys();
  43904. // Adding a start key at frame 0 if missing
  43905. if (keys[0].frame !== 0) {
  43906. var newKey = { frame: 0, value: keys[0].value };
  43907. keys.splice(0, 0, newKey);
  43908. }
  43909. // Check limits
  43910. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  43911. from = keys[0].frame;
  43912. }
  43913. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  43914. to = keys[keys.length - 1].frame;
  43915. }
  43916. //to and from cannot be the same key
  43917. if (from === to) {
  43918. if (from > keys[0].frame) {
  43919. from--;
  43920. }
  43921. else if (to < keys[keys.length - 1].frame) {
  43922. to++;
  43923. }
  43924. }
  43925. // Compute ratio
  43926. var range = to - from;
  43927. var offsetValue;
  43928. // ratio represents the frame delta between from and to
  43929. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  43930. var highLimitValue = 0;
  43931. this._previousDelay = delay;
  43932. this._previousRatio = ratio;
  43933. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  43934. returnValue = false;
  43935. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  43936. }
  43937. else {
  43938. // Get max value if required
  43939. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  43940. var keyOffset = to.toString() + from.toString();
  43941. if (!this._offsetsCache[keyOffset]) {
  43942. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  43943. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  43944. switch (this._animation.dataType) {
  43945. // Float
  43946. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43947. this._offsetsCache[keyOffset] = toValue - fromValue;
  43948. break;
  43949. // Quaternion
  43950. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43951. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43952. break;
  43953. // Vector3
  43954. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43955. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43956. // Vector2
  43957. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43958. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43959. // Size
  43960. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43961. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43962. // Color3
  43963. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43964. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43965. default:
  43966. break;
  43967. }
  43968. this._highLimitsCache[keyOffset] = toValue;
  43969. }
  43970. highLimitValue = this._highLimitsCache[keyOffset];
  43971. offsetValue = this._offsetsCache[keyOffset];
  43972. }
  43973. }
  43974. if (offsetValue === undefined) {
  43975. switch (this._animation.dataType) {
  43976. // Float
  43977. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43978. offsetValue = 0;
  43979. break;
  43980. // Quaternion
  43981. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43982. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  43983. break;
  43984. // Vector3
  43985. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43986. offsetValue = BABYLON.Vector3.Zero();
  43987. break;
  43988. // Vector2
  43989. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43990. offsetValue = BABYLON.Vector2.Zero();
  43991. break;
  43992. // Size
  43993. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43994. offsetValue = BABYLON.Size.Zero();
  43995. break;
  43996. // Color3
  43997. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43998. offsetValue = BABYLON.Color3.Black();
  43999. }
  44000. }
  44001. // Compute value
  44002. var repeatCount = (ratio / range) >> 0;
  44003. var currentFrame = returnValue ? from + ratio % range : to;
  44004. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  44005. // Set value
  44006. this.setValue(currentValue);
  44007. // Check events
  44008. var events = this._animation.getEvents();
  44009. for (var index = 0; index < events.length; index++) {
  44010. // Make sure current frame has passed event frame and that event frame is within the current range
  44011. // Also, handle both forward and reverse animations
  44012. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  44013. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  44014. var event = events[index];
  44015. if (!event.isDone) {
  44016. // If event should be done only once, remove it.
  44017. if (event.onlyOnce) {
  44018. events.splice(index, 1);
  44019. index--;
  44020. }
  44021. event.isDone = true;
  44022. event.action();
  44023. } // Don't do anything if the event has already be done.
  44024. }
  44025. else if (events[index].isDone && !events[index].onlyOnce) {
  44026. // reset event, the animation is looping
  44027. events[index].isDone = false;
  44028. }
  44029. }
  44030. if (!returnValue) {
  44031. this._stopped = true;
  44032. }
  44033. return returnValue;
  44034. };
  44035. return RuntimeAnimation;
  44036. }());
  44037. BABYLON.RuntimeAnimation = RuntimeAnimation;
  44038. })(BABYLON || (BABYLON = {}));
  44039. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  44040. var BABYLON;
  44041. (function (BABYLON) {
  44042. var Animatable = /** @class */ (function () {
  44043. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  44044. if (fromFrame === void 0) { fromFrame = 0; }
  44045. if (toFrame === void 0) { toFrame = 100; }
  44046. if (loopAnimation === void 0) { loopAnimation = false; }
  44047. if (speedRatio === void 0) { speedRatio = 1.0; }
  44048. this.target = target;
  44049. this.fromFrame = fromFrame;
  44050. this.toFrame = toFrame;
  44051. this.loopAnimation = loopAnimation;
  44052. this.onAnimationEnd = onAnimationEnd;
  44053. this._localDelayOffset = null;
  44054. this._pausedDelay = null;
  44055. this._runtimeAnimations = new Array();
  44056. this._paused = false;
  44057. this._speedRatio = 1;
  44058. this.animationStarted = false;
  44059. if (animations) {
  44060. this.appendAnimations(target, animations);
  44061. }
  44062. this._speedRatio = speedRatio;
  44063. this._scene = scene;
  44064. scene._activeAnimatables.push(this);
  44065. }
  44066. Object.defineProperty(Animatable.prototype, "speedRatio", {
  44067. get: function () {
  44068. return this._speedRatio;
  44069. },
  44070. set: function (value) {
  44071. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  44072. var animation = this._runtimeAnimations[index];
  44073. animation._prepareForSpeedRatioChange(value);
  44074. }
  44075. this._speedRatio = value;
  44076. },
  44077. enumerable: true,
  44078. configurable: true
  44079. });
  44080. // Methods
  44081. Animatable.prototype.getAnimations = function () {
  44082. return this._runtimeAnimations;
  44083. };
  44084. Animatable.prototype.appendAnimations = function (target, animations) {
  44085. for (var index = 0; index < animations.length; index++) {
  44086. var animation = animations[index];
  44087. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  44088. }
  44089. };
  44090. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  44091. var runtimeAnimations = this._runtimeAnimations;
  44092. for (var index = 0; index < runtimeAnimations.length; index++) {
  44093. if (runtimeAnimations[index].animation.targetProperty === property) {
  44094. return runtimeAnimations[index].animation;
  44095. }
  44096. }
  44097. return null;
  44098. };
  44099. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  44100. var runtimeAnimations = this._runtimeAnimations;
  44101. for (var index = 0; index < runtimeAnimations.length; index++) {
  44102. if (runtimeAnimations[index].animation.targetProperty === property) {
  44103. return runtimeAnimations[index];
  44104. }
  44105. }
  44106. return null;
  44107. };
  44108. Animatable.prototype.reset = function () {
  44109. var runtimeAnimations = this._runtimeAnimations;
  44110. for (var index = 0; index < runtimeAnimations.length; index++) {
  44111. runtimeAnimations[index].reset();
  44112. }
  44113. // Reset to original value
  44114. for (index = 0; index < runtimeAnimations.length; index++) {
  44115. var animation = runtimeAnimations[index];
  44116. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  44117. }
  44118. this._localDelayOffset = null;
  44119. this._pausedDelay = null;
  44120. };
  44121. Animatable.prototype.enableBlending = function (blendingSpeed) {
  44122. var runtimeAnimations = this._runtimeAnimations;
  44123. for (var index = 0; index < runtimeAnimations.length; index++) {
  44124. runtimeAnimations[index].animation.enableBlending = true;
  44125. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  44126. }
  44127. };
  44128. Animatable.prototype.disableBlending = function () {
  44129. var runtimeAnimations = this._runtimeAnimations;
  44130. for (var index = 0; index < runtimeAnimations.length; index++) {
  44131. runtimeAnimations[index].animation.enableBlending = false;
  44132. }
  44133. };
  44134. Animatable.prototype.goToFrame = function (frame) {
  44135. var runtimeAnimations = this._runtimeAnimations;
  44136. if (runtimeAnimations[0]) {
  44137. var fps = runtimeAnimations[0].animation.framePerSecond;
  44138. var currentFrame = runtimeAnimations[0].currentFrame;
  44139. var adjustTime = frame - currentFrame;
  44140. var delay = adjustTime * 1000 / fps;
  44141. if (this._localDelayOffset === null) {
  44142. this._localDelayOffset = 0;
  44143. }
  44144. this._localDelayOffset -= delay;
  44145. }
  44146. for (var index = 0; index < runtimeAnimations.length; index++) {
  44147. runtimeAnimations[index].goToFrame(frame);
  44148. }
  44149. };
  44150. Animatable.prototype.pause = function () {
  44151. if (this._paused) {
  44152. return;
  44153. }
  44154. this._paused = true;
  44155. };
  44156. Animatable.prototype.restart = function () {
  44157. this._paused = false;
  44158. };
  44159. Animatable.prototype.stop = function (animationName) {
  44160. if (animationName) {
  44161. var idx = this._scene._activeAnimatables.indexOf(this);
  44162. if (idx > -1) {
  44163. var runtimeAnimations = this._runtimeAnimations;
  44164. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  44165. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  44166. continue;
  44167. }
  44168. runtimeAnimations[index].dispose();
  44169. runtimeAnimations.splice(index, 1);
  44170. }
  44171. if (runtimeAnimations.length == 0) {
  44172. this._scene._activeAnimatables.splice(idx, 1);
  44173. if (this.onAnimationEnd) {
  44174. this.onAnimationEnd();
  44175. }
  44176. }
  44177. }
  44178. }
  44179. else {
  44180. var index = this._scene._activeAnimatables.indexOf(this);
  44181. if (index > -1) {
  44182. this._scene._activeAnimatables.splice(index, 1);
  44183. var runtimeAnimations = this._runtimeAnimations;
  44184. for (var index = 0; index < runtimeAnimations.length; index++) {
  44185. runtimeAnimations[index].dispose();
  44186. }
  44187. if (this.onAnimationEnd) {
  44188. this.onAnimationEnd();
  44189. }
  44190. }
  44191. }
  44192. };
  44193. Animatable.prototype._animate = function (delay) {
  44194. if (this._paused) {
  44195. this.animationStarted = false;
  44196. if (this._pausedDelay === null) {
  44197. this._pausedDelay = delay;
  44198. }
  44199. return true;
  44200. }
  44201. if (this._localDelayOffset === null) {
  44202. this._localDelayOffset = delay;
  44203. }
  44204. else if (this._pausedDelay !== null) {
  44205. this._localDelayOffset += delay - this._pausedDelay;
  44206. this._pausedDelay = null;
  44207. }
  44208. // Animating
  44209. var running = false;
  44210. var runtimeAnimations = this._runtimeAnimations;
  44211. var index;
  44212. for (index = 0; index < runtimeAnimations.length; index++) {
  44213. var animation = runtimeAnimations[index];
  44214. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  44215. running = running || isRunning;
  44216. }
  44217. this.animationStarted = running;
  44218. if (!running) {
  44219. // Remove from active animatables
  44220. index = this._scene._activeAnimatables.indexOf(this);
  44221. this._scene._activeAnimatables.splice(index, 1);
  44222. // Dispose all runtime animations
  44223. for (index = 0; index < runtimeAnimations.length; index++) {
  44224. runtimeAnimations[index].dispose();
  44225. }
  44226. }
  44227. if (!running && this.onAnimationEnd) {
  44228. this.onAnimationEnd();
  44229. this.onAnimationEnd = null;
  44230. }
  44231. return running;
  44232. };
  44233. return Animatable;
  44234. }());
  44235. BABYLON.Animatable = Animatable;
  44236. })(BABYLON || (BABYLON = {}));
  44237. //# sourceMappingURL=babylon.animatable.js.map
  44238. var BABYLON;
  44239. (function (BABYLON) {
  44240. var EasingFunction = /** @class */ (function () {
  44241. function EasingFunction() {
  44242. // Properties
  44243. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  44244. }
  44245. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  44246. get: function () {
  44247. return EasingFunction._EASINGMODE_EASEIN;
  44248. },
  44249. enumerable: true,
  44250. configurable: true
  44251. });
  44252. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  44253. get: function () {
  44254. return EasingFunction._EASINGMODE_EASEOUT;
  44255. },
  44256. enumerable: true,
  44257. configurable: true
  44258. });
  44259. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  44260. get: function () {
  44261. return EasingFunction._EASINGMODE_EASEINOUT;
  44262. },
  44263. enumerable: true,
  44264. configurable: true
  44265. });
  44266. EasingFunction.prototype.setEasingMode = function (easingMode) {
  44267. var n = Math.min(Math.max(easingMode, 0), 2);
  44268. this._easingMode = n;
  44269. };
  44270. EasingFunction.prototype.getEasingMode = function () {
  44271. return this._easingMode;
  44272. };
  44273. EasingFunction.prototype.easeInCore = function (gradient) {
  44274. throw new Error('You must implement this method');
  44275. };
  44276. EasingFunction.prototype.ease = function (gradient) {
  44277. switch (this._easingMode) {
  44278. case EasingFunction.EASINGMODE_EASEIN:
  44279. return this.easeInCore(gradient);
  44280. case EasingFunction.EASINGMODE_EASEOUT:
  44281. return (1 - this.easeInCore(1 - gradient));
  44282. }
  44283. if (gradient >= 0.5) {
  44284. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  44285. }
  44286. return (this.easeInCore(gradient * 2) * 0.5);
  44287. };
  44288. //Statics
  44289. EasingFunction._EASINGMODE_EASEIN = 0;
  44290. EasingFunction._EASINGMODE_EASEOUT = 1;
  44291. EasingFunction._EASINGMODE_EASEINOUT = 2;
  44292. return EasingFunction;
  44293. }());
  44294. BABYLON.EasingFunction = EasingFunction;
  44295. var CircleEase = /** @class */ (function (_super) {
  44296. __extends(CircleEase, _super);
  44297. function CircleEase() {
  44298. return _super !== null && _super.apply(this, arguments) || this;
  44299. }
  44300. CircleEase.prototype.easeInCore = function (gradient) {
  44301. gradient = Math.max(0, Math.min(1, gradient));
  44302. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  44303. };
  44304. return CircleEase;
  44305. }(EasingFunction));
  44306. BABYLON.CircleEase = CircleEase;
  44307. var BackEase = /** @class */ (function (_super) {
  44308. __extends(BackEase, _super);
  44309. function BackEase(amplitude) {
  44310. if (amplitude === void 0) { amplitude = 1; }
  44311. var _this = _super.call(this) || this;
  44312. _this.amplitude = amplitude;
  44313. return _this;
  44314. }
  44315. BackEase.prototype.easeInCore = function (gradient) {
  44316. var num = Math.max(0, this.amplitude);
  44317. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  44318. };
  44319. return BackEase;
  44320. }(EasingFunction));
  44321. BABYLON.BackEase = BackEase;
  44322. var BounceEase = /** @class */ (function (_super) {
  44323. __extends(BounceEase, _super);
  44324. function BounceEase(bounces, bounciness) {
  44325. if (bounces === void 0) { bounces = 3; }
  44326. if (bounciness === void 0) { bounciness = 2; }
  44327. var _this = _super.call(this) || this;
  44328. _this.bounces = bounces;
  44329. _this.bounciness = bounciness;
  44330. return _this;
  44331. }
  44332. BounceEase.prototype.easeInCore = function (gradient) {
  44333. var y = Math.max(0.0, this.bounces);
  44334. var bounciness = this.bounciness;
  44335. if (bounciness <= 1.0) {
  44336. bounciness = 1.001;
  44337. }
  44338. var num9 = Math.pow(bounciness, y);
  44339. var num5 = 1.0 - bounciness;
  44340. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  44341. var num15 = gradient * num4;
  44342. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  44343. var num3 = Math.floor(num65);
  44344. var num13 = num3 + 1.0;
  44345. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  44346. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  44347. var num7 = (num8 + num12) * 0.5;
  44348. var num6 = gradient - num7;
  44349. var num2 = num7 - num8;
  44350. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  44351. };
  44352. return BounceEase;
  44353. }(EasingFunction));
  44354. BABYLON.BounceEase = BounceEase;
  44355. var CubicEase = /** @class */ (function (_super) {
  44356. __extends(CubicEase, _super);
  44357. function CubicEase() {
  44358. return _super !== null && _super.apply(this, arguments) || this;
  44359. }
  44360. CubicEase.prototype.easeInCore = function (gradient) {
  44361. return (gradient * gradient * gradient);
  44362. };
  44363. return CubicEase;
  44364. }(EasingFunction));
  44365. BABYLON.CubicEase = CubicEase;
  44366. var ElasticEase = /** @class */ (function (_super) {
  44367. __extends(ElasticEase, _super);
  44368. function ElasticEase(oscillations, springiness) {
  44369. if (oscillations === void 0) { oscillations = 3; }
  44370. if (springiness === void 0) { springiness = 3; }
  44371. var _this = _super.call(this) || this;
  44372. _this.oscillations = oscillations;
  44373. _this.springiness = springiness;
  44374. return _this;
  44375. }
  44376. ElasticEase.prototype.easeInCore = function (gradient) {
  44377. var num2;
  44378. var num3 = Math.max(0.0, this.oscillations);
  44379. var num = Math.max(0.0, this.springiness);
  44380. if (num == 0) {
  44381. num2 = gradient;
  44382. }
  44383. else {
  44384. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  44385. }
  44386. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  44387. };
  44388. return ElasticEase;
  44389. }(EasingFunction));
  44390. BABYLON.ElasticEase = ElasticEase;
  44391. var ExponentialEase = /** @class */ (function (_super) {
  44392. __extends(ExponentialEase, _super);
  44393. function ExponentialEase(exponent) {
  44394. if (exponent === void 0) { exponent = 2; }
  44395. var _this = _super.call(this) || this;
  44396. _this.exponent = exponent;
  44397. return _this;
  44398. }
  44399. ExponentialEase.prototype.easeInCore = function (gradient) {
  44400. if (this.exponent <= 0) {
  44401. return gradient;
  44402. }
  44403. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  44404. };
  44405. return ExponentialEase;
  44406. }(EasingFunction));
  44407. BABYLON.ExponentialEase = ExponentialEase;
  44408. var PowerEase = /** @class */ (function (_super) {
  44409. __extends(PowerEase, _super);
  44410. function PowerEase(power) {
  44411. if (power === void 0) { power = 2; }
  44412. var _this = _super.call(this) || this;
  44413. _this.power = power;
  44414. return _this;
  44415. }
  44416. PowerEase.prototype.easeInCore = function (gradient) {
  44417. var y = Math.max(0.0, this.power);
  44418. return Math.pow(gradient, y);
  44419. };
  44420. return PowerEase;
  44421. }(EasingFunction));
  44422. BABYLON.PowerEase = PowerEase;
  44423. var QuadraticEase = /** @class */ (function (_super) {
  44424. __extends(QuadraticEase, _super);
  44425. function QuadraticEase() {
  44426. return _super !== null && _super.apply(this, arguments) || this;
  44427. }
  44428. QuadraticEase.prototype.easeInCore = function (gradient) {
  44429. return (gradient * gradient);
  44430. };
  44431. return QuadraticEase;
  44432. }(EasingFunction));
  44433. BABYLON.QuadraticEase = QuadraticEase;
  44434. var QuarticEase = /** @class */ (function (_super) {
  44435. __extends(QuarticEase, _super);
  44436. function QuarticEase() {
  44437. return _super !== null && _super.apply(this, arguments) || this;
  44438. }
  44439. QuarticEase.prototype.easeInCore = function (gradient) {
  44440. return (gradient * gradient * gradient * gradient);
  44441. };
  44442. return QuarticEase;
  44443. }(EasingFunction));
  44444. BABYLON.QuarticEase = QuarticEase;
  44445. var QuinticEase = /** @class */ (function (_super) {
  44446. __extends(QuinticEase, _super);
  44447. function QuinticEase() {
  44448. return _super !== null && _super.apply(this, arguments) || this;
  44449. }
  44450. QuinticEase.prototype.easeInCore = function (gradient) {
  44451. return (gradient * gradient * gradient * gradient * gradient);
  44452. };
  44453. return QuinticEase;
  44454. }(EasingFunction));
  44455. BABYLON.QuinticEase = QuinticEase;
  44456. var SineEase = /** @class */ (function (_super) {
  44457. __extends(SineEase, _super);
  44458. function SineEase() {
  44459. return _super !== null && _super.apply(this, arguments) || this;
  44460. }
  44461. SineEase.prototype.easeInCore = function (gradient) {
  44462. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  44463. };
  44464. return SineEase;
  44465. }(EasingFunction));
  44466. BABYLON.SineEase = SineEase;
  44467. var BezierCurveEase = /** @class */ (function (_super) {
  44468. __extends(BezierCurveEase, _super);
  44469. function BezierCurveEase(x1, y1, x2, y2) {
  44470. if (x1 === void 0) { x1 = 0; }
  44471. if (y1 === void 0) { y1 = 0; }
  44472. if (x2 === void 0) { x2 = 1; }
  44473. if (y2 === void 0) { y2 = 1; }
  44474. var _this = _super.call(this) || this;
  44475. _this.x1 = x1;
  44476. _this.y1 = y1;
  44477. _this.x2 = x2;
  44478. _this.y2 = y2;
  44479. return _this;
  44480. }
  44481. BezierCurveEase.prototype.easeInCore = function (gradient) {
  44482. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  44483. };
  44484. return BezierCurveEase;
  44485. }(EasingFunction));
  44486. BABYLON.BezierCurveEase = BezierCurveEase;
  44487. })(BABYLON || (BABYLON = {}));
  44488. //# sourceMappingURL=babylon.easing.js.map
  44489. var BABYLON;
  44490. (function (BABYLON) {
  44491. var Condition = /** @class */ (function () {
  44492. function Condition(actionManager) {
  44493. this._actionManager = actionManager;
  44494. }
  44495. Condition.prototype.isValid = function () {
  44496. return true;
  44497. };
  44498. Condition.prototype._getProperty = function (propertyPath) {
  44499. return this._actionManager._getProperty(propertyPath);
  44500. };
  44501. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  44502. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44503. };
  44504. Condition.prototype.serialize = function () {
  44505. };
  44506. Condition.prototype._serialize = function (serializedCondition) {
  44507. return {
  44508. type: 2,
  44509. children: [],
  44510. name: serializedCondition.name,
  44511. properties: serializedCondition.properties
  44512. };
  44513. };
  44514. return Condition;
  44515. }());
  44516. BABYLON.Condition = Condition;
  44517. var ValueCondition = /** @class */ (function (_super) {
  44518. __extends(ValueCondition, _super);
  44519. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  44520. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  44521. var _this = _super.call(this, actionManager) || this;
  44522. _this.propertyPath = propertyPath;
  44523. _this.value = value;
  44524. _this.operator = operator;
  44525. _this._target = target;
  44526. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  44527. _this._property = _this._getProperty(_this.propertyPath);
  44528. return _this;
  44529. }
  44530. Object.defineProperty(ValueCondition, "IsEqual", {
  44531. get: function () {
  44532. return ValueCondition._IsEqual;
  44533. },
  44534. enumerable: true,
  44535. configurable: true
  44536. });
  44537. Object.defineProperty(ValueCondition, "IsDifferent", {
  44538. get: function () {
  44539. return ValueCondition._IsDifferent;
  44540. },
  44541. enumerable: true,
  44542. configurable: true
  44543. });
  44544. Object.defineProperty(ValueCondition, "IsGreater", {
  44545. get: function () {
  44546. return ValueCondition._IsGreater;
  44547. },
  44548. enumerable: true,
  44549. configurable: true
  44550. });
  44551. Object.defineProperty(ValueCondition, "IsLesser", {
  44552. get: function () {
  44553. return ValueCondition._IsLesser;
  44554. },
  44555. enumerable: true,
  44556. configurable: true
  44557. });
  44558. // Methods
  44559. ValueCondition.prototype.isValid = function () {
  44560. switch (this.operator) {
  44561. case ValueCondition.IsGreater:
  44562. return this._effectiveTarget[this._property] > this.value;
  44563. case ValueCondition.IsLesser:
  44564. return this._effectiveTarget[this._property] < this.value;
  44565. case ValueCondition.IsEqual:
  44566. case ValueCondition.IsDifferent:
  44567. var check;
  44568. if (this.value.equals) {
  44569. check = this.value.equals(this._effectiveTarget[this._property]);
  44570. }
  44571. else {
  44572. check = this.value === this._effectiveTarget[this._property];
  44573. }
  44574. return this.operator === ValueCondition.IsEqual ? check : !check;
  44575. }
  44576. return false;
  44577. };
  44578. ValueCondition.prototype.serialize = function () {
  44579. return this._serialize({
  44580. name: "ValueCondition",
  44581. properties: [
  44582. BABYLON.Action._GetTargetProperty(this._target),
  44583. { name: "propertyPath", value: this.propertyPath },
  44584. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44585. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  44586. ]
  44587. });
  44588. };
  44589. ValueCondition.GetOperatorName = function (operator) {
  44590. switch (operator) {
  44591. case ValueCondition._IsEqual: return "IsEqual";
  44592. case ValueCondition._IsDifferent: return "IsDifferent";
  44593. case ValueCondition._IsGreater: return "IsGreater";
  44594. case ValueCondition._IsLesser: return "IsLesser";
  44595. default: return "";
  44596. }
  44597. };
  44598. // Statics
  44599. ValueCondition._IsEqual = 0;
  44600. ValueCondition._IsDifferent = 1;
  44601. ValueCondition._IsGreater = 2;
  44602. ValueCondition._IsLesser = 3;
  44603. return ValueCondition;
  44604. }(Condition));
  44605. BABYLON.ValueCondition = ValueCondition;
  44606. var PredicateCondition = /** @class */ (function (_super) {
  44607. __extends(PredicateCondition, _super);
  44608. function PredicateCondition(actionManager, predicate) {
  44609. var _this = _super.call(this, actionManager) || this;
  44610. _this.predicate = predicate;
  44611. return _this;
  44612. }
  44613. PredicateCondition.prototype.isValid = function () {
  44614. return this.predicate();
  44615. };
  44616. return PredicateCondition;
  44617. }(Condition));
  44618. BABYLON.PredicateCondition = PredicateCondition;
  44619. var StateCondition = /** @class */ (function (_super) {
  44620. __extends(StateCondition, _super);
  44621. function StateCondition(actionManager, target, value) {
  44622. var _this = _super.call(this, actionManager) || this;
  44623. _this.value = value;
  44624. _this._target = target;
  44625. return _this;
  44626. }
  44627. // Methods
  44628. StateCondition.prototype.isValid = function () {
  44629. return this._target.state === this.value;
  44630. };
  44631. StateCondition.prototype.serialize = function () {
  44632. return this._serialize({
  44633. name: "StateCondition",
  44634. properties: [
  44635. BABYLON.Action._GetTargetProperty(this._target),
  44636. { name: "value", value: this.value }
  44637. ]
  44638. });
  44639. };
  44640. return StateCondition;
  44641. }(Condition));
  44642. BABYLON.StateCondition = StateCondition;
  44643. })(BABYLON || (BABYLON = {}));
  44644. //# sourceMappingURL=babylon.condition.js.map
  44645. var BABYLON;
  44646. (function (BABYLON) {
  44647. var Action = /** @class */ (function () {
  44648. function Action(triggerOptions, condition) {
  44649. this.triggerOptions = triggerOptions;
  44650. this.onBeforeExecuteObservable = new BABYLON.Observable();
  44651. if (triggerOptions.parameter) {
  44652. this.trigger = triggerOptions.trigger;
  44653. this._triggerParameter = triggerOptions.parameter;
  44654. }
  44655. else {
  44656. this.trigger = triggerOptions;
  44657. }
  44658. this._nextActiveAction = this;
  44659. this._condition = condition;
  44660. }
  44661. // Methods
  44662. Action.prototype._prepare = function () {
  44663. };
  44664. Action.prototype.getTriggerParameter = function () {
  44665. return this._triggerParameter;
  44666. };
  44667. Action.prototype._executeCurrent = function (evt) {
  44668. if (this._nextActiveAction._condition) {
  44669. var condition = this._nextActiveAction._condition;
  44670. var currentRenderId = this._actionManager.getScene().getRenderId();
  44671. // We cache the current evaluation for the current frame
  44672. if (condition._evaluationId === currentRenderId) {
  44673. if (!condition._currentResult) {
  44674. return;
  44675. }
  44676. }
  44677. else {
  44678. condition._evaluationId = currentRenderId;
  44679. if (!condition.isValid()) {
  44680. condition._currentResult = false;
  44681. return;
  44682. }
  44683. condition._currentResult = true;
  44684. }
  44685. }
  44686. this.onBeforeExecuteObservable.notifyObservers(this);
  44687. this._nextActiveAction.execute(evt);
  44688. this.skipToNextActiveAction();
  44689. };
  44690. Action.prototype.execute = function (evt) {
  44691. };
  44692. Action.prototype.skipToNextActiveAction = function () {
  44693. if (this._nextActiveAction._child) {
  44694. if (!this._nextActiveAction._child._actionManager) {
  44695. this._nextActiveAction._child._actionManager = this._actionManager;
  44696. }
  44697. this._nextActiveAction = this._nextActiveAction._child;
  44698. }
  44699. else {
  44700. this._nextActiveAction = this;
  44701. }
  44702. };
  44703. Action.prototype.then = function (action) {
  44704. this._child = action;
  44705. action._actionManager = this._actionManager;
  44706. action._prepare();
  44707. return action;
  44708. };
  44709. Action.prototype._getProperty = function (propertyPath) {
  44710. return this._actionManager._getProperty(propertyPath);
  44711. };
  44712. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  44713. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44714. };
  44715. Action.prototype.serialize = function (parent) {
  44716. };
  44717. // Called by BABYLON.Action objects in serialize(...). Internal use
  44718. Action.prototype._serialize = function (serializedAction, parent) {
  44719. var serializationObject = {
  44720. type: 1,
  44721. children: [],
  44722. name: serializedAction.name,
  44723. properties: serializedAction.properties || []
  44724. };
  44725. // Serialize child
  44726. if (this._child) {
  44727. this._child.serialize(serializationObject);
  44728. }
  44729. // Check if "this" has a condition
  44730. if (this._condition) {
  44731. var serializedCondition = this._condition.serialize();
  44732. serializedCondition.children.push(serializationObject);
  44733. if (parent) {
  44734. parent.children.push(serializedCondition);
  44735. }
  44736. return serializedCondition;
  44737. }
  44738. if (parent) {
  44739. parent.children.push(serializationObject);
  44740. }
  44741. return serializationObject;
  44742. };
  44743. Action._SerializeValueAsString = function (value) {
  44744. if (typeof value === "number") {
  44745. return value.toString();
  44746. }
  44747. if (typeof value === "boolean") {
  44748. return value ? "true" : "false";
  44749. }
  44750. if (value instanceof BABYLON.Vector2) {
  44751. return value.x + ", " + value.y;
  44752. }
  44753. if (value instanceof BABYLON.Vector3) {
  44754. return value.x + ", " + value.y + ", " + value.z;
  44755. }
  44756. if (value instanceof BABYLON.Color3) {
  44757. return value.r + ", " + value.g + ", " + value.b;
  44758. }
  44759. if (value instanceof BABYLON.Color4) {
  44760. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  44761. }
  44762. return value; // string
  44763. };
  44764. Action._GetTargetProperty = function (target) {
  44765. return {
  44766. name: "target",
  44767. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  44768. : target instanceof BABYLON.Light ? "LightProperties"
  44769. : target instanceof BABYLON.Camera ? "CameraProperties"
  44770. : "SceneProperties",
  44771. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  44772. };
  44773. };
  44774. return Action;
  44775. }());
  44776. BABYLON.Action = Action;
  44777. })(BABYLON || (BABYLON = {}));
  44778. //# sourceMappingURL=babylon.action.js.map
  44779. var BABYLON;
  44780. (function (BABYLON) {
  44781. /**
  44782. * ActionEvent is the event beint sent when an action is triggered.
  44783. */
  44784. var ActionEvent = /** @class */ (function () {
  44785. /**
  44786. * @param source The mesh or sprite that triggered the action.
  44787. * @param pointerX The X mouse cursor position at the time of the event
  44788. * @param pointerY The Y mouse cursor position at the time of the event
  44789. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  44790. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  44791. */
  44792. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  44793. this.source = source;
  44794. this.pointerX = pointerX;
  44795. this.pointerY = pointerY;
  44796. this.meshUnderPointer = meshUnderPointer;
  44797. this.sourceEvent = sourceEvent;
  44798. this.additionalData = additionalData;
  44799. }
  44800. /**
  44801. * Helper function to auto-create an ActionEvent from a source mesh.
  44802. * @param source The source mesh that triggered the event
  44803. * @param evt {Event} The original (browser) event
  44804. */
  44805. ActionEvent.CreateNew = function (source, evt, additionalData) {
  44806. var scene = source.getScene();
  44807. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44808. };
  44809. /**
  44810. * Helper function to auto-create an ActionEvent from a source mesh.
  44811. * @param source The source sprite that triggered the event
  44812. * @param scene Scene associated with the sprite
  44813. * @param evt {Event} The original (browser) event
  44814. */
  44815. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  44816. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44817. };
  44818. /**
  44819. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  44820. * @param scene the scene where the event occurred
  44821. * @param evt {Event} The original (browser) event
  44822. */
  44823. ActionEvent.CreateNewFromScene = function (scene, evt) {
  44824. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  44825. };
  44826. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  44827. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  44828. };
  44829. return ActionEvent;
  44830. }());
  44831. BABYLON.ActionEvent = ActionEvent;
  44832. /**
  44833. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  44834. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  44835. */
  44836. var ActionManager = /** @class */ (function () {
  44837. function ActionManager(scene) {
  44838. // Members
  44839. this.actions = new Array();
  44840. this.hoverCursor = '';
  44841. this._scene = scene;
  44842. scene._actionManagers.push(this);
  44843. }
  44844. Object.defineProperty(ActionManager, "NothingTrigger", {
  44845. get: function () {
  44846. return ActionManager._NothingTrigger;
  44847. },
  44848. enumerable: true,
  44849. configurable: true
  44850. });
  44851. Object.defineProperty(ActionManager, "OnPickTrigger", {
  44852. get: function () {
  44853. return ActionManager._OnPickTrigger;
  44854. },
  44855. enumerable: true,
  44856. configurable: true
  44857. });
  44858. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  44859. get: function () {
  44860. return ActionManager._OnLeftPickTrigger;
  44861. },
  44862. enumerable: true,
  44863. configurable: true
  44864. });
  44865. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  44866. get: function () {
  44867. return ActionManager._OnRightPickTrigger;
  44868. },
  44869. enumerable: true,
  44870. configurable: true
  44871. });
  44872. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  44873. get: function () {
  44874. return ActionManager._OnCenterPickTrigger;
  44875. },
  44876. enumerable: true,
  44877. configurable: true
  44878. });
  44879. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  44880. get: function () {
  44881. return ActionManager._OnPickDownTrigger;
  44882. },
  44883. enumerable: true,
  44884. configurable: true
  44885. });
  44886. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  44887. get: function () {
  44888. return ActionManager._OnDoublePickTrigger;
  44889. },
  44890. enumerable: true,
  44891. configurable: true
  44892. });
  44893. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  44894. get: function () {
  44895. return ActionManager._OnPickUpTrigger;
  44896. },
  44897. enumerable: true,
  44898. configurable: true
  44899. });
  44900. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  44901. /// This trigger will only be raised if you also declared a OnPickDown
  44902. get: function () {
  44903. return ActionManager._OnPickOutTrigger;
  44904. },
  44905. enumerable: true,
  44906. configurable: true
  44907. });
  44908. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  44909. get: function () {
  44910. return ActionManager._OnLongPressTrigger;
  44911. },
  44912. enumerable: true,
  44913. configurable: true
  44914. });
  44915. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  44916. get: function () {
  44917. return ActionManager._OnPointerOverTrigger;
  44918. },
  44919. enumerable: true,
  44920. configurable: true
  44921. });
  44922. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  44923. get: function () {
  44924. return ActionManager._OnPointerOutTrigger;
  44925. },
  44926. enumerable: true,
  44927. configurable: true
  44928. });
  44929. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  44930. get: function () {
  44931. return ActionManager._OnEveryFrameTrigger;
  44932. },
  44933. enumerable: true,
  44934. configurable: true
  44935. });
  44936. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  44937. get: function () {
  44938. return ActionManager._OnIntersectionEnterTrigger;
  44939. },
  44940. enumerable: true,
  44941. configurable: true
  44942. });
  44943. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  44944. get: function () {
  44945. return ActionManager._OnIntersectionExitTrigger;
  44946. },
  44947. enumerable: true,
  44948. configurable: true
  44949. });
  44950. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  44951. get: function () {
  44952. return ActionManager._OnKeyDownTrigger;
  44953. },
  44954. enumerable: true,
  44955. configurable: true
  44956. });
  44957. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  44958. get: function () {
  44959. return ActionManager._OnKeyUpTrigger;
  44960. },
  44961. enumerable: true,
  44962. configurable: true
  44963. });
  44964. // Methods
  44965. ActionManager.prototype.dispose = function () {
  44966. var index = this._scene._actionManagers.indexOf(this);
  44967. for (var i = 0; i < this.actions.length; i++) {
  44968. var action = this.actions[i];
  44969. ActionManager.Triggers[action.trigger]--;
  44970. if (ActionManager.Triggers[action.trigger] === 0) {
  44971. delete ActionManager.Triggers[action.trigger];
  44972. }
  44973. }
  44974. if (index > -1) {
  44975. this._scene._actionManagers.splice(index, 1);
  44976. }
  44977. };
  44978. ActionManager.prototype.getScene = function () {
  44979. return this._scene;
  44980. };
  44981. /**
  44982. * Does this action manager handles actions of any of the given triggers
  44983. * @param {number[]} triggers - the triggers to be tested
  44984. * @return {boolean} whether one (or more) of the triggers is handeled
  44985. */
  44986. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  44987. for (var index = 0; index < this.actions.length; index++) {
  44988. var action = this.actions[index];
  44989. if (triggers.indexOf(action.trigger) > -1) {
  44990. return true;
  44991. }
  44992. }
  44993. return false;
  44994. };
  44995. /**
  44996. * Does this action manager handles actions of a given trigger
  44997. * @param {number} trigger - the trigger to be tested
  44998. * @return {boolean} whether the trigger is handeled
  44999. */
  45000. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45001. for (var index = 0; index < this.actions.length; index++) {
  45002. var action = this.actions[index];
  45003. if (action.trigger === trigger) {
  45004. return true;
  45005. }
  45006. }
  45007. return false;
  45008. };
  45009. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45010. /**
  45011. * Does this action manager has pointer triggers
  45012. * @return {boolean} whether or not it has pointer triggers
  45013. */
  45014. get: function () {
  45015. for (var index = 0; index < this.actions.length; index++) {
  45016. var action = this.actions[index];
  45017. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45018. return true;
  45019. }
  45020. }
  45021. return false;
  45022. },
  45023. enumerable: true,
  45024. configurable: true
  45025. });
  45026. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45027. /**
  45028. * Does this action manager has pick triggers
  45029. * @return {boolean} whether or not it has pick triggers
  45030. */
  45031. get: function () {
  45032. for (var index = 0; index < this.actions.length; index++) {
  45033. var action = this.actions[index];
  45034. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45035. return true;
  45036. }
  45037. }
  45038. return false;
  45039. },
  45040. enumerable: true,
  45041. configurable: true
  45042. });
  45043. Object.defineProperty(ActionManager, "HasTriggers", {
  45044. /**
  45045. * Does exist one action manager with at least one trigger
  45046. * @return {boolean} whether or not it exists one action manager with one trigger
  45047. **/
  45048. get: function () {
  45049. for (var t in ActionManager.Triggers) {
  45050. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45051. return true;
  45052. }
  45053. }
  45054. return false;
  45055. },
  45056. enumerable: true,
  45057. configurable: true
  45058. });
  45059. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45060. /**
  45061. * Does exist one action manager with at least one pick trigger
  45062. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45063. **/
  45064. get: function () {
  45065. for (var t in ActionManager.Triggers) {
  45066. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45067. var t_int = parseInt(t);
  45068. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45069. return true;
  45070. }
  45071. }
  45072. }
  45073. return false;
  45074. },
  45075. enumerable: true,
  45076. configurable: true
  45077. });
  45078. /**
  45079. * Does exist one action manager that handles actions of a given trigger
  45080. * @param {number} trigger - the trigger to be tested
  45081. * @return {boolean} whether the trigger is handeled by at least one action manager
  45082. **/
  45083. ActionManager.HasSpecificTrigger = function (trigger) {
  45084. for (var t in ActionManager.Triggers) {
  45085. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45086. var t_int = parseInt(t);
  45087. if (t_int === trigger) {
  45088. return true;
  45089. }
  45090. }
  45091. }
  45092. return false;
  45093. };
  45094. /**
  45095. * Registers an action to this action manager
  45096. * @param {BABYLON.Action} action - the action to be registered
  45097. * @return {BABYLON.Action} the action amended (prepared) after registration
  45098. */
  45099. ActionManager.prototype.registerAction = function (action) {
  45100. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  45101. if (this.getScene().actionManager !== this) {
  45102. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  45103. return null;
  45104. }
  45105. }
  45106. this.actions.push(action);
  45107. if (ActionManager.Triggers[action.trigger]) {
  45108. ActionManager.Triggers[action.trigger]++;
  45109. }
  45110. else {
  45111. ActionManager.Triggers[action.trigger] = 1;
  45112. }
  45113. action._actionManager = this;
  45114. action._prepare();
  45115. return action;
  45116. };
  45117. /**
  45118. * Unregisters an action to this action manager
  45119. * @param action The action to be unregistered
  45120. * @return whether the action has been unregistered
  45121. */
  45122. ActionManager.prototype.unregisterAction = function (action) {
  45123. var index = this.actions.indexOf(action);
  45124. if (index !== -1) {
  45125. this.actions.splice(index, 1);
  45126. ActionManager.Triggers[action.trigger] -= 1;
  45127. if (ActionManager.Triggers[action.trigger] === 0) {
  45128. delete ActionManager.Triggers[action.trigger];
  45129. }
  45130. delete action._actionManager;
  45131. return true;
  45132. }
  45133. return false;
  45134. };
  45135. /**
  45136. * Process a specific trigger
  45137. * @param {number} trigger - the trigger to process
  45138. * @param evt {BABYLON.ActionEvent} the event details to be processed
  45139. */
  45140. ActionManager.prototype.processTrigger = function (trigger, evt) {
  45141. for (var index = 0; index < this.actions.length; index++) {
  45142. var action = this.actions[index];
  45143. if (action.trigger === trigger) {
  45144. if (evt) {
  45145. if (trigger === ActionManager.OnKeyUpTrigger
  45146. || trigger === ActionManager.OnKeyDownTrigger) {
  45147. var parameter = action.getTriggerParameter();
  45148. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  45149. if (!parameter.toLowerCase) {
  45150. continue;
  45151. }
  45152. var lowerCase = parameter.toLowerCase();
  45153. if (lowerCase !== evt.sourceEvent.key) {
  45154. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  45155. var actualkey = String.fromCharCode(unicode).toLowerCase();
  45156. if (actualkey !== lowerCase) {
  45157. continue;
  45158. }
  45159. }
  45160. }
  45161. }
  45162. }
  45163. action._executeCurrent(evt);
  45164. }
  45165. }
  45166. };
  45167. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  45168. var properties = propertyPath.split(".");
  45169. for (var index = 0; index < properties.length - 1; index++) {
  45170. target = target[properties[index]];
  45171. }
  45172. return target;
  45173. };
  45174. ActionManager.prototype._getProperty = function (propertyPath) {
  45175. var properties = propertyPath.split(".");
  45176. return properties[properties.length - 1];
  45177. };
  45178. ActionManager.prototype.serialize = function (name) {
  45179. var root = {
  45180. children: new Array(),
  45181. name: name,
  45182. type: 3,
  45183. properties: new Array() // Empty for root but required
  45184. };
  45185. for (var i = 0; i < this.actions.length; i++) {
  45186. var triggerObject = {
  45187. type: 0,
  45188. children: new Array(),
  45189. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  45190. properties: new Array()
  45191. };
  45192. var triggerOptions = this.actions[i].triggerOptions;
  45193. if (triggerOptions && typeof triggerOptions !== "number") {
  45194. if (triggerOptions.parameter instanceof BABYLON.Node) {
  45195. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  45196. }
  45197. else {
  45198. var parameter = {};
  45199. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  45200. if (triggerOptions.parameter.mesh) {
  45201. parameter._meshId = triggerOptions.parameter.mesh.id;
  45202. }
  45203. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  45204. }
  45205. }
  45206. // Serialize child action, recursively
  45207. this.actions[i].serialize(triggerObject);
  45208. // Add serialized trigger
  45209. root.children.push(triggerObject);
  45210. }
  45211. return root;
  45212. };
  45213. ActionManager.Parse = function (parsedActions, object, scene) {
  45214. var actionManager = new ActionManager(scene);
  45215. if (object === null)
  45216. scene.actionManager = actionManager;
  45217. else
  45218. object.actionManager = actionManager;
  45219. // instanciate a new object
  45220. var instanciate = function (name, params) {
  45221. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  45222. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  45223. newInstance.constructor.apply(newInstance, params);
  45224. return newInstance;
  45225. };
  45226. var parseParameter = function (name, value, target, propertyPath) {
  45227. if (propertyPath === null) {
  45228. // String, boolean or float
  45229. var floatValue = parseFloat(value);
  45230. if (value === "true" || value === "false")
  45231. return value === "true";
  45232. else
  45233. return isNaN(floatValue) ? value : floatValue;
  45234. }
  45235. var effectiveTarget = propertyPath.split(".");
  45236. var values = value.split(",");
  45237. // Get effective Target
  45238. for (var i = 0; i < effectiveTarget.length; i++) {
  45239. target = target[effectiveTarget[i]];
  45240. }
  45241. // Return appropriate value with its type
  45242. if (typeof (target) === "boolean")
  45243. return values[0] === "true";
  45244. if (typeof (target) === "string")
  45245. return values[0];
  45246. // Parameters with multiple values such as Vector3 etc.
  45247. var split = new Array();
  45248. for (var i = 0; i < values.length; i++)
  45249. split.push(parseFloat(values[i]));
  45250. if (target instanceof BABYLON.Vector3)
  45251. return BABYLON.Vector3.FromArray(split);
  45252. if (target instanceof BABYLON.Vector4)
  45253. return BABYLON.Vector4.FromArray(split);
  45254. if (target instanceof BABYLON.Color3)
  45255. return BABYLON.Color3.FromArray(split);
  45256. if (target instanceof BABYLON.Color4)
  45257. return BABYLON.Color4.FromArray(split);
  45258. return parseFloat(values[0]);
  45259. };
  45260. // traverse graph per trigger
  45261. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  45262. if (combineArray === void 0) { combineArray = null; }
  45263. if (parsedAction.detached)
  45264. return;
  45265. var parameters = new Array();
  45266. var target = null;
  45267. var propertyPath = null;
  45268. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  45269. // Parameters
  45270. if (parsedAction.type === 2)
  45271. parameters.push(actionManager);
  45272. else
  45273. parameters.push(trigger);
  45274. if (combine) {
  45275. var actions = new Array();
  45276. for (var j = 0; j < parsedAction.combine.length; j++) {
  45277. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  45278. }
  45279. parameters.push(actions);
  45280. }
  45281. else {
  45282. for (var i = 0; i < parsedAction.properties.length; i++) {
  45283. var value = parsedAction.properties[i].value;
  45284. var name = parsedAction.properties[i].name;
  45285. var targetType = parsedAction.properties[i].targetType;
  45286. if (name === "target")
  45287. if (targetType !== null && targetType === "SceneProperties")
  45288. value = target = scene;
  45289. else
  45290. value = target = scene.getNodeByName(value);
  45291. else if (name === "parent")
  45292. value = scene.getNodeByName(value);
  45293. else if (name === "sound")
  45294. value = scene.getSoundByName(value);
  45295. else if (name !== "propertyPath") {
  45296. if (parsedAction.type === 2 && name === "operator")
  45297. value = BABYLON.ValueCondition[value];
  45298. else
  45299. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  45300. }
  45301. else {
  45302. propertyPath = value;
  45303. }
  45304. parameters.push(value);
  45305. }
  45306. }
  45307. if (combineArray === null) {
  45308. parameters.push(condition);
  45309. }
  45310. else {
  45311. parameters.push(null);
  45312. }
  45313. // If interpolate value action
  45314. if (parsedAction.name === "InterpolateValueAction") {
  45315. var param = parameters[parameters.length - 2];
  45316. parameters[parameters.length - 1] = param;
  45317. parameters[parameters.length - 2] = condition;
  45318. }
  45319. // Action or condition(s) and not CombineAction
  45320. var newAction = instanciate(parsedAction.name, parameters);
  45321. if (newAction instanceof BABYLON.Condition && condition !== null) {
  45322. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  45323. if (action)
  45324. action.then(nothing);
  45325. else
  45326. actionManager.registerAction(nothing);
  45327. action = nothing;
  45328. }
  45329. if (combineArray === null) {
  45330. if (newAction instanceof BABYLON.Condition) {
  45331. condition = newAction;
  45332. newAction = action;
  45333. }
  45334. else {
  45335. condition = null;
  45336. if (action)
  45337. action.then(newAction);
  45338. else
  45339. actionManager.registerAction(newAction);
  45340. }
  45341. }
  45342. else {
  45343. combineArray.push(newAction);
  45344. }
  45345. for (var i = 0; i < parsedAction.children.length; i++)
  45346. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  45347. };
  45348. // triggers
  45349. for (var i = 0; i < parsedActions.children.length; i++) {
  45350. var triggerParams;
  45351. var trigger = parsedActions.children[i];
  45352. if (trigger.properties.length > 0) {
  45353. var param = trigger.properties[0].value;
  45354. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  45355. if (value._meshId) {
  45356. value.mesh = scene.getMeshByID(value._meshId);
  45357. }
  45358. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  45359. }
  45360. else
  45361. triggerParams = ActionManager[trigger.name];
  45362. for (var j = 0; j < trigger.children.length; j++) {
  45363. if (!trigger.detached)
  45364. traverse(trigger.children[j], triggerParams, null, null);
  45365. }
  45366. }
  45367. };
  45368. ActionManager.GetTriggerName = function (trigger) {
  45369. switch (trigger) {
  45370. case 0: return "NothingTrigger";
  45371. case 1: return "OnPickTrigger";
  45372. case 2: return "OnLeftPickTrigger";
  45373. case 3: return "OnRightPickTrigger";
  45374. case 4: return "OnCenterPickTrigger";
  45375. case 5: return "OnPickDownTrigger";
  45376. case 6: return "OnPickUpTrigger";
  45377. case 7: return "OnLongPressTrigger";
  45378. case 8: return "OnPointerOverTrigger";
  45379. case 9: return "OnPointerOutTrigger";
  45380. case 10: return "OnEveryFrameTrigger";
  45381. case 11: return "OnIntersectionEnterTrigger";
  45382. case 12: return "OnIntersectionExitTrigger";
  45383. case 13: return "OnKeyDownTrigger";
  45384. case 14: return "OnKeyUpTrigger";
  45385. case 15: return "OnPickOutTrigger";
  45386. default: return "";
  45387. }
  45388. };
  45389. // Statics
  45390. ActionManager._NothingTrigger = 0;
  45391. ActionManager._OnPickTrigger = 1;
  45392. ActionManager._OnLeftPickTrigger = 2;
  45393. ActionManager._OnRightPickTrigger = 3;
  45394. ActionManager._OnCenterPickTrigger = 4;
  45395. ActionManager._OnPickDownTrigger = 5;
  45396. ActionManager._OnDoublePickTrigger = 6;
  45397. ActionManager._OnPickUpTrigger = 7;
  45398. ActionManager._OnLongPressTrigger = 8;
  45399. ActionManager._OnPointerOverTrigger = 9;
  45400. ActionManager._OnPointerOutTrigger = 10;
  45401. ActionManager._OnEveryFrameTrigger = 11;
  45402. ActionManager._OnIntersectionEnterTrigger = 12;
  45403. ActionManager._OnIntersectionExitTrigger = 13;
  45404. ActionManager._OnKeyDownTrigger = 14;
  45405. ActionManager._OnKeyUpTrigger = 15;
  45406. ActionManager._OnPickOutTrigger = 16;
  45407. ActionManager.Triggers = {};
  45408. return ActionManager;
  45409. }());
  45410. BABYLON.ActionManager = ActionManager;
  45411. })(BABYLON || (BABYLON = {}));
  45412. //# sourceMappingURL=babylon.actionManager.js.map
  45413. var BABYLON;
  45414. (function (BABYLON) {
  45415. var InterpolateValueAction = /** @class */ (function (_super) {
  45416. __extends(InterpolateValueAction, _super);
  45417. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  45418. if (duration === void 0) { duration = 1000; }
  45419. var _this = _super.call(this, triggerOptions, condition) || this;
  45420. _this.propertyPath = propertyPath;
  45421. _this.value = value;
  45422. _this.duration = duration;
  45423. _this.stopOtherAnimations = stopOtherAnimations;
  45424. _this.onInterpolationDone = onInterpolationDone;
  45425. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  45426. _this._target = _this._effectiveTarget = target;
  45427. return _this;
  45428. }
  45429. InterpolateValueAction.prototype._prepare = function () {
  45430. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45431. this._property = this._getProperty(this.propertyPath);
  45432. };
  45433. InterpolateValueAction.prototype.execute = function () {
  45434. var _this = this;
  45435. var scene = this._actionManager.getScene();
  45436. var keys = [
  45437. {
  45438. frame: 0,
  45439. value: this._effectiveTarget[this._property]
  45440. }, {
  45441. frame: 100,
  45442. value: this.value
  45443. }
  45444. ];
  45445. var dataType;
  45446. if (typeof this.value === "number") {
  45447. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  45448. }
  45449. else if (this.value instanceof BABYLON.Color3) {
  45450. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  45451. }
  45452. else if (this.value instanceof BABYLON.Vector3) {
  45453. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  45454. }
  45455. else if (this.value instanceof BABYLON.Matrix) {
  45456. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  45457. }
  45458. else if (this.value instanceof BABYLON.Quaternion) {
  45459. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  45460. }
  45461. else {
  45462. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  45463. return;
  45464. }
  45465. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  45466. animation.setKeys(keys);
  45467. if (this.stopOtherAnimations) {
  45468. scene.stopAnimation(this._effectiveTarget);
  45469. }
  45470. var wrapper = function () {
  45471. _this.onInterpolationDoneObservable.notifyObservers(_this);
  45472. if (_this.onInterpolationDone) {
  45473. _this.onInterpolationDone();
  45474. }
  45475. };
  45476. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  45477. };
  45478. InterpolateValueAction.prototype.serialize = function (parent) {
  45479. return _super.prototype._serialize.call(this, {
  45480. name: "InterpolateValueAction",
  45481. properties: [
  45482. BABYLON.Action._GetTargetProperty(this._target),
  45483. { name: "propertyPath", value: this.propertyPath },
  45484. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45485. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  45486. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  45487. ]
  45488. }, parent);
  45489. };
  45490. return InterpolateValueAction;
  45491. }(BABYLON.Action));
  45492. BABYLON.InterpolateValueAction = InterpolateValueAction;
  45493. })(BABYLON || (BABYLON = {}));
  45494. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  45495. var BABYLON;
  45496. (function (BABYLON) {
  45497. var SwitchBooleanAction = /** @class */ (function (_super) {
  45498. __extends(SwitchBooleanAction, _super);
  45499. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  45500. var _this = _super.call(this, triggerOptions, condition) || this;
  45501. _this.propertyPath = propertyPath;
  45502. _this._target = _this._effectiveTarget = target;
  45503. return _this;
  45504. }
  45505. SwitchBooleanAction.prototype._prepare = function () {
  45506. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45507. this._property = this._getProperty(this.propertyPath);
  45508. };
  45509. SwitchBooleanAction.prototype.execute = function () {
  45510. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  45511. };
  45512. SwitchBooleanAction.prototype.serialize = function (parent) {
  45513. return _super.prototype._serialize.call(this, {
  45514. name: "SwitchBooleanAction",
  45515. properties: [
  45516. BABYLON.Action._GetTargetProperty(this._target),
  45517. { name: "propertyPath", value: this.propertyPath }
  45518. ]
  45519. }, parent);
  45520. };
  45521. return SwitchBooleanAction;
  45522. }(BABYLON.Action));
  45523. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  45524. var SetStateAction = /** @class */ (function (_super) {
  45525. __extends(SetStateAction, _super);
  45526. function SetStateAction(triggerOptions, target, value, condition) {
  45527. var _this = _super.call(this, triggerOptions, condition) || this;
  45528. _this.value = value;
  45529. _this._target = target;
  45530. return _this;
  45531. }
  45532. SetStateAction.prototype.execute = function () {
  45533. this._target.state = this.value;
  45534. };
  45535. SetStateAction.prototype.serialize = function (parent) {
  45536. return _super.prototype._serialize.call(this, {
  45537. name: "SetStateAction",
  45538. properties: [
  45539. BABYLON.Action._GetTargetProperty(this._target),
  45540. { name: "value", value: this.value }
  45541. ]
  45542. }, parent);
  45543. };
  45544. return SetStateAction;
  45545. }(BABYLON.Action));
  45546. BABYLON.SetStateAction = SetStateAction;
  45547. var SetValueAction = /** @class */ (function (_super) {
  45548. __extends(SetValueAction, _super);
  45549. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  45550. var _this = _super.call(this, triggerOptions, condition) || this;
  45551. _this.propertyPath = propertyPath;
  45552. _this.value = value;
  45553. _this._target = _this._effectiveTarget = target;
  45554. return _this;
  45555. }
  45556. SetValueAction.prototype._prepare = function () {
  45557. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45558. this._property = this._getProperty(this.propertyPath);
  45559. };
  45560. SetValueAction.prototype.execute = function () {
  45561. this._effectiveTarget[this._property] = this.value;
  45562. if (this._target.markAsDirty) {
  45563. this._target.markAsDirty(this._property);
  45564. }
  45565. };
  45566. SetValueAction.prototype.serialize = function (parent) {
  45567. return _super.prototype._serialize.call(this, {
  45568. name: "SetValueAction",
  45569. properties: [
  45570. BABYLON.Action._GetTargetProperty(this._target),
  45571. { name: "propertyPath", value: this.propertyPath },
  45572. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45573. ]
  45574. }, parent);
  45575. };
  45576. return SetValueAction;
  45577. }(BABYLON.Action));
  45578. BABYLON.SetValueAction = SetValueAction;
  45579. var IncrementValueAction = /** @class */ (function (_super) {
  45580. __extends(IncrementValueAction, _super);
  45581. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  45582. var _this = _super.call(this, triggerOptions, condition) || this;
  45583. _this.propertyPath = propertyPath;
  45584. _this.value = value;
  45585. _this._target = _this._effectiveTarget = target;
  45586. return _this;
  45587. }
  45588. IncrementValueAction.prototype._prepare = function () {
  45589. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45590. this._property = this._getProperty(this.propertyPath);
  45591. if (typeof this._effectiveTarget[this._property] !== "number") {
  45592. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  45593. }
  45594. };
  45595. IncrementValueAction.prototype.execute = function () {
  45596. this._effectiveTarget[this._property] += this.value;
  45597. if (this._target.markAsDirty) {
  45598. this._target.markAsDirty(this._property);
  45599. }
  45600. };
  45601. IncrementValueAction.prototype.serialize = function (parent) {
  45602. return _super.prototype._serialize.call(this, {
  45603. name: "IncrementValueAction",
  45604. properties: [
  45605. BABYLON.Action._GetTargetProperty(this._target),
  45606. { name: "propertyPath", value: this.propertyPath },
  45607. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45608. ]
  45609. }, parent);
  45610. };
  45611. return IncrementValueAction;
  45612. }(BABYLON.Action));
  45613. BABYLON.IncrementValueAction = IncrementValueAction;
  45614. var PlayAnimationAction = /** @class */ (function (_super) {
  45615. __extends(PlayAnimationAction, _super);
  45616. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  45617. var _this = _super.call(this, triggerOptions, condition) || this;
  45618. _this.from = from;
  45619. _this.to = to;
  45620. _this.loop = loop;
  45621. _this._target = target;
  45622. return _this;
  45623. }
  45624. PlayAnimationAction.prototype._prepare = function () {
  45625. };
  45626. PlayAnimationAction.prototype.execute = function () {
  45627. var scene = this._actionManager.getScene();
  45628. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  45629. };
  45630. PlayAnimationAction.prototype.serialize = function (parent) {
  45631. return _super.prototype._serialize.call(this, {
  45632. name: "PlayAnimationAction",
  45633. properties: [
  45634. BABYLON.Action._GetTargetProperty(this._target),
  45635. { name: "from", value: String(this.from) },
  45636. { name: "to", value: String(this.to) },
  45637. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  45638. ]
  45639. }, parent);
  45640. };
  45641. return PlayAnimationAction;
  45642. }(BABYLON.Action));
  45643. BABYLON.PlayAnimationAction = PlayAnimationAction;
  45644. var StopAnimationAction = /** @class */ (function (_super) {
  45645. __extends(StopAnimationAction, _super);
  45646. function StopAnimationAction(triggerOptions, target, condition) {
  45647. var _this = _super.call(this, triggerOptions, condition) || this;
  45648. _this._target = target;
  45649. return _this;
  45650. }
  45651. StopAnimationAction.prototype._prepare = function () {
  45652. };
  45653. StopAnimationAction.prototype.execute = function () {
  45654. var scene = this._actionManager.getScene();
  45655. scene.stopAnimation(this._target);
  45656. };
  45657. StopAnimationAction.prototype.serialize = function (parent) {
  45658. return _super.prototype._serialize.call(this, {
  45659. name: "StopAnimationAction",
  45660. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  45661. }, parent);
  45662. };
  45663. return StopAnimationAction;
  45664. }(BABYLON.Action));
  45665. BABYLON.StopAnimationAction = StopAnimationAction;
  45666. var DoNothingAction = /** @class */ (function (_super) {
  45667. __extends(DoNothingAction, _super);
  45668. function DoNothingAction(triggerOptions, condition) {
  45669. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  45670. return _super.call(this, triggerOptions, condition) || this;
  45671. }
  45672. DoNothingAction.prototype.execute = function () {
  45673. };
  45674. DoNothingAction.prototype.serialize = function (parent) {
  45675. return _super.prototype._serialize.call(this, {
  45676. name: "DoNothingAction",
  45677. properties: []
  45678. }, parent);
  45679. };
  45680. return DoNothingAction;
  45681. }(BABYLON.Action));
  45682. BABYLON.DoNothingAction = DoNothingAction;
  45683. var CombineAction = /** @class */ (function (_super) {
  45684. __extends(CombineAction, _super);
  45685. function CombineAction(triggerOptions, children, condition) {
  45686. var _this = _super.call(this, triggerOptions, condition) || this;
  45687. _this.children = children;
  45688. return _this;
  45689. }
  45690. CombineAction.prototype._prepare = function () {
  45691. for (var index = 0; index < this.children.length; index++) {
  45692. this.children[index]._actionManager = this._actionManager;
  45693. this.children[index]._prepare();
  45694. }
  45695. };
  45696. CombineAction.prototype.execute = function (evt) {
  45697. for (var index = 0; index < this.children.length; index++) {
  45698. this.children[index].execute(evt);
  45699. }
  45700. };
  45701. CombineAction.prototype.serialize = function (parent) {
  45702. var serializationObject = _super.prototype._serialize.call(this, {
  45703. name: "CombineAction",
  45704. properties: [],
  45705. combine: []
  45706. }, parent);
  45707. for (var i = 0; i < this.children.length; i++) {
  45708. serializationObject.combine.push(this.children[i].serialize(null));
  45709. }
  45710. return serializationObject;
  45711. };
  45712. return CombineAction;
  45713. }(BABYLON.Action));
  45714. BABYLON.CombineAction = CombineAction;
  45715. var ExecuteCodeAction = /** @class */ (function (_super) {
  45716. __extends(ExecuteCodeAction, _super);
  45717. function ExecuteCodeAction(triggerOptions, func, condition) {
  45718. var _this = _super.call(this, triggerOptions, condition) || this;
  45719. _this.func = func;
  45720. return _this;
  45721. }
  45722. ExecuteCodeAction.prototype.execute = function (evt) {
  45723. this.func(evt);
  45724. };
  45725. return ExecuteCodeAction;
  45726. }(BABYLON.Action));
  45727. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  45728. var SetParentAction = /** @class */ (function (_super) {
  45729. __extends(SetParentAction, _super);
  45730. function SetParentAction(triggerOptions, target, parent, condition) {
  45731. var _this = _super.call(this, triggerOptions, condition) || this;
  45732. _this._target = target;
  45733. _this._parent = parent;
  45734. return _this;
  45735. }
  45736. SetParentAction.prototype._prepare = function () {
  45737. };
  45738. SetParentAction.prototype.execute = function () {
  45739. if (this._target.parent === this._parent) {
  45740. return;
  45741. }
  45742. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  45743. invertParentWorldMatrix.invert();
  45744. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  45745. this._target.parent = this._parent;
  45746. };
  45747. SetParentAction.prototype.serialize = function (parent) {
  45748. return _super.prototype._serialize.call(this, {
  45749. name: "SetParentAction",
  45750. properties: [
  45751. BABYLON.Action._GetTargetProperty(this._target),
  45752. BABYLON.Action._GetTargetProperty(this._parent),
  45753. ]
  45754. }, parent);
  45755. };
  45756. return SetParentAction;
  45757. }(BABYLON.Action));
  45758. BABYLON.SetParentAction = SetParentAction;
  45759. var PlaySoundAction = /** @class */ (function (_super) {
  45760. __extends(PlaySoundAction, _super);
  45761. function PlaySoundAction(triggerOptions, sound, condition) {
  45762. var _this = _super.call(this, triggerOptions, condition) || this;
  45763. _this._sound = sound;
  45764. return _this;
  45765. }
  45766. PlaySoundAction.prototype._prepare = function () {
  45767. };
  45768. PlaySoundAction.prototype.execute = function () {
  45769. if (this._sound !== undefined)
  45770. this._sound.play();
  45771. };
  45772. PlaySoundAction.prototype.serialize = function (parent) {
  45773. return _super.prototype._serialize.call(this, {
  45774. name: "PlaySoundAction",
  45775. properties: [{ name: "sound", value: this._sound.name }]
  45776. }, parent);
  45777. };
  45778. return PlaySoundAction;
  45779. }(BABYLON.Action));
  45780. BABYLON.PlaySoundAction = PlaySoundAction;
  45781. var StopSoundAction = /** @class */ (function (_super) {
  45782. __extends(StopSoundAction, _super);
  45783. function StopSoundAction(triggerOptions, sound, condition) {
  45784. var _this = _super.call(this, triggerOptions, condition) || this;
  45785. _this._sound = sound;
  45786. return _this;
  45787. }
  45788. StopSoundAction.prototype._prepare = function () {
  45789. };
  45790. StopSoundAction.prototype.execute = function () {
  45791. if (this._sound !== undefined)
  45792. this._sound.stop();
  45793. };
  45794. StopSoundAction.prototype.serialize = function (parent) {
  45795. return _super.prototype._serialize.call(this, {
  45796. name: "StopSoundAction",
  45797. properties: [{ name: "sound", value: this._sound.name }]
  45798. }, parent);
  45799. };
  45800. return StopSoundAction;
  45801. }(BABYLON.Action));
  45802. BABYLON.StopSoundAction = StopSoundAction;
  45803. })(BABYLON || (BABYLON = {}));
  45804. //# sourceMappingURL=babylon.directActions.js.map
  45805. var BABYLON;
  45806. (function (BABYLON) {
  45807. var SpriteManager = /** @class */ (function () {
  45808. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  45809. if (epsilon === void 0) { epsilon = 0.01; }
  45810. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45811. this.name = name;
  45812. this.sprites = new Array();
  45813. this.renderingGroupId = 0;
  45814. this.layerMask = 0x0FFFFFFF;
  45815. this.fogEnabled = true;
  45816. this.isPickable = false;
  45817. /**
  45818. * An event triggered when the manager is disposed.
  45819. * @type {BABYLON.Observable}
  45820. */
  45821. this.onDisposeObservable = new BABYLON.Observable();
  45822. this._vertexBuffers = {};
  45823. this._capacity = capacity;
  45824. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  45825. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45826. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45827. if (cellSize.width && cellSize.height) {
  45828. this.cellWidth = cellSize.width;
  45829. this.cellHeight = cellSize.height;
  45830. }
  45831. else if (cellSize !== undefined) {
  45832. this.cellWidth = cellSize;
  45833. this.cellHeight = cellSize;
  45834. }
  45835. else {
  45836. return;
  45837. }
  45838. this._epsilon = epsilon;
  45839. this._scene = scene;
  45840. this._scene.spriteManagers.push(this);
  45841. var indices = [];
  45842. var index = 0;
  45843. for (var count = 0; count < capacity; count++) {
  45844. indices.push(index);
  45845. indices.push(index + 1);
  45846. indices.push(index + 2);
  45847. indices.push(index);
  45848. indices.push(index + 2);
  45849. indices.push(index + 3);
  45850. index += 4;
  45851. }
  45852. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  45853. // VBO
  45854. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  45855. this._vertexData = new Float32Array(capacity * 16 * 4);
  45856. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  45857. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  45858. var options = this._buffer.createVertexBuffer("options", 4, 4);
  45859. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  45860. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  45861. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45862. this._vertexBuffers["options"] = options;
  45863. this._vertexBuffers["cellInfo"] = cellInfo;
  45864. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45865. // Effects
  45866. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  45867. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  45868. }
  45869. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  45870. set: function (callback) {
  45871. if (this._onDisposeObserver) {
  45872. this.onDisposeObservable.remove(this._onDisposeObserver);
  45873. }
  45874. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45875. },
  45876. enumerable: true,
  45877. configurable: true
  45878. });
  45879. Object.defineProperty(SpriteManager.prototype, "texture", {
  45880. get: function () {
  45881. return this._spriteTexture;
  45882. },
  45883. set: function (value) {
  45884. this._spriteTexture = value;
  45885. },
  45886. enumerable: true,
  45887. configurable: true
  45888. });
  45889. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  45890. var arrayOffset = index * 16;
  45891. if (offsetX === 0)
  45892. offsetX = this._epsilon;
  45893. else if (offsetX === 1)
  45894. offsetX = 1 - this._epsilon;
  45895. if (offsetY === 0)
  45896. offsetY = this._epsilon;
  45897. else if (offsetY === 1)
  45898. offsetY = 1 - this._epsilon;
  45899. this._vertexData[arrayOffset] = sprite.position.x;
  45900. this._vertexData[arrayOffset + 1] = sprite.position.y;
  45901. this._vertexData[arrayOffset + 2] = sprite.position.z;
  45902. this._vertexData[arrayOffset + 3] = sprite.angle;
  45903. this._vertexData[arrayOffset + 4] = sprite.width;
  45904. this._vertexData[arrayOffset + 5] = sprite.height;
  45905. this._vertexData[arrayOffset + 6] = offsetX;
  45906. this._vertexData[arrayOffset + 7] = offsetY;
  45907. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  45908. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  45909. var offset = (sprite.cellIndex / rowSize) >> 0;
  45910. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  45911. this._vertexData[arrayOffset + 11] = offset;
  45912. // Color
  45913. this._vertexData[arrayOffset + 12] = sprite.color.r;
  45914. this._vertexData[arrayOffset + 13] = sprite.color.g;
  45915. this._vertexData[arrayOffset + 14] = sprite.color.b;
  45916. this._vertexData[arrayOffset + 15] = sprite.color.a;
  45917. };
  45918. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  45919. var count = Math.min(this._capacity, this.sprites.length);
  45920. var min = BABYLON.Vector3.Zero();
  45921. var max = BABYLON.Vector3.Zero();
  45922. var distance = Number.MAX_VALUE;
  45923. var currentSprite = null;
  45924. var cameraSpacePosition = BABYLON.Vector3.Zero();
  45925. var cameraView = camera.getViewMatrix();
  45926. for (var index = 0; index < count; index++) {
  45927. var sprite = this.sprites[index];
  45928. if (!sprite) {
  45929. continue;
  45930. }
  45931. if (predicate) {
  45932. if (!predicate(sprite)) {
  45933. continue;
  45934. }
  45935. }
  45936. else if (!sprite.isPickable) {
  45937. continue;
  45938. }
  45939. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  45940. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  45941. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  45942. if (ray.intersectsBoxMinMax(min, max)) {
  45943. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  45944. if (distance > currentDistance) {
  45945. distance = currentDistance;
  45946. currentSprite = sprite;
  45947. if (fastCheck) {
  45948. break;
  45949. }
  45950. }
  45951. }
  45952. }
  45953. if (currentSprite) {
  45954. var result = new BABYLON.PickingInfo();
  45955. result.hit = true;
  45956. result.pickedSprite = currentSprite;
  45957. result.distance = distance;
  45958. return result;
  45959. }
  45960. return null;
  45961. };
  45962. SpriteManager.prototype.render = function () {
  45963. // Check
  45964. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  45965. return;
  45966. var engine = this._scene.getEngine();
  45967. var baseSize = this._spriteTexture.getBaseSize();
  45968. // Sprites
  45969. var deltaTime = engine.getDeltaTime();
  45970. var max = Math.min(this._capacity, this.sprites.length);
  45971. var rowSize = baseSize.width / this.cellWidth;
  45972. var offset = 0;
  45973. for (var index = 0; index < max; index++) {
  45974. var sprite = this.sprites[index];
  45975. if (!sprite) {
  45976. continue;
  45977. }
  45978. sprite._animate(deltaTime);
  45979. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  45980. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  45981. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  45982. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  45983. }
  45984. this._buffer.update(this._vertexData);
  45985. // Render
  45986. var effect = this._effectBase;
  45987. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45988. effect = this._effectFog;
  45989. }
  45990. engine.enableEffect(effect);
  45991. var viewMatrix = this._scene.getViewMatrix();
  45992. effect.setTexture("diffuseSampler", this._spriteTexture);
  45993. effect.setMatrix("view", viewMatrix);
  45994. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45995. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  45996. // Fog
  45997. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45998. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  45999. effect.setColor3("vFogColor", this._scene.fogColor);
  46000. }
  46001. // VBOs
  46002. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46003. // Draw order
  46004. engine.setDepthFunctionToLessOrEqual();
  46005. effect.setBool("alphaTest", true);
  46006. engine.setColorWrite(false);
  46007. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46008. engine.setColorWrite(true);
  46009. effect.setBool("alphaTest", false);
  46010. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46011. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46012. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46013. };
  46014. SpriteManager.prototype.dispose = function () {
  46015. if (this._buffer) {
  46016. this._buffer.dispose();
  46017. this._buffer = null;
  46018. }
  46019. if (this._indexBuffer) {
  46020. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46021. this._indexBuffer = null;
  46022. }
  46023. if (this._spriteTexture) {
  46024. this._spriteTexture.dispose();
  46025. this._spriteTexture = null;
  46026. }
  46027. // Remove from scene
  46028. var index = this._scene.spriteManagers.indexOf(this);
  46029. this._scene.spriteManagers.splice(index, 1);
  46030. // Callback
  46031. this.onDisposeObservable.notifyObservers(this);
  46032. this.onDisposeObservable.clear();
  46033. };
  46034. return SpriteManager;
  46035. }());
  46036. BABYLON.SpriteManager = SpriteManager;
  46037. })(BABYLON || (BABYLON = {}));
  46038. //# sourceMappingURL=babylon.spriteManager.js.map
  46039. var BABYLON;
  46040. (function (BABYLON) {
  46041. var Sprite = /** @class */ (function () {
  46042. function Sprite(name, manager) {
  46043. this.name = name;
  46044. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46045. this.width = 1.0;
  46046. this.height = 1.0;
  46047. this.angle = 0;
  46048. this.cellIndex = 0;
  46049. this.invertU = 0;
  46050. this.invertV = 0;
  46051. this.animations = new Array();
  46052. this.isPickable = false;
  46053. this._animationStarted = false;
  46054. this._loopAnimation = false;
  46055. this._fromIndex = 0;
  46056. this._toIndex = 0;
  46057. this._delay = 0;
  46058. this._direction = 1;
  46059. this._time = 0;
  46060. this._manager = manager;
  46061. this._manager.sprites.push(this);
  46062. this.position = BABYLON.Vector3.Zero();
  46063. }
  46064. Object.defineProperty(Sprite.prototype, "size", {
  46065. get: function () {
  46066. return this.width;
  46067. },
  46068. set: function (value) {
  46069. this.width = value;
  46070. this.height = value;
  46071. },
  46072. enumerable: true,
  46073. configurable: true
  46074. });
  46075. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  46076. this._fromIndex = from;
  46077. this._toIndex = to;
  46078. this._loopAnimation = loop;
  46079. this._delay = delay;
  46080. this._animationStarted = true;
  46081. this._direction = from < to ? 1 : -1;
  46082. this.cellIndex = from;
  46083. this._time = 0;
  46084. this._onAnimationEnd = onAnimationEnd;
  46085. };
  46086. Sprite.prototype.stopAnimation = function () {
  46087. this._animationStarted = false;
  46088. };
  46089. Sprite.prototype._animate = function (deltaTime) {
  46090. if (!this._animationStarted)
  46091. return;
  46092. this._time += deltaTime;
  46093. if (this._time > this._delay) {
  46094. this._time = this._time % this._delay;
  46095. this.cellIndex += this._direction;
  46096. if (this.cellIndex > this._toIndex) {
  46097. if (this._loopAnimation) {
  46098. this.cellIndex = this._fromIndex;
  46099. }
  46100. else {
  46101. this.cellIndex = this._toIndex;
  46102. this._animationStarted = false;
  46103. if (this._onAnimationEnd) {
  46104. this._onAnimationEnd();
  46105. }
  46106. if (this.disposeWhenFinishedAnimating) {
  46107. this.dispose();
  46108. }
  46109. }
  46110. }
  46111. }
  46112. };
  46113. Sprite.prototype.dispose = function () {
  46114. for (var i = 0; i < this._manager.sprites.length; i++) {
  46115. if (this._manager.sprites[i] == this) {
  46116. this._manager.sprites.splice(i, 1);
  46117. }
  46118. }
  46119. };
  46120. return Sprite;
  46121. }());
  46122. BABYLON.Sprite = Sprite;
  46123. })(BABYLON || (BABYLON = {}));
  46124. //# sourceMappingURL=babylon.sprite.js.map
  46125. var BABYLON;
  46126. (function (BABYLON) {
  46127. var IntersectionInfo = /** @class */ (function () {
  46128. function IntersectionInfo(bu, bv, distance) {
  46129. this.bu = bu;
  46130. this.bv = bv;
  46131. this.distance = distance;
  46132. this.faceId = 0;
  46133. this.subMeshId = 0;
  46134. }
  46135. return IntersectionInfo;
  46136. }());
  46137. BABYLON.IntersectionInfo = IntersectionInfo;
  46138. var PickingInfo = /** @class */ (function () {
  46139. function PickingInfo() {
  46140. this.hit = false;
  46141. this.distance = 0;
  46142. this.pickedPoint = null;
  46143. this.pickedMesh = null;
  46144. this.bu = 0;
  46145. this.bv = 0;
  46146. this.faceId = -1;
  46147. this.subMeshId = 0;
  46148. this.pickedSprite = null;
  46149. }
  46150. // Methods
  46151. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  46152. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  46153. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  46154. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46155. return null;
  46156. }
  46157. var indices = this.pickedMesh.getIndices();
  46158. if (!indices) {
  46159. return null;
  46160. }
  46161. var result;
  46162. if (useVerticesNormals) {
  46163. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46164. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  46165. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  46166. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  46167. normal0 = normal0.scale(this.bu);
  46168. normal1 = normal1.scale(this.bv);
  46169. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  46170. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  46171. }
  46172. else {
  46173. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46174. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  46175. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  46176. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  46177. var p1p2 = vertex1.subtract(vertex2);
  46178. var p3p2 = vertex3.subtract(vertex2);
  46179. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  46180. }
  46181. if (useWorldCoordinates) {
  46182. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  46183. }
  46184. return BABYLON.Vector3.Normalize(result);
  46185. };
  46186. PickingInfo.prototype.getTextureCoordinates = function () {
  46187. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46188. return null;
  46189. }
  46190. var indices = this.pickedMesh.getIndices();
  46191. if (!indices) {
  46192. return null;
  46193. }
  46194. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46195. if (!uvs) {
  46196. return null;
  46197. }
  46198. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  46199. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  46200. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  46201. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  46202. uv1 = uv1.scale(this.bu);
  46203. uv2 = uv2.scale(this.bv);
  46204. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  46205. };
  46206. return PickingInfo;
  46207. }());
  46208. BABYLON.PickingInfo = PickingInfo;
  46209. })(BABYLON || (BABYLON = {}));
  46210. //# sourceMappingURL=babylon.pickingInfo.js.map
  46211. var BABYLON;
  46212. (function (BABYLON) {
  46213. var Ray = /** @class */ (function () {
  46214. function Ray(origin, direction, length) {
  46215. if (length === void 0) { length = Number.MAX_VALUE; }
  46216. this.origin = origin;
  46217. this.direction = direction;
  46218. this.length = length;
  46219. }
  46220. // Methods
  46221. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  46222. var d = 0.0;
  46223. var maxValue = Number.MAX_VALUE;
  46224. var inv;
  46225. var min;
  46226. var max;
  46227. var temp;
  46228. if (Math.abs(this.direction.x) < 0.0000001) {
  46229. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  46230. return false;
  46231. }
  46232. }
  46233. else {
  46234. inv = 1.0 / this.direction.x;
  46235. min = (minimum.x - this.origin.x) * inv;
  46236. max = (maximum.x - this.origin.x) * inv;
  46237. if (max === -Infinity) {
  46238. max = Infinity;
  46239. }
  46240. if (min > max) {
  46241. temp = min;
  46242. min = max;
  46243. max = temp;
  46244. }
  46245. d = Math.max(min, d);
  46246. maxValue = Math.min(max, maxValue);
  46247. if (d > maxValue) {
  46248. return false;
  46249. }
  46250. }
  46251. if (Math.abs(this.direction.y) < 0.0000001) {
  46252. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  46253. return false;
  46254. }
  46255. }
  46256. else {
  46257. inv = 1.0 / this.direction.y;
  46258. min = (minimum.y - this.origin.y) * inv;
  46259. max = (maximum.y - this.origin.y) * inv;
  46260. if (max === -Infinity) {
  46261. max = Infinity;
  46262. }
  46263. if (min > max) {
  46264. temp = min;
  46265. min = max;
  46266. max = temp;
  46267. }
  46268. d = Math.max(min, d);
  46269. maxValue = Math.min(max, maxValue);
  46270. if (d > maxValue) {
  46271. return false;
  46272. }
  46273. }
  46274. if (Math.abs(this.direction.z) < 0.0000001) {
  46275. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  46276. return false;
  46277. }
  46278. }
  46279. else {
  46280. inv = 1.0 / this.direction.z;
  46281. min = (minimum.z - this.origin.z) * inv;
  46282. max = (maximum.z - this.origin.z) * inv;
  46283. if (max === -Infinity) {
  46284. max = Infinity;
  46285. }
  46286. if (min > max) {
  46287. temp = min;
  46288. min = max;
  46289. max = temp;
  46290. }
  46291. d = Math.max(min, d);
  46292. maxValue = Math.min(max, maxValue);
  46293. if (d > maxValue) {
  46294. return false;
  46295. }
  46296. }
  46297. return true;
  46298. };
  46299. Ray.prototype.intersectsBox = function (box) {
  46300. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  46301. };
  46302. Ray.prototype.intersectsSphere = function (sphere) {
  46303. var x = sphere.center.x - this.origin.x;
  46304. var y = sphere.center.y - this.origin.y;
  46305. var z = sphere.center.z - this.origin.z;
  46306. var pyth = (x * x) + (y * y) + (z * z);
  46307. var rr = sphere.radius * sphere.radius;
  46308. if (pyth <= rr) {
  46309. return true;
  46310. }
  46311. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  46312. if (dot < 0.0) {
  46313. return false;
  46314. }
  46315. var temp = pyth - (dot * dot);
  46316. return temp <= rr;
  46317. };
  46318. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  46319. if (!this._edge1) {
  46320. this._edge1 = BABYLON.Vector3.Zero();
  46321. this._edge2 = BABYLON.Vector3.Zero();
  46322. this._pvec = BABYLON.Vector3.Zero();
  46323. this._tvec = BABYLON.Vector3.Zero();
  46324. this._qvec = BABYLON.Vector3.Zero();
  46325. }
  46326. vertex1.subtractToRef(vertex0, this._edge1);
  46327. vertex2.subtractToRef(vertex0, this._edge2);
  46328. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  46329. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  46330. if (det === 0) {
  46331. return null;
  46332. }
  46333. var invdet = 1 / det;
  46334. this.origin.subtractToRef(vertex0, this._tvec);
  46335. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  46336. if (bu < 0 || bu > 1.0) {
  46337. return null;
  46338. }
  46339. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  46340. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  46341. if (bv < 0 || bu + bv > 1.0) {
  46342. return null;
  46343. }
  46344. //check if the distance is longer than the predefined length.
  46345. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  46346. if (distance > this.length) {
  46347. return null;
  46348. }
  46349. return new BABYLON.IntersectionInfo(bu, bv, distance);
  46350. };
  46351. Ray.prototype.intersectsPlane = function (plane) {
  46352. var distance;
  46353. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  46354. if (Math.abs(result1) < 9.99999997475243E-07) {
  46355. return null;
  46356. }
  46357. else {
  46358. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  46359. distance = (-plane.d - result2) / result1;
  46360. if (distance < 0.0) {
  46361. if (distance < -9.99999997475243E-07) {
  46362. return null;
  46363. }
  46364. else {
  46365. return 0;
  46366. }
  46367. }
  46368. return distance;
  46369. }
  46370. };
  46371. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  46372. var tm = BABYLON.Tmp.Matrix[0];
  46373. mesh.getWorldMatrix().invertToRef(tm);
  46374. if (this._tmpRay) {
  46375. Ray.TransformToRef(this, tm, this._tmpRay);
  46376. }
  46377. else {
  46378. this._tmpRay = Ray.Transform(this, tm);
  46379. }
  46380. return mesh.intersects(this._tmpRay, fastCheck);
  46381. };
  46382. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  46383. if (results) {
  46384. results.length = 0;
  46385. }
  46386. else {
  46387. results = [];
  46388. }
  46389. for (var i = 0; i < meshes.length; i++) {
  46390. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  46391. if (pickInfo.hit) {
  46392. results.push(pickInfo);
  46393. }
  46394. }
  46395. results.sort(this._comparePickingInfo);
  46396. return results;
  46397. };
  46398. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  46399. if (pickingInfoA.distance < pickingInfoB.distance) {
  46400. return -1;
  46401. }
  46402. else if (pickingInfoA.distance > pickingInfoB.distance) {
  46403. return 1;
  46404. }
  46405. else {
  46406. return 0;
  46407. }
  46408. };
  46409. /**
  46410. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  46411. * @param sega the first point of the segment to test the intersection against
  46412. * @param segb the second point of the segment to test the intersection against
  46413. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  46414. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  46415. */
  46416. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  46417. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  46418. var u = segb.subtract(sega);
  46419. var v = rsegb.subtract(this.origin);
  46420. var w = sega.subtract(this.origin);
  46421. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  46422. var b = BABYLON.Vector3.Dot(u, v);
  46423. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  46424. var d = BABYLON.Vector3.Dot(u, w);
  46425. var e = BABYLON.Vector3.Dot(v, w);
  46426. var D = a * c - b * b; // always >= 0
  46427. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  46428. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  46429. // compute the line parameters of the two closest points
  46430. if (D < Ray.smallnum) {
  46431. sN = 0.0; // force using point P0 on segment S1
  46432. sD = 1.0; // to prevent possible division by 0.0 later
  46433. tN = e;
  46434. tD = c;
  46435. }
  46436. else {
  46437. sN = (b * e - c * d);
  46438. tN = (a * e - b * d);
  46439. if (sN < 0.0) {
  46440. sN = 0.0;
  46441. tN = e;
  46442. tD = c;
  46443. }
  46444. else if (sN > sD) {
  46445. sN = sD;
  46446. tN = e + b;
  46447. tD = c;
  46448. }
  46449. }
  46450. if (tN < 0.0) {
  46451. tN = 0.0;
  46452. // recompute sc for this edge
  46453. if (-d < 0.0) {
  46454. sN = 0.0;
  46455. }
  46456. else if (-d > a)
  46457. sN = sD;
  46458. else {
  46459. sN = -d;
  46460. sD = a;
  46461. }
  46462. }
  46463. else if (tN > tD) {
  46464. tN = tD;
  46465. // recompute sc for this edge
  46466. if ((-d + b) < 0.0) {
  46467. sN = 0;
  46468. }
  46469. else if ((-d + b) > a) {
  46470. sN = sD;
  46471. }
  46472. else {
  46473. sN = (-d + b);
  46474. sD = a;
  46475. }
  46476. }
  46477. // finally do the division to get sc and tc
  46478. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  46479. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  46480. // get the difference of the two closest points
  46481. var qtc = v.multiplyByFloats(tc, tc, tc);
  46482. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  46483. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  46484. if (isIntersected) {
  46485. return qtc.length();
  46486. }
  46487. return -1;
  46488. };
  46489. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46490. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  46491. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  46492. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  46493. this.direction.normalize();
  46494. return this;
  46495. };
  46496. // Statics
  46497. Ray.Zero = function () {
  46498. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  46499. };
  46500. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46501. var result = Ray.Zero();
  46502. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  46503. };
  46504. /**
  46505. * 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
  46506. * transformed to the given world matrix.
  46507. * @param origin The origin point
  46508. * @param end The end point
  46509. * @param world a matrix to transform the ray to. Default is the identity matrix.
  46510. */
  46511. Ray.CreateNewFromTo = function (origin, end, world) {
  46512. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  46513. var direction = end.subtract(origin);
  46514. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  46515. direction.normalize();
  46516. return Ray.Transform(new Ray(origin, direction, length), world);
  46517. };
  46518. Ray.Transform = function (ray, matrix) {
  46519. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  46520. Ray.TransformToRef(ray, matrix, result);
  46521. return result;
  46522. };
  46523. Ray.TransformToRef = function (ray, matrix, result) {
  46524. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  46525. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  46526. result.length = ray.length;
  46527. var dir = result.direction;
  46528. var len = dir.length();
  46529. if (!(len === 0 || len === 1)) {
  46530. var num = 1.0 / len;
  46531. dir.x *= num;
  46532. dir.y *= num;
  46533. dir.z *= num;
  46534. result.length *= len;
  46535. }
  46536. };
  46537. Ray.smallnum = 0.00000001;
  46538. Ray.rayl = 10e8;
  46539. return Ray;
  46540. }());
  46541. BABYLON.Ray = Ray;
  46542. })(BABYLON || (BABYLON = {}));
  46543. //# sourceMappingURL=babylon.ray.js.map
  46544. var BABYLON;
  46545. (function (BABYLON) {
  46546. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  46547. if (boxMin.x > sphereCenter.x + sphereRadius)
  46548. return false;
  46549. if (sphereCenter.x - sphereRadius > boxMax.x)
  46550. return false;
  46551. if (boxMin.y > sphereCenter.y + sphereRadius)
  46552. return false;
  46553. if (sphereCenter.y - sphereRadius > boxMax.y)
  46554. return false;
  46555. if (boxMin.z > sphereCenter.z + sphereRadius)
  46556. return false;
  46557. if (sphereCenter.z - sphereRadius > boxMax.z)
  46558. return false;
  46559. return true;
  46560. };
  46561. var getLowestRoot = (function () {
  46562. var result = { root: 0, found: false };
  46563. return function (a, b, c, maxR) {
  46564. result.root = 0;
  46565. result.found = false;
  46566. var determinant = b * b - 4.0 * a * c;
  46567. if (determinant < 0)
  46568. return result;
  46569. var sqrtD = Math.sqrt(determinant);
  46570. var r1 = (-b - sqrtD) / (2.0 * a);
  46571. var r2 = (-b + sqrtD) / (2.0 * a);
  46572. if (r1 > r2) {
  46573. var temp = r2;
  46574. r2 = r1;
  46575. r1 = temp;
  46576. }
  46577. if (r1 > 0 && r1 < maxR) {
  46578. result.root = r1;
  46579. result.found = true;
  46580. return result;
  46581. }
  46582. if (r2 > 0 && r2 < maxR) {
  46583. result.root = r2;
  46584. result.found = true;
  46585. return result;
  46586. }
  46587. return result;
  46588. };
  46589. })();
  46590. var Collider = /** @class */ (function () {
  46591. function Collider() {
  46592. this._collisionPoint = BABYLON.Vector3.Zero();
  46593. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  46594. this._tempVector = BABYLON.Vector3.Zero();
  46595. this._tempVector2 = BABYLON.Vector3.Zero();
  46596. this._tempVector3 = BABYLON.Vector3.Zero();
  46597. this._tempVector4 = BABYLON.Vector3.Zero();
  46598. this._edge = BABYLON.Vector3.Zero();
  46599. this._baseToVertex = BABYLON.Vector3.Zero();
  46600. this._destinationPoint = BABYLON.Vector3.Zero();
  46601. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  46602. this._displacementVector = BABYLON.Vector3.Zero();
  46603. this._radius = BABYLON.Vector3.One();
  46604. this._retry = 0;
  46605. this._basePointWorld = BABYLON.Vector3.Zero();
  46606. this._velocityWorld = BABYLON.Vector3.Zero();
  46607. this._normalizedVelocity = BABYLON.Vector3.Zero();
  46608. this._collisionMask = -1;
  46609. }
  46610. Object.defineProperty(Collider.prototype, "collisionMask", {
  46611. get: function () {
  46612. return this._collisionMask;
  46613. },
  46614. set: function (mask) {
  46615. this._collisionMask = !isNaN(mask) ? mask : -1;
  46616. },
  46617. enumerable: true,
  46618. configurable: true
  46619. });
  46620. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  46621. /**
  46622. * Gets the plane normal used to compute the sliding response (in local space)
  46623. */
  46624. get: function () {
  46625. return this._slidePlaneNormal;
  46626. },
  46627. enumerable: true,
  46628. configurable: true
  46629. });
  46630. // Methods
  46631. Collider.prototype._initialize = function (source, dir, e) {
  46632. this._velocity = dir;
  46633. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  46634. this._basePoint = source;
  46635. source.multiplyToRef(this._radius, this._basePointWorld);
  46636. dir.multiplyToRef(this._radius, this._velocityWorld);
  46637. this._velocityWorldLength = this._velocityWorld.length();
  46638. this._epsilon = e;
  46639. this.collisionFound = false;
  46640. };
  46641. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  46642. pa.subtractToRef(point, this._tempVector);
  46643. pb.subtractToRef(point, this._tempVector2);
  46644. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  46645. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46646. if (d < 0)
  46647. return false;
  46648. pc.subtractToRef(point, this._tempVector3);
  46649. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  46650. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46651. if (d < 0)
  46652. return false;
  46653. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  46654. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46655. return d >= 0;
  46656. };
  46657. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  46658. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  46659. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  46660. if (distance > this._velocityWorldLength + max + sphereRadius) {
  46661. return false;
  46662. }
  46663. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  46664. return false;
  46665. return true;
  46666. };
  46667. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  46668. var t0;
  46669. var embeddedInPlane = false;
  46670. //defensive programming, actually not needed.
  46671. if (!trianglePlaneArray) {
  46672. trianglePlaneArray = [];
  46673. }
  46674. if (!trianglePlaneArray[faceIndex]) {
  46675. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  46676. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  46677. }
  46678. var trianglePlane = trianglePlaneArray[faceIndex];
  46679. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  46680. return;
  46681. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  46682. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  46683. if (normalDotVelocity == 0) {
  46684. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  46685. return;
  46686. embeddedInPlane = true;
  46687. t0 = 0;
  46688. }
  46689. else {
  46690. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46691. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46692. if (t0 > t1) {
  46693. var temp = t1;
  46694. t1 = t0;
  46695. t0 = temp;
  46696. }
  46697. if (t0 > 1.0 || t1 < 0.0)
  46698. return;
  46699. if (t0 < 0)
  46700. t0 = 0;
  46701. if (t0 > 1.0)
  46702. t0 = 1.0;
  46703. }
  46704. this._collisionPoint.copyFromFloats(0, 0, 0);
  46705. var found = false;
  46706. var t = 1.0;
  46707. if (!embeddedInPlane) {
  46708. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  46709. this._velocity.scaleToRef(t0, this._tempVector);
  46710. this._planeIntersectionPoint.addInPlace(this._tempVector);
  46711. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  46712. found = true;
  46713. t = t0;
  46714. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  46715. }
  46716. }
  46717. if (!found) {
  46718. var velocitySquaredLength = this._velocity.lengthSquared();
  46719. var a = velocitySquaredLength;
  46720. this._basePoint.subtractToRef(p1, this._tempVector);
  46721. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46722. var c = this._tempVector.lengthSquared() - 1.0;
  46723. var lowestRoot = getLowestRoot(a, b, c, t);
  46724. if (lowestRoot.found) {
  46725. t = lowestRoot.root;
  46726. found = true;
  46727. this._collisionPoint.copyFrom(p1);
  46728. }
  46729. this._basePoint.subtractToRef(p2, this._tempVector);
  46730. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46731. c = this._tempVector.lengthSquared() - 1.0;
  46732. lowestRoot = getLowestRoot(a, b, c, t);
  46733. if (lowestRoot.found) {
  46734. t = lowestRoot.root;
  46735. found = true;
  46736. this._collisionPoint.copyFrom(p2);
  46737. }
  46738. this._basePoint.subtractToRef(p3, this._tempVector);
  46739. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46740. c = this._tempVector.lengthSquared() - 1.0;
  46741. lowestRoot = getLowestRoot(a, b, c, t);
  46742. if (lowestRoot.found) {
  46743. t = lowestRoot.root;
  46744. found = true;
  46745. this._collisionPoint.copyFrom(p3);
  46746. }
  46747. p2.subtractToRef(p1, this._edge);
  46748. p1.subtractToRef(this._basePoint, this._baseToVertex);
  46749. var edgeSquaredLength = this._edge.lengthSquared();
  46750. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46751. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46752. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46753. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46754. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46755. lowestRoot = getLowestRoot(a, b, c, t);
  46756. if (lowestRoot.found) {
  46757. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46758. if (f >= 0.0 && f <= 1.0) {
  46759. t = lowestRoot.root;
  46760. found = true;
  46761. this._edge.scaleInPlace(f);
  46762. p1.addToRef(this._edge, this._collisionPoint);
  46763. }
  46764. }
  46765. p3.subtractToRef(p2, this._edge);
  46766. p2.subtractToRef(this._basePoint, this._baseToVertex);
  46767. edgeSquaredLength = this._edge.lengthSquared();
  46768. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46769. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46770. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46771. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46772. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46773. lowestRoot = getLowestRoot(a, b, c, t);
  46774. if (lowestRoot.found) {
  46775. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46776. if (f >= 0.0 && f <= 1.0) {
  46777. t = lowestRoot.root;
  46778. found = true;
  46779. this._edge.scaleInPlace(f);
  46780. p2.addToRef(this._edge, this._collisionPoint);
  46781. }
  46782. }
  46783. p1.subtractToRef(p3, this._edge);
  46784. p3.subtractToRef(this._basePoint, this._baseToVertex);
  46785. edgeSquaredLength = this._edge.lengthSquared();
  46786. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46787. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46788. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46789. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46790. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46791. lowestRoot = getLowestRoot(a, b, c, t);
  46792. if (lowestRoot.found) {
  46793. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46794. if (f >= 0.0 && f <= 1.0) {
  46795. t = lowestRoot.root;
  46796. found = true;
  46797. this._edge.scaleInPlace(f);
  46798. p3.addToRef(this._edge, this._collisionPoint);
  46799. }
  46800. }
  46801. }
  46802. if (found) {
  46803. var distToCollision = t * this._velocity.length();
  46804. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  46805. if (!this.intersectionPoint) {
  46806. this.intersectionPoint = this._collisionPoint.clone();
  46807. }
  46808. else {
  46809. this.intersectionPoint.copyFrom(this._collisionPoint);
  46810. }
  46811. this._nearestDistance = distToCollision;
  46812. this.collisionFound = true;
  46813. }
  46814. }
  46815. };
  46816. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  46817. for (var i = indexStart; i < indexEnd; i += 3) {
  46818. var p1 = pts[indices[i] - decal];
  46819. var p2 = pts[indices[i + 1] - decal];
  46820. var p3 = pts[indices[i + 2] - decal];
  46821. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  46822. }
  46823. };
  46824. Collider.prototype._getResponse = function (pos, vel) {
  46825. pos.addToRef(vel, this._destinationPoint);
  46826. vel.scaleInPlace((this._nearestDistance / vel.length()));
  46827. this._basePoint.addToRef(vel, pos);
  46828. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  46829. this._slidePlaneNormal.normalize();
  46830. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  46831. pos.addInPlace(this._displacementVector);
  46832. this.intersectionPoint.addInPlace(this._displacementVector);
  46833. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  46834. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  46835. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  46836. };
  46837. return Collider;
  46838. }());
  46839. BABYLON.Collider = Collider;
  46840. })(BABYLON || (BABYLON = {}));
  46841. //# sourceMappingURL=babylon.collider.js.map
  46842. var BABYLON;
  46843. (function (BABYLON) {
  46844. //WebWorker code will be inserted to this variable.
  46845. BABYLON.CollisionWorker = "";
  46846. var WorkerTaskType;
  46847. (function (WorkerTaskType) {
  46848. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  46849. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  46850. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  46851. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  46852. var WorkerReplyType;
  46853. (function (WorkerReplyType) {
  46854. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  46855. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  46856. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  46857. var CollisionCoordinatorWorker = /** @class */ (function () {
  46858. function CollisionCoordinatorWorker() {
  46859. var _this = this;
  46860. this._scaledPosition = BABYLON.Vector3.Zero();
  46861. this._scaledVelocity = BABYLON.Vector3.Zero();
  46862. this.onMeshUpdated = function (transformNode) {
  46863. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  46864. };
  46865. this.onGeometryUpdated = function (geometry) {
  46866. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  46867. };
  46868. this._afterRender = function () {
  46869. if (!_this._init)
  46870. return;
  46871. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  46872. return;
  46873. }
  46874. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  46875. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  46876. if (_this._runningUpdated > 4) {
  46877. return;
  46878. }
  46879. ++_this._runningUpdated;
  46880. var payload = {
  46881. updatedMeshes: _this._addUpdateMeshesList,
  46882. updatedGeometries: _this._addUpdateGeometriesList,
  46883. removedGeometries: _this._toRemoveGeometryArray,
  46884. removedMeshes: _this._toRemoveMeshesArray
  46885. };
  46886. var message = {
  46887. payload: payload,
  46888. taskType: WorkerTaskType.UPDATE
  46889. };
  46890. var serializable = [];
  46891. for (var id in payload.updatedGeometries) {
  46892. if (payload.updatedGeometries.hasOwnProperty(id)) {
  46893. //prepare transferables
  46894. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  46895. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  46896. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  46897. }
  46898. }
  46899. _this._worker.postMessage(message, serializable);
  46900. _this._addUpdateMeshesList = {};
  46901. _this._addUpdateGeometriesList = {};
  46902. _this._toRemoveGeometryArray = [];
  46903. _this._toRemoveMeshesArray = [];
  46904. };
  46905. this._onMessageFromWorker = function (e) {
  46906. var returnData = e.data;
  46907. if (returnData.error != WorkerReplyType.SUCCESS) {
  46908. //TODO what errors can be returned from the worker?
  46909. BABYLON.Tools.Warn("error returned from worker!");
  46910. return;
  46911. }
  46912. switch (returnData.taskType) {
  46913. case WorkerTaskType.INIT:
  46914. _this._init = true;
  46915. //Update the worked with ALL of the scene's current state
  46916. _this._scene.meshes.forEach(function (mesh) {
  46917. _this.onMeshAdded(mesh);
  46918. });
  46919. _this._scene.getGeometries().forEach(function (geometry) {
  46920. _this.onGeometryAdded(geometry);
  46921. });
  46922. break;
  46923. case WorkerTaskType.UPDATE:
  46924. _this._runningUpdated--;
  46925. break;
  46926. case WorkerTaskType.COLLIDE:
  46927. var returnPayload = returnData.payload;
  46928. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  46929. return;
  46930. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  46931. if (callback) {
  46932. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  46933. if (mesh) {
  46934. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  46935. }
  46936. }
  46937. //cleanup
  46938. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  46939. break;
  46940. }
  46941. };
  46942. this._collisionsCallbackArray = [];
  46943. this._init = false;
  46944. this._runningUpdated = 0;
  46945. this._addUpdateMeshesList = {};
  46946. this._addUpdateGeometriesList = {};
  46947. this._toRemoveGeometryArray = [];
  46948. this._toRemoveMeshesArray = [];
  46949. }
  46950. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46951. if (!this._init)
  46952. return;
  46953. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  46954. return;
  46955. position.divideToRef(collider._radius, this._scaledPosition);
  46956. displacement.divideToRef(collider._radius, this._scaledVelocity);
  46957. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  46958. var payload = {
  46959. collider: {
  46960. position: this._scaledPosition.asArray(),
  46961. velocity: this._scaledVelocity.asArray(),
  46962. radius: collider._radius.asArray()
  46963. },
  46964. collisionId: collisionIndex,
  46965. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  46966. maximumRetry: maximumRetry
  46967. };
  46968. var message = {
  46969. payload: payload,
  46970. taskType: WorkerTaskType.COLLIDE
  46971. };
  46972. this._worker.postMessage(message);
  46973. };
  46974. CollisionCoordinatorWorker.prototype.init = function (scene) {
  46975. this._scene = scene;
  46976. this._scene.registerAfterRender(this._afterRender);
  46977. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  46978. this._worker = new Worker(workerUrl);
  46979. this._worker.onmessage = this._onMessageFromWorker;
  46980. var message = {
  46981. payload: {},
  46982. taskType: WorkerTaskType.INIT
  46983. };
  46984. this._worker.postMessage(message);
  46985. };
  46986. CollisionCoordinatorWorker.prototype.destroy = function () {
  46987. this._scene.unregisterAfterRender(this._afterRender);
  46988. this._worker.terminate();
  46989. };
  46990. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  46991. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  46992. this.onMeshUpdated(mesh);
  46993. };
  46994. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  46995. this._toRemoveMeshesArray.push(mesh.uniqueId);
  46996. };
  46997. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  46998. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  46999. geometry.onGeometryUpdated = this.onGeometryUpdated;
  47000. this.onGeometryUpdated(geometry);
  47001. };
  47002. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  47003. this._toRemoveGeometryArray.push(geometry.id);
  47004. };
  47005. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  47006. var submeshes = [];
  47007. if (mesh.subMeshes) {
  47008. submeshes = mesh.subMeshes.map(function (sm, idx) {
  47009. var boundingInfo = sm.getBoundingInfo();
  47010. return {
  47011. position: idx,
  47012. verticesStart: sm.verticesStart,
  47013. verticesCount: sm.verticesCount,
  47014. indexStart: sm.indexStart,
  47015. indexCount: sm.indexCount,
  47016. hasMaterial: !!sm.getMaterial(),
  47017. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47018. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47019. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47020. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  47021. };
  47022. });
  47023. }
  47024. var geometryId = null;
  47025. if (mesh instanceof BABYLON.Mesh) {
  47026. var geometry = mesh.geometry;
  47027. geometryId = geometry ? geometry.id : null;
  47028. }
  47029. else if (mesh instanceof BABYLON.InstancedMesh) {
  47030. var geometry = mesh.sourceMesh.geometry;
  47031. geometryId = geometry ? geometry.id : null;
  47032. }
  47033. var boundingInfo = mesh.getBoundingInfo();
  47034. return {
  47035. uniqueId: mesh.uniqueId,
  47036. id: mesh.id,
  47037. name: mesh.name,
  47038. geometryId: geometryId,
  47039. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47040. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47041. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47042. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  47043. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  47044. subMeshes: submeshes,
  47045. checkCollisions: mesh.checkCollisions
  47046. };
  47047. };
  47048. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  47049. return {
  47050. id: geometry.id,
  47051. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  47052. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  47053. indices: new Uint32Array(geometry.getIndices() || []),
  47054. };
  47055. };
  47056. return CollisionCoordinatorWorker;
  47057. }());
  47058. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  47059. var CollisionCoordinatorLegacy = /** @class */ (function () {
  47060. function CollisionCoordinatorLegacy() {
  47061. this._scaledPosition = BABYLON.Vector3.Zero();
  47062. this._scaledVelocity = BABYLON.Vector3.Zero();
  47063. this._finalPosition = BABYLON.Vector3.Zero();
  47064. }
  47065. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47066. position.divideToRef(collider._radius, this._scaledPosition);
  47067. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47068. collider.collidedMesh = null;
  47069. collider._retry = 0;
  47070. collider._initialVelocity = this._scaledVelocity;
  47071. collider._initialPosition = this._scaledPosition;
  47072. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  47073. this._finalPosition.multiplyInPlace(collider._radius);
  47074. //run the callback
  47075. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  47076. };
  47077. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  47078. this._scene = scene;
  47079. };
  47080. CollisionCoordinatorLegacy.prototype.destroy = function () {
  47081. //Legacy need no destruction method.
  47082. };
  47083. //No update in legacy mode
  47084. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  47085. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  47086. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  47087. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  47088. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  47089. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  47090. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  47091. if (excludedMesh === void 0) { excludedMesh = null; }
  47092. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  47093. if (collider._retry >= maximumRetry) {
  47094. finalPosition.copyFrom(position);
  47095. return;
  47096. }
  47097. // Check if this is a mesh else camera or -1
  47098. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  47099. collider._initialize(position, velocity, closeDistance);
  47100. // Check all meshes
  47101. for (var index = 0; index < this._scene.meshes.length; index++) {
  47102. var mesh = this._scene.meshes[index];
  47103. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  47104. mesh._checkCollision(collider);
  47105. }
  47106. }
  47107. if (!collider.collisionFound) {
  47108. position.addToRef(velocity, finalPosition);
  47109. return;
  47110. }
  47111. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  47112. collider._getResponse(position, velocity);
  47113. }
  47114. if (velocity.length() <= closeDistance) {
  47115. finalPosition.copyFrom(position);
  47116. return;
  47117. }
  47118. collider._retry++;
  47119. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  47120. };
  47121. return CollisionCoordinatorLegacy;
  47122. }());
  47123. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  47124. })(BABYLON || (BABYLON = {}));
  47125. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  47126. var BABYLON;
  47127. (function (BABYLON) {
  47128. /**
  47129. * A particle represents one of the element emitted by a particle system.
  47130. * This is mainly define by its coordinates, direction, velocity and age.
  47131. */
  47132. var Particle = /** @class */ (function () {
  47133. /**
  47134. * Creates a new instance of @see Particle
  47135. * @param particleSystem the particle system the particle belongs to
  47136. */
  47137. function Particle(particleSystem) {
  47138. this.particleSystem = particleSystem;
  47139. /**
  47140. * The world position of the particle in the scene.
  47141. */
  47142. this.position = BABYLON.Vector3.Zero();
  47143. /**
  47144. * The world direction of the particle in the scene.
  47145. */
  47146. this.direction = BABYLON.Vector3.Zero();
  47147. /**
  47148. * The color of the particle.
  47149. */
  47150. this.color = new BABYLON.Color4(0, 0, 0, 0);
  47151. /**
  47152. * The color change of the particle per step.
  47153. */
  47154. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  47155. /**
  47156. * Defines how long will the life of the particle be.
  47157. */
  47158. this.lifeTime = 1.0;
  47159. /**
  47160. * The current age of the particle.
  47161. */
  47162. this.age = 0;
  47163. /**
  47164. * The current size of the particle.
  47165. */
  47166. this.size = 0;
  47167. /**
  47168. * The current angle of the particle.
  47169. */
  47170. this.angle = 0;
  47171. /**
  47172. * Defines how fast is the angle changing.
  47173. */
  47174. this.angularSpeed = 0;
  47175. /**
  47176. * Defines the cell index used by the particle to be rendered from a sprite.
  47177. */
  47178. this.cellIndex = 0;
  47179. this._currentFrameCounter = 0;
  47180. if (!this.particleSystem.isAnimationSheetEnabled) {
  47181. return;
  47182. }
  47183. this.cellIndex = this.particleSystem.startSpriteCellID;
  47184. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  47185. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  47186. }
  47187. else {
  47188. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  47189. }
  47190. }
  47191. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  47192. // (ageOffset / scaledUpdateSpeed) / available cells
  47193. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  47194. this._currentFrameCounter += scaledUpdateSpeed;
  47195. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  47196. this._currentFrameCounter = 0;
  47197. this.cellIndex++;
  47198. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47199. this.cellIndex = this.particleSystem.endSpriteCellID;
  47200. }
  47201. }
  47202. };
  47203. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  47204. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  47205. this.cellIndex++;
  47206. this._currentFrameCounter = 0;
  47207. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47208. if (this.particleSystem.spriteCellLoop) {
  47209. this.cellIndex = this.particleSystem.startSpriteCellID;
  47210. }
  47211. else {
  47212. this.cellIndex = this.particleSystem.endSpriteCellID;
  47213. }
  47214. }
  47215. }
  47216. else {
  47217. this._currentFrameCounter++;
  47218. }
  47219. };
  47220. /**
  47221. * Copy the properties of particle to another one.
  47222. * @param other the particle to copy the information to.
  47223. */
  47224. Particle.prototype.copyTo = function (other) {
  47225. other.position.copyFrom(this.position);
  47226. other.direction.copyFrom(this.direction);
  47227. other.color.copyFrom(this.color);
  47228. other.colorStep.copyFrom(this.colorStep);
  47229. other.lifeTime = this.lifeTime;
  47230. other.age = this.age;
  47231. other.size = this.size;
  47232. other.angle = this.angle;
  47233. other.angularSpeed = this.angularSpeed;
  47234. other.particleSystem = this.particleSystem;
  47235. other.cellIndex = this.cellIndex;
  47236. };
  47237. return Particle;
  47238. }());
  47239. BABYLON.Particle = Particle;
  47240. })(BABYLON || (BABYLON = {}));
  47241. //# sourceMappingURL=babylon.particle.js.map
  47242. var BABYLON;
  47243. (function (BABYLON) {
  47244. /**
  47245. * This represents a particle system in Babylon.
  47246. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  47247. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  47248. * @example https://doc.babylonjs.com/babylon101/particles
  47249. */
  47250. var ParticleSystem = /** @class */ (function () {
  47251. /**
  47252. * Instantiates a particle system.
  47253. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  47254. * @param name The name of the particle system
  47255. * @param capacity The max number of particles alive at the same time
  47256. * @param scene The scene the particle system belongs to
  47257. * @param customEffect a custom effect used to change the way particles are rendered by default
  47258. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  47259. * @param epsilon Offset used to render the particles
  47260. */
  47261. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  47262. if (customEffect === void 0) { customEffect = null; }
  47263. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  47264. if (epsilon === void 0) { epsilon = 0.01; }
  47265. var _this = this;
  47266. /**
  47267. * List of animations used by the particle system.
  47268. */
  47269. this.animations = [];
  47270. /**
  47271. * The rendering group used by the Particle system to chose when to render.
  47272. */
  47273. this.renderingGroupId = 0;
  47274. /**
  47275. * The emitter represents the Mesh or position we are attaching the particle system to.
  47276. */
  47277. this.emitter = null;
  47278. /**
  47279. * The density of particles, the rate of particle flow
  47280. */
  47281. this.emitRate = 10;
  47282. /**
  47283. * If you want to launch only a few particles at once, that can be done, as well.
  47284. */
  47285. this.manualEmitCount = -1;
  47286. /**
  47287. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  47288. */
  47289. this.updateSpeed = 0.01;
  47290. /**
  47291. * The amount of time the particle system is running (depends of the overall speed above).
  47292. */
  47293. this.targetStopDuration = 0;
  47294. /**
  47295. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  47296. */
  47297. this.disposeOnStop = false;
  47298. /**
  47299. * Minimum power of emitting particles.
  47300. */
  47301. this.minEmitPower = 1;
  47302. /**
  47303. * Maximum power of emitting particles.
  47304. */
  47305. this.maxEmitPower = 1;
  47306. /**
  47307. * Minimum life time of emitting particles.
  47308. */
  47309. this.minLifeTime = 1;
  47310. /**
  47311. * Maximum life time of emitting particles.
  47312. */
  47313. this.maxLifeTime = 1;
  47314. /**
  47315. * Minimum Size of emitting particles.
  47316. */
  47317. this.minSize = 1;
  47318. /**
  47319. * Maximum Size of emitting particles.
  47320. */
  47321. this.maxSize = 1;
  47322. /**
  47323. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  47324. */
  47325. this.minAngularSpeed = 0;
  47326. /**
  47327. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  47328. */
  47329. this.maxAngularSpeed = 0;
  47330. /**
  47331. * The layer mask we are rendering the particles through.
  47332. */
  47333. this.layerMask = 0x0FFFFFFF;
  47334. /**
  47335. * This can help using your own shader to render the particle system.
  47336. * The according effect will be created
  47337. */
  47338. this.customShader = null;
  47339. /**
  47340. * By default particle system starts as soon as they are created. This prevents the
  47341. * automatic start to happen and let you decide when to start emitting particles.
  47342. */
  47343. this.preventAutoStart = false;
  47344. /**
  47345. * Callback triggered when the particle animation is ending.
  47346. */
  47347. this.onAnimationEnd = null;
  47348. /**
  47349. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  47350. */
  47351. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  47352. /**
  47353. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  47354. * to override the particles.
  47355. */
  47356. this.forceDepthWrite = false;
  47357. /**
  47358. * You can use gravity if you want to give an orientation to your particles.
  47359. */
  47360. this.gravity = BABYLON.Vector3.Zero();
  47361. /**
  47362. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47363. */
  47364. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  47365. /**
  47366. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47367. */
  47368. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  47369. /**
  47370. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  47371. */
  47372. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  47373. /**
  47374. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  47375. */
  47376. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47377. /**
  47378. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47379. */
  47380. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47381. /**
  47382. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47383. */
  47384. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47385. /**
  47386. * Color the particle will have at the end of its lifetime.
  47387. */
  47388. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  47389. /**
  47390. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  47391. */
  47392. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47393. /**
  47394. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  47395. */
  47396. this.spriteCellLoop = true;
  47397. /**
  47398. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  47399. */
  47400. this.spriteCellChangeSpeed = 0;
  47401. /**
  47402. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  47403. */
  47404. this.startSpriteCellID = 0;
  47405. /**
  47406. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  47407. */
  47408. this.endSpriteCellID = 0;
  47409. /**
  47410. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  47411. */
  47412. this.spriteCellWidth = 0;
  47413. /**
  47414. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  47415. */
  47416. this.spriteCellHeight = 0;
  47417. /**
  47418. * An event triggered when the system is disposed.
  47419. */
  47420. this.onDisposeObservable = new BABYLON.Observable();
  47421. this._particles = new Array();
  47422. this._stockParticles = new Array();
  47423. this._newPartsExcess = 0;
  47424. this._vertexBuffers = {};
  47425. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  47426. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  47427. this._scaledDirection = BABYLON.Vector3.Zero();
  47428. this._scaledGravity = BABYLON.Vector3.Zero();
  47429. this._currentRenderId = -1;
  47430. this._started = false;
  47431. this._stopped = false;
  47432. this._actualFrame = 0;
  47433. this._vertexBufferSize = 11;
  47434. this._appendParticleVertexes = null;
  47435. this.id = name;
  47436. this.name = name;
  47437. this._capacity = capacity;
  47438. this._epsilon = epsilon;
  47439. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  47440. if (isAnimationSheetEnabled) {
  47441. this._vertexBufferSize = 12;
  47442. }
  47443. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47444. this._customEffect = customEffect;
  47445. scene.particleSystems.push(this);
  47446. this._createIndexBuffer();
  47447. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  47448. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  47449. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  47450. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  47451. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  47452. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  47453. if (this._isAnimationSheetEnabled) {
  47454. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  47455. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  47456. }
  47457. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47458. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47459. this._vertexBuffers["options"] = options;
  47460. // Default behaviors
  47461. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  47462. this.updateFunction = function (particles) {
  47463. for (var index = 0; index < particles.length; index++) {
  47464. var particle = particles[index];
  47465. particle.age += _this._scaledUpdateSpeed;
  47466. if (particle.age >= particle.lifeTime) {
  47467. _this.recycleParticle(particle);
  47468. index--;
  47469. continue;
  47470. }
  47471. else {
  47472. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  47473. particle.color.addInPlace(_this._scaledColorStep);
  47474. if (particle.color.a < 0)
  47475. particle.color.a = 0;
  47476. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  47477. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  47478. particle.position.addInPlace(_this._scaledDirection);
  47479. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  47480. particle.direction.addInPlace(_this._scaledGravity);
  47481. if (_this._isAnimationSheetEnabled) {
  47482. particle.updateCellIndex(_this._scaledUpdateSpeed);
  47483. }
  47484. }
  47485. }
  47486. };
  47487. }
  47488. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  47489. /**
  47490. * Sets a callback that will be triggered when the system is disposed.
  47491. */
  47492. set: function (callback) {
  47493. if (this._onDisposeObserver) {
  47494. this.onDisposeObservable.remove(this._onDisposeObserver);
  47495. }
  47496. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47497. },
  47498. enumerable: true,
  47499. configurable: true
  47500. });
  47501. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  47502. /**
  47503. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  47504. */
  47505. get: function () {
  47506. return this._isAnimationSheetEnabled;
  47507. },
  47508. enumerable: true,
  47509. configurable: true
  47510. });
  47511. ParticleSystem.prototype._createIndexBuffer = function () {
  47512. var indices = [];
  47513. var index = 0;
  47514. for (var count = 0; count < this._capacity; count++) {
  47515. indices.push(index);
  47516. indices.push(index + 1);
  47517. indices.push(index + 2);
  47518. indices.push(index);
  47519. indices.push(index + 2);
  47520. indices.push(index + 3);
  47521. index += 4;
  47522. }
  47523. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  47524. };
  47525. /**
  47526. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  47527. * Its lifetime will start back at 0.
  47528. * @param particle The particle to recycle
  47529. */
  47530. ParticleSystem.prototype.recycleParticle = function (particle) {
  47531. var lastParticle = this._particles.pop();
  47532. if (lastParticle !== particle) {
  47533. lastParticle.copyTo(particle);
  47534. this._stockParticles.push(lastParticle);
  47535. }
  47536. };
  47537. /**
  47538. * Gets the maximum number of particles active at the same time.
  47539. * @returns The max number of active particles.
  47540. */
  47541. ParticleSystem.prototype.getCapacity = function () {
  47542. return this._capacity;
  47543. };
  47544. /**
  47545. * Gets Wether there are still active particles in the system.
  47546. * @returns True if it is alive, otherwise false.
  47547. */
  47548. ParticleSystem.prototype.isAlive = function () {
  47549. return this._alive;
  47550. };
  47551. /**
  47552. * Gets Wether the system has been started.
  47553. * @returns True if it has been started, otherwise false.
  47554. */
  47555. ParticleSystem.prototype.isStarted = function () {
  47556. return this._started;
  47557. };
  47558. /**
  47559. * Starts the particle system and begins to emit.
  47560. */
  47561. ParticleSystem.prototype.start = function () {
  47562. this._started = true;
  47563. this._stopped = false;
  47564. this._actualFrame = 0;
  47565. };
  47566. /**
  47567. * Stops the particle system.
  47568. */
  47569. ParticleSystem.prototype.stop = function () {
  47570. this._stopped = true;
  47571. };
  47572. /**
  47573. * @ignore (for internal use only)
  47574. */
  47575. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  47576. var offset = index * this._vertexBufferSize;
  47577. this._vertexData[offset] = particle.position.x;
  47578. this._vertexData[offset + 1] = particle.position.y;
  47579. this._vertexData[offset + 2] = particle.position.z;
  47580. this._vertexData[offset + 3] = particle.color.r;
  47581. this._vertexData[offset + 4] = particle.color.g;
  47582. this._vertexData[offset + 5] = particle.color.b;
  47583. this._vertexData[offset + 6] = particle.color.a;
  47584. this._vertexData[offset + 7] = particle.angle;
  47585. this._vertexData[offset + 8] = particle.size;
  47586. this._vertexData[offset + 9] = offsetX;
  47587. this._vertexData[offset + 10] = offsetY;
  47588. };
  47589. /**
  47590. * @ignore (for internal use only)
  47591. */
  47592. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  47593. if (offsetX === 0)
  47594. offsetX = this._epsilon;
  47595. else if (offsetX === 1)
  47596. offsetX = 1 - this._epsilon;
  47597. if (offsetY === 0)
  47598. offsetY = this._epsilon;
  47599. else if (offsetY === 1)
  47600. offsetY = 1 - this._epsilon;
  47601. var offset = index * this._vertexBufferSize;
  47602. this._vertexData[offset] = particle.position.x;
  47603. this._vertexData[offset + 1] = particle.position.y;
  47604. this._vertexData[offset + 2] = particle.position.z;
  47605. this._vertexData[offset + 3] = particle.color.r;
  47606. this._vertexData[offset + 4] = particle.color.g;
  47607. this._vertexData[offset + 5] = particle.color.b;
  47608. this._vertexData[offset + 6] = particle.color.a;
  47609. this._vertexData[offset + 7] = particle.angle;
  47610. this._vertexData[offset + 8] = particle.size;
  47611. this._vertexData[offset + 9] = offsetX;
  47612. this._vertexData[offset + 10] = offsetY;
  47613. this._vertexData[offset + 11] = particle.cellIndex;
  47614. };
  47615. ParticleSystem.prototype._update = function (newParticles) {
  47616. // Update current
  47617. this._alive = this._particles.length > 0;
  47618. this.updateFunction(this._particles);
  47619. // Add new ones
  47620. var worldMatrix;
  47621. if (this.emitter.position) {
  47622. var emitterMesh = this.emitter;
  47623. worldMatrix = emitterMesh.getWorldMatrix();
  47624. }
  47625. else {
  47626. var emitterPosition = this.emitter;
  47627. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  47628. }
  47629. var particle;
  47630. for (var index = 0; index < newParticles; index++) {
  47631. if (this._particles.length === this._capacity) {
  47632. break;
  47633. }
  47634. if (this._stockParticles.length !== 0) {
  47635. particle = this._stockParticles.pop();
  47636. particle.age = 0;
  47637. particle.cellIndex = this.startSpriteCellID;
  47638. }
  47639. else {
  47640. particle = new BABYLON.Particle(this);
  47641. }
  47642. this._particles.push(particle);
  47643. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  47644. if (this.startPositionFunction) {
  47645. this.startPositionFunction(worldMatrix, particle.position, particle);
  47646. }
  47647. else {
  47648. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  47649. }
  47650. if (this.startDirectionFunction) {
  47651. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47652. }
  47653. else {
  47654. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47655. }
  47656. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  47657. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  47658. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  47659. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  47660. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  47661. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  47662. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  47663. }
  47664. };
  47665. ParticleSystem.prototype._getEffect = function () {
  47666. if (this._customEffect) {
  47667. return this._customEffect;
  47668. }
  47669. ;
  47670. var defines = [];
  47671. if (this._scene.clipPlane) {
  47672. defines.push("#define CLIPPLANE");
  47673. }
  47674. if (this._isAnimationSheetEnabled) {
  47675. defines.push("#define ANIMATESHEET");
  47676. }
  47677. // Effect
  47678. var join = defines.join("\n");
  47679. if (this._cachedDefines !== join) {
  47680. this._cachedDefines = join;
  47681. var attributesNamesOrOptions;
  47682. var effectCreationOption;
  47683. if (this._isAnimationSheetEnabled) {
  47684. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  47685. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  47686. }
  47687. else {
  47688. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  47689. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  47690. }
  47691. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  47692. }
  47693. return this._effect;
  47694. };
  47695. /**
  47696. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  47697. */
  47698. ParticleSystem.prototype.animate = function () {
  47699. if (!this._started)
  47700. return;
  47701. var effect = this._getEffect();
  47702. // Check
  47703. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  47704. return;
  47705. if (this._currentRenderId === this._scene.getRenderId()) {
  47706. return;
  47707. }
  47708. this._currentRenderId = this._scene.getRenderId();
  47709. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  47710. // determine the number of particles we need to create
  47711. var newParticles;
  47712. if (this.manualEmitCount > -1) {
  47713. newParticles = this.manualEmitCount;
  47714. this._newPartsExcess = 0;
  47715. this.manualEmitCount = 0;
  47716. }
  47717. else {
  47718. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  47719. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  47720. }
  47721. if (this._newPartsExcess > 1.0) {
  47722. newParticles += this._newPartsExcess >> 0;
  47723. this._newPartsExcess -= this._newPartsExcess >> 0;
  47724. }
  47725. this._alive = false;
  47726. if (!this._stopped) {
  47727. this._actualFrame += this._scaledUpdateSpeed;
  47728. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  47729. this.stop();
  47730. }
  47731. else {
  47732. newParticles = 0;
  47733. }
  47734. this._update(newParticles);
  47735. // Stopped?
  47736. if (this._stopped) {
  47737. if (!this._alive) {
  47738. this._started = false;
  47739. if (this.onAnimationEnd) {
  47740. this.onAnimationEnd();
  47741. }
  47742. if (this.disposeOnStop) {
  47743. this._scene._toBeDisposed.push(this);
  47744. }
  47745. }
  47746. }
  47747. // Animation sheet
  47748. if (this._isAnimationSheetEnabled) {
  47749. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  47750. }
  47751. else {
  47752. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  47753. }
  47754. // Update VBO
  47755. var offset = 0;
  47756. for (var index = 0; index < this._particles.length; index++) {
  47757. var particle = this._particles[index];
  47758. this._appendParticleVertexes(offset, particle);
  47759. offset += 4;
  47760. }
  47761. if (this._vertexBuffer) {
  47762. this._vertexBuffer.update(this._vertexData);
  47763. }
  47764. };
  47765. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  47766. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  47767. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  47768. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  47769. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  47770. };
  47771. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  47772. this._appendParticleVertex(offset++, particle, 0, 0);
  47773. this._appendParticleVertex(offset++, particle, 1, 0);
  47774. this._appendParticleVertex(offset++, particle, 1, 1);
  47775. this._appendParticleVertex(offset++, particle, 0, 1);
  47776. };
  47777. /**
  47778. * Rebuilds the particle system.
  47779. */
  47780. ParticleSystem.prototype.rebuild = function () {
  47781. this._createIndexBuffer();
  47782. if (this._vertexBuffer) {
  47783. this._vertexBuffer._rebuild();
  47784. }
  47785. };
  47786. /**
  47787. * Renders the particle system in its current state.
  47788. * @returns the current number of particles.
  47789. */
  47790. ParticleSystem.prototype.render = function () {
  47791. var effect = this._getEffect();
  47792. // Check
  47793. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  47794. return 0;
  47795. var engine = this._scene.getEngine();
  47796. // Render
  47797. engine.enableEffect(effect);
  47798. engine.setState(false);
  47799. var viewMatrix = this._scene.getViewMatrix();
  47800. effect.setTexture("diffuseSampler", this.particleTexture);
  47801. effect.setMatrix("view", viewMatrix);
  47802. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  47803. if (this._isAnimationSheetEnabled) {
  47804. var baseSize = this.particleTexture.getBaseSize();
  47805. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  47806. }
  47807. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  47808. if (this._scene.clipPlane) {
  47809. var clipPlane = this._scene.clipPlane;
  47810. var invView = viewMatrix.clone();
  47811. invView.invert();
  47812. effect.setMatrix("invView", invView);
  47813. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  47814. }
  47815. // VBOs
  47816. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  47817. // Draw order
  47818. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  47819. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  47820. }
  47821. else {
  47822. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47823. }
  47824. if (this.forceDepthWrite) {
  47825. engine.setDepthWrite(true);
  47826. }
  47827. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  47828. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47829. return this._particles.length;
  47830. };
  47831. /**
  47832. * Disposes the particle system and free the associated resources.
  47833. */
  47834. ParticleSystem.prototype.dispose = function () {
  47835. if (this._vertexBuffer) {
  47836. this._vertexBuffer.dispose();
  47837. this._vertexBuffer = null;
  47838. }
  47839. if (this._indexBuffer) {
  47840. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47841. this._indexBuffer = null;
  47842. }
  47843. if (this.particleTexture) {
  47844. this.particleTexture.dispose();
  47845. this.particleTexture = null;
  47846. }
  47847. // Remove from scene
  47848. var index = this._scene.particleSystems.indexOf(this);
  47849. if (index > -1) {
  47850. this._scene.particleSystems.splice(index, 1);
  47851. }
  47852. // Callback
  47853. this.onDisposeObservable.notifyObservers(this);
  47854. this.onDisposeObservable.clear();
  47855. };
  47856. /**
  47857. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  47858. * @param radius The radius of the sphere to emit from
  47859. * @returns the emitter
  47860. */
  47861. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  47862. if (radius === void 0) { radius = 1; }
  47863. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  47864. this.particleEmitterType = particleEmitter;
  47865. return particleEmitter;
  47866. };
  47867. /**
  47868. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  47869. * @param radius The radius of the sphere to emit from
  47870. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  47871. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  47872. * @returns the emitter
  47873. */
  47874. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  47875. if (radius === void 0) { radius = 1; }
  47876. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  47877. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  47878. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  47879. this.particleEmitterType = particleEmitter;
  47880. return particleEmitter;
  47881. };
  47882. /**
  47883. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  47884. * @param radius The radius of the cone to emit from
  47885. * @param angle The base angle of the cone
  47886. * @returns the emitter
  47887. */
  47888. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  47889. if (radius === void 0) { radius = 1; }
  47890. if (angle === void 0) { angle = Math.PI / 4; }
  47891. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  47892. this.particleEmitterType = particleEmitter;
  47893. return particleEmitter;
  47894. };
  47895. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  47896. /**
  47897. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  47898. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  47899. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  47900. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  47901. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  47902. * @returns the emitter
  47903. */
  47904. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  47905. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  47906. this.direction1 = direction1;
  47907. this.direction2 = direction2;
  47908. this.minEmitBox = minEmitBox;
  47909. this.maxEmitBox = maxEmitBox;
  47910. this.particleEmitterType = particleEmitter;
  47911. return particleEmitter;
  47912. };
  47913. /**
  47914. * Clones the particle system.
  47915. * @param name The name of the cloned object
  47916. * @param newEmitter The new emitter to use
  47917. * @returns the cloned particle system
  47918. */
  47919. ParticleSystem.prototype.clone = function (name, newEmitter) {
  47920. var custom = null;
  47921. var program = null;
  47922. if (this.customShader != null) {
  47923. program = this.customShader;
  47924. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  47925. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  47926. }
  47927. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  47928. result.customShader = program;
  47929. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  47930. if (newEmitter === undefined) {
  47931. newEmitter = this.emitter;
  47932. }
  47933. result.emitter = newEmitter;
  47934. if (this.particleTexture) {
  47935. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  47936. }
  47937. if (!this.preventAutoStart) {
  47938. result.start();
  47939. }
  47940. return result;
  47941. };
  47942. /**
  47943. * Serializes the particle system to a JSON object.
  47944. * @returns the JSON object
  47945. */
  47946. ParticleSystem.prototype.serialize = function () {
  47947. var serializationObject = {};
  47948. serializationObject.name = this.name;
  47949. serializationObject.id = this.id;
  47950. // Emitter
  47951. if (this.emitter.position) {
  47952. var emitterMesh = this.emitter;
  47953. serializationObject.emitterId = emitterMesh.id;
  47954. }
  47955. else {
  47956. var emitterPosition = this.emitter;
  47957. serializationObject.emitter = emitterPosition.asArray();
  47958. }
  47959. serializationObject.capacity = this.getCapacity();
  47960. if (this.particleTexture) {
  47961. serializationObject.textureName = this.particleTexture.name;
  47962. }
  47963. // Animations
  47964. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  47965. // Particle system
  47966. serializationObject.minAngularSpeed = this.minAngularSpeed;
  47967. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  47968. serializationObject.minSize = this.minSize;
  47969. serializationObject.maxSize = this.maxSize;
  47970. serializationObject.minEmitPower = this.minEmitPower;
  47971. serializationObject.maxEmitPower = this.maxEmitPower;
  47972. serializationObject.minLifeTime = this.minLifeTime;
  47973. serializationObject.maxLifeTime = this.maxLifeTime;
  47974. serializationObject.emitRate = this.emitRate;
  47975. serializationObject.minEmitBox = this.minEmitBox.asArray();
  47976. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  47977. serializationObject.gravity = this.gravity.asArray();
  47978. serializationObject.direction1 = this.direction1.asArray();
  47979. serializationObject.direction2 = this.direction2.asArray();
  47980. serializationObject.color1 = this.color1.asArray();
  47981. serializationObject.color2 = this.color2.asArray();
  47982. serializationObject.colorDead = this.colorDead.asArray();
  47983. serializationObject.updateSpeed = this.updateSpeed;
  47984. serializationObject.targetStopDuration = this.targetStopDuration;
  47985. serializationObject.textureMask = this.textureMask.asArray();
  47986. serializationObject.blendMode = this.blendMode;
  47987. serializationObject.customShader = this.customShader;
  47988. serializationObject.preventAutoStart = this.preventAutoStart;
  47989. serializationObject.startSpriteCellID = this.startSpriteCellID;
  47990. serializationObject.endSpriteCellID = this.endSpriteCellID;
  47991. serializationObject.spriteCellLoop = this.spriteCellLoop;
  47992. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  47993. serializationObject.spriteCellWidth = this.spriteCellWidth;
  47994. serializationObject.spriteCellHeight = this.spriteCellHeight;
  47995. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  47996. return serializationObject;
  47997. };
  47998. /**
  47999. * Parses a JSON object to create a particle system.
  48000. * @param parsedParticleSystem The JSON object to parse
  48001. * @param scene The scene to create the particle system in
  48002. * @param rootUrl The root url to use to load external dependencies like texture
  48003. * @returns the Parsed particle system
  48004. */
  48005. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  48006. var name = parsedParticleSystem.name;
  48007. var custom = null;
  48008. var program = null;
  48009. if (parsedParticleSystem.customShader) {
  48010. program = parsedParticleSystem.customShader;
  48011. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48012. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48013. }
  48014. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  48015. particleSystem.customShader = program;
  48016. if (parsedParticleSystem.id) {
  48017. particleSystem.id = parsedParticleSystem.id;
  48018. }
  48019. // Auto start
  48020. if (parsedParticleSystem.preventAutoStart) {
  48021. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  48022. }
  48023. // Texture
  48024. if (parsedParticleSystem.textureName) {
  48025. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  48026. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  48027. }
  48028. // Emitter
  48029. if (parsedParticleSystem.emitterId) {
  48030. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  48031. }
  48032. else {
  48033. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  48034. }
  48035. // Animations
  48036. if (parsedParticleSystem.animations) {
  48037. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  48038. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  48039. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48040. }
  48041. }
  48042. if (parsedParticleSystem.autoAnimate) {
  48043. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  48044. }
  48045. // Particle system
  48046. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  48047. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  48048. particleSystem.minSize = parsedParticleSystem.minSize;
  48049. particleSystem.maxSize = parsedParticleSystem.maxSize;
  48050. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  48051. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  48052. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  48053. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  48054. particleSystem.emitRate = parsedParticleSystem.emitRate;
  48055. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  48056. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  48057. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  48058. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  48059. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  48060. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  48061. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  48062. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  48063. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  48064. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  48065. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  48066. particleSystem.blendMode = parsedParticleSystem.blendMode;
  48067. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  48068. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  48069. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  48070. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  48071. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  48072. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  48073. if (!particleSystem.preventAutoStart) {
  48074. particleSystem.start();
  48075. }
  48076. return particleSystem;
  48077. };
  48078. /**
  48079. * Source color is added to the destination color without alpha affecting the result.
  48080. */
  48081. ParticleSystem.BLENDMODE_ONEONE = 0;
  48082. /**
  48083. * Blend current color and particle color using particle’s alpha.
  48084. */
  48085. ParticleSystem.BLENDMODE_STANDARD = 1;
  48086. return ParticleSystem;
  48087. }());
  48088. BABYLON.ParticleSystem = ParticleSystem;
  48089. })(BABYLON || (BABYLON = {}));
  48090. //# sourceMappingURL=babylon.particleSystem.js.map
  48091. var BABYLON;
  48092. (function (BABYLON) {
  48093. /**
  48094. * Particle emitter emitting particles from the inside of a box.
  48095. * It emits the particles randomly between 2 given directions.
  48096. */
  48097. var BoxParticleEmitter = /** @class */ (function () {
  48098. // to be updated like the rest of emitters when breaking changes.
  48099. // all property should be come public variables and passed through constructor.
  48100. /**
  48101. * Creates a new instance of @see BoxParticleEmitter
  48102. * @param _particleSystem the particle system associated with the emitter
  48103. */
  48104. function BoxParticleEmitter(_particleSystem) {
  48105. this._particleSystem = _particleSystem;
  48106. }
  48107. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  48108. /**
  48109. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48110. */
  48111. get: function () {
  48112. return this._particleSystem.direction1;
  48113. },
  48114. /**
  48115. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48116. */
  48117. set: function (value) {
  48118. this._particleSystem.direction1 = value;
  48119. },
  48120. enumerable: true,
  48121. configurable: true
  48122. });
  48123. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  48124. /**
  48125. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48126. */
  48127. get: function () {
  48128. return this._particleSystem.direction2;
  48129. },
  48130. /**
  48131. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48132. */
  48133. set: function (value) {
  48134. this._particleSystem.direction2 = value;
  48135. },
  48136. enumerable: true,
  48137. configurable: true
  48138. });
  48139. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  48140. /**
  48141. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48142. */
  48143. get: function () {
  48144. return this._particleSystem.minEmitBox;
  48145. },
  48146. /**
  48147. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48148. */
  48149. set: function (value) {
  48150. this._particleSystem.minEmitBox = value;
  48151. },
  48152. enumerable: true,
  48153. configurable: true
  48154. });
  48155. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  48156. /**
  48157. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48158. */
  48159. get: function () {
  48160. return this._particleSystem.maxEmitBox;
  48161. },
  48162. /**
  48163. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48164. */
  48165. set: function (value) {
  48166. this._particleSystem.maxEmitBox = value;
  48167. },
  48168. enumerable: true,
  48169. configurable: true
  48170. });
  48171. /**
  48172. * Called by the particle System when the direction is computed for the created particle.
  48173. * @param emitPower is the power of the particle (speed)
  48174. * @param worldMatrix is the world matrix of the particle system
  48175. * @param directionToUpdate is the direction vector to update with the result
  48176. * @param particle is the particle we are computed the direction for
  48177. */
  48178. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48179. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48180. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48181. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48182. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48183. };
  48184. /**
  48185. * Called by the particle System when the position is computed for the created particle.
  48186. * @param worldMatrix is the world matrix of the particle system
  48187. * @param positionToUpdate is the position vector to update with the result
  48188. * @param particle is the particle we are computed the position for
  48189. */
  48190. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48191. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  48192. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  48193. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  48194. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48195. };
  48196. return BoxParticleEmitter;
  48197. }());
  48198. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  48199. })(BABYLON || (BABYLON = {}));
  48200. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  48201. var BABYLON;
  48202. (function (BABYLON) {
  48203. /**
  48204. * Particle emitter emitting particles from the inside of a cone.
  48205. * It emits the particles alongside the cone volume from the base to the particle.
  48206. * The emission direction might be randomized.
  48207. */
  48208. var ConeParticleEmitter = /** @class */ (function () {
  48209. /**
  48210. * Creates a new instance of @see ConeParticleEmitter
  48211. * @param radius the radius of the emission cone
  48212. * @param angles the cone base angle
  48213. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48214. */
  48215. function ConeParticleEmitter(radius,
  48216. /**
  48217. * The radius of the emission cone.
  48218. */
  48219. angle,
  48220. /**
  48221. * The cone base angle.
  48222. */
  48223. directionRandomizer) {
  48224. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48225. this.angle = angle;
  48226. this.directionRandomizer = directionRandomizer;
  48227. this.radius = radius;
  48228. }
  48229. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  48230. /**
  48231. * Gets the radius of the emission cone.
  48232. */
  48233. get: function () {
  48234. return this._radius;
  48235. },
  48236. /**
  48237. * Sets the radius of the emission cone.
  48238. */
  48239. set: function (value) {
  48240. this._radius = value;
  48241. if (this.angle !== 0) {
  48242. this._height = value / Math.tan(this.angle / 2);
  48243. }
  48244. else {
  48245. this._height = 1;
  48246. }
  48247. },
  48248. enumerable: true,
  48249. configurable: true
  48250. });
  48251. /**
  48252. * Called by the particle System when the direction is computed for the created particle.
  48253. * @param emitPower is the power of the particle (speed)
  48254. * @param worldMatrix is the world matrix of the particle system
  48255. * @param directionToUpdate is the direction vector to update with the result
  48256. * @param particle is the particle we are computed the direction for
  48257. */
  48258. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48259. if (this.angle === 0) {
  48260. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  48261. }
  48262. else {
  48263. // measure the direction Vector from the emitter to the particle.
  48264. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48265. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48266. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48267. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48268. direction.x += randX;
  48269. direction.y += randY;
  48270. direction.z += randZ;
  48271. direction.normalize();
  48272. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48273. }
  48274. };
  48275. /**
  48276. * Called by the particle System when the position is computed for the created particle.
  48277. * @param worldMatrix is the world matrix of the particle system
  48278. * @param positionToUpdate is the position vector to update with the result
  48279. * @param particle is the particle we are computed the position for
  48280. */
  48281. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48282. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  48283. var h = BABYLON.Scalar.RandomRange(0, 1);
  48284. // Better distribution in a cone at normal angles.
  48285. h = 1 - h * h;
  48286. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  48287. radius = radius * h / this._height;
  48288. var randX = radius * Math.sin(s);
  48289. var randZ = radius * Math.cos(s);
  48290. var randY = h;
  48291. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48292. };
  48293. return ConeParticleEmitter;
  48294. }());
  48295. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  48296. })(BABYLON || (BABYLON = {}));
  48297. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  48298. var BABYLON;
  48299. (function (BABYLON) {
  48300. /**
  48301. * Particle emitter emitting particles from the inside of a sphere.
  48302. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  48303. */
  48304. var SphereParticleEmitter = /** @class */ (function () {
  48305. /**
  48306. * Creates a new instance of @see SphereParticleEmitter
  48307. * @param radius the radius of the emission sphere
  48308. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48309. */
  48310. function SphereParticleEmitter(
  48311. /**
  48312. * The radius of the emission sphere.
  48313. */
  48314. radius,
  48315. /**
  48316. * How much to randomize the particle direction [0-1].
  48317. */
  48318. directionRandomizer) {
  48319. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48320. this.radius = radius;
  48321. this.directionRandomizer = directionRandomizer;
  48322. }
  48323. /**
  48324. * Called by the particle System when the direction is computed for the created particle.
  48325. * @param emitPower is the power of the particle (speed)
  48326. * @param worldMatrix is the world matrix of the particle system
  48327. * @param directionToUpdate is the direction vector to update with the result
  48328. * @param particle is the particle we are computed the direction for
  48329. */
  48330. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48331. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48332. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48333. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48334. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48335. direction.x += randX;
  48336. direction.y += randY;
  48337. direction.z += randZ;
  48338. direction.normalize();
  48339. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48340. };
  48341. /**
  48342. * Called by the particle System when the position is computed for the created particle.
  48343. * @param worldMatrix is the world matrix of the particle system
  48344. * @param positionToUpdate is the position vector to update with the result
  48345. * @param particle is the particle we are computed the position for
  48346. */
  48347. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48348. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  48349. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  48350. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  48351. var randY = this.radius * Math.cos(theta);
  48352. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  48353. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48354. };
  48355. return SphereParticleEmitter;
  48356. }());
  48357. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  48358. /**
  48359. * Particle emitter emitting particles from the inside of a sphere.
  48360. * It emits the particles randomly between two vectors.
  48361. */
  48362. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  48363. __extends(SphereDirectedParticleEmitter, _super);
  48364. /**
  48365. * Creates a new instance of @see SphereDirectedParticleEmitter
  48366. * @param radius the radius of the emission sphere
  48367. * @param direction1 the min limit of the emission direction
  48368. * @param direction2 the max limit of the emission direction
  48369. */
  48370. function SphereDirectedParticleEmitter(radius,
  48371. /**
  48372. * The min limit of the emission direction.
  48373. */
  48374. direction1,
  48375. /**
  48376. * The max limit of the emission direction.
  48377. */
  48378. direction2) {
  48379. var _this = _super.call(this, radius) || this;
  48380. _this.direction1 = direction1;
  48381. _this.direction2 = direction2;
  48382. return _this;
  48383. }
  48384. /**
  48385. * Called by the particle System when the direction is computed for the created particle.
  48386. * @param emitPower is the power of the particle (speed)
  48387. * @param worldMatrix is the world matrix of the particle system
  48388. * @param directionToUpdate is the direction vector to update with the result
  48389. * @param particle is the particle we are computed the direction for
  48390. */
  48391. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48392. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48393. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48394. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48395. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48396. };
  48397. return SphereDirectedParticleEmitter;
  48398. }(SphereParticleEmitter));
  48399. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  48400. })(BABYLON || (BABYLON = {}));
  48401. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  48402. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  48403. var BABYLON;
  48404. (function (BABYLON) {
  48405. /**
  48406. * Represents one particle of a solid particle system.
  48407. * @see SolidParticleSystem
  48408. */
  48409. var SolidParticle = /** @class */ (function () {
  48410. /**
  48411. * Creates a Solid Particle object.
  48412. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48413. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48414. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48415. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  48416. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  48417. * @param shapeId (integer) is the model shape identifier in the SPS.
  48418. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48419. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  48420. */
  48421. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48422. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  48423. /**
  48424. * particle global index
  48425. */
  48426. this.idx = 0;
  48427. /**
  48428. * The color of the particle
  48429. */
  48430. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48431. /**
  48432. * The world space position of the particle.
  48433. */
  48434. this.position = BABYLON.Vector3.Zero();
  48435. /**
  48436. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  48437. */
  48438. this.rotation = BABYLON.Vector3.Zero();
  48439. /**
  48440. * The scaling of the particle.
  48441. */
  48442. this.scaling = BABYLON.Vector3.One();
  48443. /**
  48444. * The uvs of the particle.
  48445. */
  48446. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  48447. /**
  48448. * The current speed of the particle.
  48449. */
  48450. this.velocity = BABYLON.Vector3.Zero();
  48451. /**
  48452. * The pivot point in the particle local space.
  48453. */
  48454. this.pivot = BABYLON.Vector3.Zero();
  48455. /**
  48456. * Is the particle active or not ?
  48457. */
  48458. this.alive = true;
  48459. /**
  48460. * Is the particle visible or not ?
  48461. */
  48462. this.isVisible = true;
  48463. /**
  48464. * Index of this particle in the global "positions" array (Internal use)
  48465. */
  48466. this._pos = 0;
  48467. /**
  48468. * Index of this particle in the global "indices" array (Internal use)
  48469. */
  48470. this._ind = 0;
  48471. /**
  48472. * ModelShape id of this particle
  48473. */
  48474. this.shapeId = 0;
  48475. /**
  48476. * Index of the particle in its shape id (Internal use)
  48477. */
  48478. this.idxInShape = 0;
  48479. /**
  48480. * Still set as invisible in order to skip useless computations (Internal use)
  48481. */
  48482. this._stillInvisible = false;
  48483. this.idx = particleIndex;
  48484. this._pos = positionIndex;
  48485. this._ind = indiceIndex;
  48486. this._model = model;
  48487. this.shapeId = shapeId;
  48488. this.idxInShape = idxInShape;
  48489. this._sps = sps;
  48490. if (modelBoundingInfo) {
  48491. this._modelBoundingInfo = modelBoundingInfo;
  48492. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48493. }
  48494. }
  48495. Object.defineProperty(SolidParticle.prototype, "scale", {
  48496. /**
  48497. * Legacy support, changed scale to scaling
  48498. */
  48499. get: function () {
  48500. return this.scaling;
  48501. },
  48502. /**
  48503. * Legacy support, changed scale to scaling
  48504. */
  48505. set: function (scale) {
  48506. this.scaling = scale;
  48507. },
  48508. enumerable: true,
  48509. configurable: true
  48510. });
  48511. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48512. /**
  48513. * Legacy support, changed quaternion to rotationQuaternion
  48514. */
  48515. get: function () {
  48516. return this.rotationQuaternion;
  48517. },
  48518. /**
  48519. * Legacy support, changed quaternion to rotationQuaternion
  48520. */
  48521. set: function (q) {
  48522. this.rotationQuaternion = q;
  48523. },
  48524. enumerable: true,
  48525. configurable: true
  48526. });
  48527. /**
  48528. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48529. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48530. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  48531. * @returns true if it intersects
  48532. */
  48533. SolidParticle.prototype.intersectsMesh = function (target) {
  48534. if (!this._boundingInfo || !target._boundingInfo) {
  48535. return false;
  48536. }
  48537. if (this._sps._bSphereOnly) {
  48538. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48539. }
  48540. return this._boundingInfo.intersects(target._boundingInfo, false);
  48541. };
  48542. return SolidParticle;
  48543. }());
  48544. BABYLON.SolidParticle = SolidParticle;
  48545. /**
  48546. * Represents the shape of the model used by one particle of a solid particle system.
  48547. * SPS internal tool, don't use it manually.
  48548. * @see SolidParticleSystem
  48549. */
  48550. var ModelShape = /** @class */ (function () {
  48551. /**
  48552. * 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.
  48553. * SPS internal tool, don't use it manually.
  48554. * @ignore
  48555. */
  48556. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  48557. /**
  48558. * length of the shape in the model indices array (internal use)
  48559. */
  48560. this._indicesLength = 0;
  48561. this.shapeID = id;
  48562. this._shape = shape;
  48563. this._indicesLength = indicesLength;
  48564. this._shapeUV = shapeUV;
  48565. this._positionFunction = posFunction;
  48566. this._vertexFunction = vtxFunction;
  48567. }
  48568. return ModelShape;
  48569. }());
  48570. BABYLON.ModelShape = ModelShape;
  48571. /**
  48572. * Represents a Depth Sorted Particle in the solid particle system.
  48573. * @see SolidParticleSystem
  48574. */
  48575. var DepthSortedParticle = /** @class */ (function () {
  48576. function DepthSortedParticle() {
  48577. /**
  48578. * Index of the particle in the "indices" array
  48579. */
  48580. this.ind = 0;
  48581. /**
  48582. * Length of the particle shape in the "indices" array
  48583. */
  48584. this.indicesLength = 0;
  48585. /**
  48586. * Squared distance from the particle to the camera
  48587. */
  48588. this.sqDistance = 0.0;
  48589. }
  48590. return DepthSortedParticle;
  48591. }());
  48592. BABYLON.DepthSortedParticle = DepthSortedParticle;
  48593. })(BABYLON || (BABYLON = {}));
  48594. //# sourceMappingURL=babylon.solidParticle.js.map
  48595. var BABYLON;
  48596. (function (BABYLON) {
  48597. /**
  48598. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  48599. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  48600. * The SPS is also a particle system. It provides some methods to manage the particles.
  48601. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  48602. *
  48603. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  48604. */
  48605. var SolidParticleSystem = /** @class */ (function () {
  48606. /**
  48607. * Creates a SPS (Solid Particle System) object.
  48608. * @param name (String) is the SPS name, this will be the underlying mesh name.
  48609. * @param scene (Scene) is the scene in which the SPS is added.
  48610. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  48611. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  48612. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  48613. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  48614. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  48615. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  48616. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  48617. */
  48618. function SolidParticleSystem(name, scene, options) {
  48619. /**
  48620. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  48621. * Example : var p = SPS.particles[i];
  48622. */
  48623. this.particles = new Array();
  48624. /**
  48625. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  48626. */
  48627. this.nbParticles = 0;
  48628. /**
  48629. * If the particles must ever face the camera (default false). Useful for planar particles.
  48630. */
  48631. this.billboard = false;
  48632. /**
  48633. * Recompute normals when adding a shape
  48634. */
  48635. this.recomputeNormals = true;
  48636. /**
  48637. * This a counter ofr your own usage. It's not set by any SPS functions.
  48638. */
  48639. this.counter = 0;
  48640. /**
  48641. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  48642. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  48643. */
  48644. this.vars = {};
  48645. /**
  48646. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  48647. */
  48648. this._bSphereOnly = false;
  48649. /**
  48650. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  48651. */
  48652. this._bSphereRadiusFactor = 1.0;
  48653. this._positions = new Array();
  48654. this._indices = new Array();
  48655. this._normals = new Array();
  48656. this._colors = new Array();
  48657. this._uvs = new Array();
  48658. this._index = 0; // indices index
  48659. this._updatable = true;
  48660. this._pickable = false;
  48661. this._isVisibilityBoxLocked = false;
  48662. this._alwaysVisible = false;
  48663. this._depthSort = false;
  48664. this._shapeCounter = 0;
  48665. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  48666. this._color = new BABYLON.Color4(0, 0, 0, 0);
  48667. this._computeParticleColor = true;
  48668. this._computeParticleTexture = true;
  48669. this._computeParticleRotation = true;
  48670. this._computeParticleVertex = false;
  48671. this._computeBoundingBox = false;
  48672. this._depthSortParticles = true;
  48673. this._cam_axisZ = BABYLON.Vector3.Zero();
  48674. this._cam_axisY = BABYLON.Vector3.Zero();
  48675. this._cam_axisX = BABYLON.Vector3.Zero();
  48676. this._axisZ = BABYLON.Axis.Z;
  48677. this._camDir = BABYLON.Vector3.Zero();
  48678. this._camInvertedPosition = BABYLON.Vector3.Zero();
  48679. this._rotMatrix = new BABYLON.Matrix();
  48680. this._invertMatrix = new BABYLON.Matrix();
  48681. this._rotated = BABYLON.Vector3.Zero();
  48682. this._quaternion = new BABYLON.Quaternion();
  48683. this._vertex = BABYLON.Vector3.Zero();
  48684. this._normal = BABYLON.Vector3.Zero();
  48685. this._yaw = 0.0;
  48686. this._pitch = 0.0;
  48687. this._roll = 0.0;
  48688. this._halfroll = 0.0;
  48689. this._halfpitch = 0.0;
  48690. this._halfyaw = 0.0;
  48691. this._sinRoll = 0.0;
  48692. this._cosRoll = 0.0;
  48693. this._sinPitch = 0.0;
  48694. this._cosPitch = 0.0;
  48695. this._sinYaw = 0.0;
  48696. this._cosYaw = 0.0;
  48697. this._mustUnrotateFixedNormals = false;
  48698. this._minimum = BABYLON.Tmp.Vector3[0];
  48699. this._maximum = BABYLON.Tmp.Vector3[1];
  48700. this._minBbox = BABYLON.Tmp.Vector3[4];
  48701. this._maxBbox = BABYLON.Tmp.Vector3[5];
  48702. this._particlesIntersect = false;
  48703. this._depthSortFunction = function (p1, p2) {
  48704. return (p2.sqDistance - p1.sqDistance);
  48705. };
  48706. this._needs32Bits = false;
  48707. this.name = name;
  48708. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48709. this._camera = scene.activeCamera;
  48710. this._pickable = options ? options.isPickable : false;
  48711. this._depthSort = options ? options.enableDepthSort : false;
  48712. this._particlesIntersect = options ? options.particleIntersection : false;
  48713. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  48714. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  48715. if (options && options.updatable) {
  48716. this._updatable = options.updatable;
  48717. }
  48718. else {
  48719. this._updatable = true;
  48720. }
  48721. if (this._pickable) {
  48722. this.pickedParticles = [];
  48723. }
  48724. if (this._depthSort) {
  48725. this.depthSortedParticles = [];
  48726. }
  48727. }
  48728. /**
  48729. * Builds the SPS underlying mesh. Returns a standard Mesh.
  48730. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  48731. * @returns the created mesh
  48732. */
  48733. SolidParticleSystem.prototype.buildMesh = function () {
  48734. if (this.nbParticles === 0) {
  48735. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  48736. this.addShape(triangle, 1);
  48737. triangle.dispose();
  48738. }
  48739. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  48740. this._positions32 = new Float32Array(this._positions);
  48741. this._uvs32 = new Float32Array(this._uvs);
  48742. this._colors32 = new Float32Array(this._colors);
  48743. if (this.recomputeNormals) {
  48744. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  48745. }
  48746. this._normals32 = new Float32Array(this._normals);
  48747. this._fixedNormal32 = new Float32Array(this._normals);
  48748. if (this._mustUnrotateFixedNormals) {
  48749. this._unrotateFixedNormals();
  48750. }
  48751. var vertexData = new BABYLON.VertexData();
  48752. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  48753. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  48754. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  48755. if (this._uvs32) {
  48756. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  48757. ;
  48758. }
  48759. if (this._colors32) {
  48760. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  48761. }
  48762. var mesh = new BABYLON.Mesh(this.name, this._scene);
  48763. vertexData.applyToMesh(mesh, this._updatable);
  48764. this.mesh = mesh;
  48765. this.mesh.isPickable = this._pickable;
  48766. // free memory
  48767. if (!this._depthSort) {
  48768. this._indices = null;
  48769. }
  48770. this._positions = null;
  48771. this._normals = null;
  48772. this._uvs = null;
  48773. this._colors = null;
  48774. if (!this._updatable) {
  48775. this.particles.length = 0;
  48776. }
  48777. return mesh;
  48778. };
  48779. /**
  48780. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  48781. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  48782. * Thus the particles generated from `digest()` have their property `position` set yet.
  48783. * @param mesh ( Mesh ) is the mesh to be digested
  48784. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  48785. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  48786. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  48787. * @returns the current SPS
  48788. */
  48789. SolidParticleSystem.prototype.digest = function (mesh, options) {
  48790. var size = (options && options.facetNb) || 1;
  48791. var number = (options && options.number) || 0;
  48792. var delta = (options && options.delta) || 0;
  48793. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48794. var meshInd = mesh.getIndices();
  48795. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48796. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48797. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48798. var f = 0; // facet counter
  48799. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  48800. // compute size from number
  48801. if (number) {
  48802. number = (number > totalFacets) ? totalFacets : number;
  48803. size = Math.round(totalFacets / number);
  48804. delta = 0;
  48805. }
  48806. else {
  48807. size = (size > totalFacets) ? totalFacets : size;
  48808. }
  48809. var facetPos = []; // submesh positions
  48810. var facetInd = []; // submesh indices
  48811. var facetUV = []; // submesh UV
  48812. var facetCol = []; // submesh colors
  48813. var barycenter = BABYLON.Tmp.Vector3[0];
  48814. var sizeO = size;
  48815. while (f < totalFacets) {
  48816. size = sizeO + Math.floor((1 + delta) * Math.random());
  48817. if (f > totalFacets - size) {
  48818. size = totalFacets - f;
  48819. }
  48820. // reset temp arrays
  48821. facetPos.length = 0;
  48822. facetInd.length = 0;
  48823. facetUV.length = 0;
  48824. facetCol.length = 0;
  48825. // iterate over "size" facets
  48826. var fi = 0;
  48827. for (var j = f * 3; j < (f + size) * 3; j++) {
  48828. facetInd.push(fi);
  48829. var i = meshInd[j];
  48830. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  48831. if (meshUV) {
  48832. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  48833. }
  48834. if (meshCol) {
  48835. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  48836. }
  48837. fi++;
  48838. }
  48839. // create a model shape for each single particle
  48840. var idx = this.nbParticles;
  48841. var shape = this._posToShape(facetPos);
  48842. var shapeUV = this._uvsToShapeUV(facetUV);
  48843. // compute the barycenter of the shape
  48844. var v;
  48845. for (v = 0; v < shape.length; v++) {
  48846. barycenter.addInPlace(shape[v]);
  48847. }
  48848. barycenter.scaleInPlace(1 / shape.length);
  48849. // shift the shape from its barycenter to the origin
  48850. for (v = 0; v < shape.length; v++) {
  48851. shape[v].subtractInPlace(barycenter);
  48852. }
  48853. var bInfo;
  48854. if (this._particlesIntersect) {
  48855. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  48856. }
  48857. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  48858. // add the particle in the SPS
  48859. var currentPos = this._positions.length;
  48860. var currentInd = this._indices.length;
  48861. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  48862. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  48863. // initialize the particle position
  48864. this.particles[this.nbParticles].position.addInPlace(barycenter);
  48865. this._index += shape.length;
  48866. idx++;
  48867. this.nbParticles++;
  48868. this._shapeCounter++;
  48869. f += size;
  48870. }
  48871. return this;
  48872. };
  48873. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  48874. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  48875. var index = 0;
  48876. var idx = 0;
  48877. for (var p = 0; p < this.particles.length; p++) {
  48878. this._particle = this.particles[p];
  48879. this._shape = this._particle._model._shape;
  48880. if (this._particle.rotationQuaternion) {
  48881. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  48882. }
  48883. else {
  48884. this._yaw = this._particle.rotation.y;
  48885. this._pitch = this._particle.rotation.x;
  48886. this._roll = this._particle.rotation.z;
  48887. this._quaternionRotationYPR();
  48888. }
  48889. this._quaternionToRotationMatrix();
  48890. this._rotMatrix.invertToRef(this._invertMatrix);
  48891. for (var pt = 0; pt < this._shape.length; pt++) {
  48892. idx = index + pt * 3;
  48893. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  48894. this._fixedNormal32[idx] = this._normal.x;
  48895. this._fixedNormal32[idx + 1] = this._normal.y;
  48896. this._fixedNormal32[idx + 2] = this._normal.z;
  48897. }
  48898. index = idx + 3;
  48899. }
  48900. };
  48901. //reset copy
  48902. SolidParticleSystem.prototype._resetCopy = function () {
  48903. this._copy.position.x = 0;
  48904. this._copy.position.y = 0;
  48905. this._copy.position.z = 0;
  48906. this._copy.rotation.x = 0;
  48907. this._copy.rotation.y = 0;
  48908. this._copy.rotation.z = 0;
  48909. this._copy.rotationQuaternion = null;
  48910. this._copy.scaling.x = 1.0;
  48911. this._copy.scaling.y = 1.0;
  48912. this._copy.scaling.z = 1.0;
  48913. this._copy.uvs.x = 0;
  48914. this._copy.uvs.y = 0;
  48915. this._copy.uvs.z = 1.0;
  48916. this._copy.uvs.w = 1.0;
  48917. this._copy.color = null;
  48918. };
  48919. // _meshBuilder : inserts the shape model in the global SPS mesh
  48920. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  48921. var i;
  48922. var u = 0;
  48923. var c = 0;
  48924. var n = 0;
  48925. this._resetCopy();
  48926. if (options && options.positionFunction) {
  48927. options.positionFunction(this._copy, idx, idxInShape);
  48928. this._mustUnrotateFixedNormals = true;
  48929. }
  48930. if (this._copy.rotationQuaternion) {
  48931. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48932. }
  48933. else {
  48934. this._yaw = this._copy.rotation.y;
  48935. this._pitch = this._copy.rotation.x;
  48936. this._roll = this._copy.rotation.z;
  48937. this._quaternionRotationYPR();
  48938. }
  48939. this._quaternionToRotationMatrix();
  48940. for (i = 0; i < shape.length; i++) {
  48941. this._vertex.x = shape[i].x;
  48942. this._vertex.y = shape[i].y;
  48943. this._vertex.z = shape[i].z;
  48944. if (options && options.vertexFunction) {
  48945. options.vertexFunction(this._copy, this._vertex, i);
  48946. }
  48947. this._vertex.x *= this._copy.scaling.x;
  48948. this._vertex.y *= this._copy.scaling.y;
  48949. this._vertex.z *= this._copy.scaling.z;
  48950. this._vertex.x += this._copy.pivot.x;
  48951. this._vertex.y += this._copy.pivot.y;
  48952. this._vertex.z += this._copy.pivot.z;
  48953. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48954. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  48955. if (meshUV) {
  48956. 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);
  48957. u += 2;
  48958. }
  48959. if (this._copy.color) {
  48960. this._color = this._copy.color;
  48961. }
  48962. else if (meshCol && meshCol[c] !== undefined) {
  48963. this._color.r = meshCol[c];
  48964. this._color.g = meshCol[c + 1];
  48965. this._color.b = meshCol[c + 2];
  48966. this._color.a = meshCol[c + 3];
  48967. }
  48968. else {
  48969. this._color.r = 1.0;
  48970. this._color.g = 1.0;
  48971. this._color.b = 1.0;
  48972. this._color.a = 1.0;
  48973. }
  48974. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  48975. c += 4;
  48976. if (!this.recomputeNormals && meshNor) {
  48977. this._normal.x = meshNor[n];
  48978. this._normal.y = meshNor[n + 1];
  48979. this._normal.z = meshNor[n + 2];
  48980. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  48981. normals.push(this._normal.x, this._normal.y, this._normal.z);
  48982. n += 3;
  48983. }
  48984. }
  48985. for (i = 0; i < meshInd.length; i++) {
  48986. var current_ind = p + meshInd[i];
  48987. indices.push(current_ind);
  48988. if (current_ind > 65535) {
  48989. this._needs32Bits = true;
  48990. }
  48991. }
  48992. if (this._pickable) {
  48993. var nbfaces = meshInd.length / 3;
  48994. for (i = 0; i < nbfaces; i++) {
  48995. this.pickedParticles.push({ idx: idx, faceId: i });
  48996. }
  48997. }
  48998. if (this._depthSort) {
  48999. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  49000. }
  49001. return this._copy;
  49002. };
  49003. // returns a shape array from positions array
  49004. SolidParticleSystem.prototype._posToShape = function (positions) {
  49005. var shape = [];
  49006. for (var i = 0; i < positions.length; i += 3) {
  49007. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49008. }
  49009. return shape;
  49010. };
  49011. // returns a shapeUV array from a Vector4 uvs
  49012. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49013. var shapeUV = [];
  49014. if (uvs) {
  49015. for (var i = 0; i < uvs.length; i++)
  49016. shapeUV.push(uvs[i]);
  49017. }
  49018. return shapeUV;
  49019. };
  49020. // adds a new particle object in the particles array
  49021. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  49022. if (bInfo === void 0) { bInfo = null; }
  49023. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  49024. this.particles.push(sp);
  49025. return sp;
  49026. };
  49027. /**
  49028. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49029. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49030. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  49031. * @param nb (positive integer) the number of particles to be created from this model
  49032. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  49033. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  49034. * @returns the number of shapes in the system
  49035. */
  49036. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49037. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49038. var meshInd = mesh.getIndices();
  49039. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49040. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49041. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49042. var bbInfo;
  49043. if (this._particlesIntersect) {
  49044. bbInfo = mesh.getBoundingInfo();
  49045. }
  49046. var shape = this._posToShape(meshPos);
  49047. var shapeUV = this._uvsToShapeUV(meshUV);
  49048. var posfunc = options ? options.positionFunction : null;
  49049. var vtxfunc = options ? options.vertexFunction : null;
  49050. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  49051. // particles
  49052. var sp;
  49053. var currentCopy;
  49054. var idx = this.nbParticles;
  49055. for (var i = 0; i < nb; i++) {
  49056. var currentPos = this._positions.length;
  49057. var currentInd = this._indices.length;
  49058. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49059. if (this._updatable) {
  49060. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  49061. sp.position.copyFrom(currentCopy.position);
  49062. sp.rotation.copyFrom(currentCopy.rotation);
  49063. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  49064. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  49065. }
  49066. if (currentCopy.color && sp.color) {
  49067. sp.color.copyFrom(currentCopy.color);
  49068. }
  49069. sp.scaling.copyFrom(currentCopy.scaling);
  49070. sp.uvs.copyFrom(currentCopy.uvs);
  49071. }
  49072. this._index += shape.length;
  49073. idx++;
  49074. }
  49075. this.nbParticles += nb;
  49076. this._shapeCounter++;
  49077. return this._shapeCounter - 1;
  49078. };
  49079. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49080. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49081. this._resetCopy();
  49082. if (particle._model._positionFunction) {
  49083. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49084. }
  49085. if (this._copy.rotationQuaternion) {
  49086. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49087. }
  49088. else {
  49089. this._yaw = this._copy.rotation.y;
  49090. this._pitch = this._copy.rotation.x;
  49091. this._roll = this._copy.rotation.z;
  49092. this._quaternionRotationYPR();
  49093. }
  49094. this._quaternionToRotationMatrix();
  49095. this._shape = particle._model._shape;
  49096. for (var pt = 0; pt < this._shape.length; pt++) {
  49097. this._vertex.x = this._shape[pt].x;
  49098. this._vertex.y = this._shape[pt].y;
  49099. this._vertex.z = this._shape[pt].z;
  49100. if (particle._model._vertexFunction) {
  49101. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49102. }
  49103. this._vertex.x *= this._copy.scaling.x;
  49104. this._vertex.y *= this._copy.scaling.y;
  49105. this._vertex.z *= this._copy.scaling.z;
  49106. this._vertex.x += this._copy.pivot.x;
  49107. this._vertex.y += this._copy.pivot.y;
  49108. this._vertex.z += this._copy.pivot.z;
  49109. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49110. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49111. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49112. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49113. }
  49114. particle.position.x = 0.0;
  49115. particle.position.y = 0.0;
  49116. particle.position.z = 0.0;
  49117. particle.rotation.x = 0.0;
  49118. particle.rotation.y = 0.0;
  49119. particle.rotation.z = 0.0;
  49120. particle.rotationQuaternion = null;
  49121. particle.scaling.x = 1.0;
  49122. particle.scaling.y = 1.0;
  49123. particle.scaling.z = 1.0;
  49124. };
  49125. /**
  49126. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49127. * @returns the SPS.
  49128. */
  49129. SolidParticleSystem.prototype.rebuildMesh = function () {
  49130. for (var p = 0; p < this.particles.length; p++) {
  49131. this._rebuildParticle(this.particles[p]);
  49132. }
  49133. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49134. return this;
  49135. };
  49136. /**
  49137. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49138. * This method calls `updateParticle()` for each particle of the SPS.
  49139. * For an animated SPS, it is usually called within the render loop.
  49140. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49141. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49142. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49143. * @returns the SPS.
  49144. */
  49145. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49146. if (start === void 0) { start = 0; }
  49147. if (end === void 0) { end = this.nbParticles - 1; }
  49148. if (update === void 0) { update = true; }
  49149. if (!this._updatable) {
  49150. return this;
  49151. }
  49152. // custom beforeUpdate
  49153. this.beforeUpdateParticles(start, end, update);
  49154. this._cam_axisX.x = 1.0;
  49155. this._cam_axisX.y = 0.0;
  49156. this._cam_axisX.z = 0.0;
  49157. this._cam_axisY.x = 0.0;
  49158. this._cam_axisY.y = 1.0;
  49159. this._cam_axisY.z = 0.0;
  49160. this._cam_axisZ.x = 0.0;
  49161. this._cam_axisZ.y = 0.0;
  49162. this._cam_axisZ.z = 1.0;
  49163. // cases when the World Matrix is to be computed first
  49164. if (this.billboard || this._depthSort) {
  49165. this.mesh.computeWorldMatrix(true);
  49166. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  49167. }
  49168. // if the particles will always face the camera
  49169. if (this.billboard) {
  49170. // compute the camera position and un-rotate it by the current mesh rotation
  49171. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  49172. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49173. this._cam_axisZ.normalize();
  49174. // same for camera up vector extracted from the cam view matrix
  49175. var view = this._camera.getViewMatrix(true);
  49176. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  49177. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49178. this._cam_axisY.normalize();
  49179. this._cam_axisX.normalize();
  49180. }
  49181. // if depthSort, compute the camera global position in the mesh local system
  49182. if (this._depthSort) {
  49183. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  49184. }
  49185. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49186. var idx = 0; // current position index in the global array positions32
  49187. var index = 0; // position start index in the global array positions32 of the current particle
  49188. var colidx = 0; // current color index in the global array colors32
  49189. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  49190. var uvidx = 0; // current uv index in the global array uvs32
  49191. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  49192. var pt = 0; // current index in the particle model shape
  49193. if (this.mesh.isFacetDataEnabled) {
  49194. this._computeBoundingBox = true;
  49195. }
  49196. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  49197. if (this._computeBoundingBox) {
  49198. if (start == 0 && end == this.nbParticles - 1) {
  49199. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49200. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49201. }
  49202. else {
  49203. if (this.mesh._boundingInfo) {
  49204. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  49205. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  49206. }
  49207. }
  49208. }
  49209. // particle loop
  49210. index = this.particles[start]._pos;
  49211. var vpos = (index / 3) | 0;
  49212. colorIndex = vpos * 4;
  49213. uvIndex = vpos * 2;
  49214. for (var p = start; p <= end; p++) {
  49215. this._particle = this.particles[p];
  49216. this._shape = this._particle._model._shape;
  49217. this._shapeUV = this._particle._model._shapeUV;
  49218. // call to custom user function to update the particle properties
  49219. this.updateParticle(this._particle);
  49220. // camera-particle distance for depth sorting
  49221. if (this._depthSort && this._depthSortParticles) {
  49222. var dsp = this.depthSortedParticles[p];
  49223. dsp.ind = this._particle._ind;
  49224. dsp.indicesLength = this._particle._model._indicesLength;
  49225. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  49226. }
  49227. // skip the computations for inactive or already invisible particles
  49228. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  49229. // increment indexes for the next particle
  49230. pt = this._shape.length;
  49231. index += pt * 3;
  49232. colorIndex += pt * 4;
  49233. uvIndex += pt * 2;
  49234. continue;
  49235. }
  49236. if (this._particle.isVisible) {
  49237. this._particle._stillInvisible = false; // un-mark permanent invisibility
  49238. // particle rotation matrix
  49239. if (this.billboard) {
  49240. this._particle.rotation.x = 0.0;
  49241. this._particle.rotation.y = 0.0;
  49242. }
  49243. if (this._computeParticleRotation || this.billboard) {
  49244. if (this._particle.rotationQuaternion) {
  49245. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49246. }
  49247. else {
  49248. this._yaw = this._particle.rotation.y;
  49249. this._pitch = this._particle.rotation.x;
  49250. this._roll = this._particle.rotation.z;
  49251. this._quaternionRotationYPR();
  49252. }
  49253. this._quaternionToRotationMatrix();
  49254. }
  49255. // particle vertex loop
  49256. for (pt = 0; pt < this._shape.length; pt++) {
  49257. idx = index + pt * 3;
  49258. colidx = colorIndex + pt * 4;
  49259. uvidx = uvIndex + pt * 2;
  49260. this._vertex.x = this._shape[pt].x;
  49261. this._vertex.y = this._shape[pt].y;
  49262. this._vertex.z = this._shape[pt].z;
  49263. if (this._computeParticleVertex) {
  49264. this.updateParticleVertex(this._particle, this._vertex, pt);
  49265. }
  49266. // positions
  49267. this._vertex.x *= this._particle.scaling.x;
  49268. this._vertex.y *= this._particle.scaling.y;
  49269. this._vertex.z *= this._particle.scaling.z;
  49270. this._vertex.x += this._particle.pivot.x;
  49271. this._vertex.y += this._particle.pivot.y;
  49272. this._vertex.z += this._particle.pivot.z;
  49273. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49274. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49275. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49276. 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;
  49277. 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;
  49278. 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;
  49279. if (this._computeBoundingBox) {
  49280. if (this._positions32[idx] < this._minimum.x) {
  49281. this._minimum.x = this._positions32[idx];
  49282. }
  49283. if (this._positions32[idx] > this._maximum.x) {
  49284. this._maximum.x = this._positions32[idx];
  49285. }
  49286. if (this._positions32[idx + 1] < this._minimum.y) {
  49287. this._minimum.y = this._positions32[idx + 1];
  49288. }
  49289. if (this._positions32[idx + 1] > this._maximum.y) {
  49290. this._maximum.y = this._positions32[idx + 1];
  49291. }
  49292. if (this._positions32[idx + 2] < this._minimum.z) {
  49293. this._minimum.z = this._positions32[idx + 2];
  49294. }
  49295. if (this._positions32[idx + 2] > this._maximum.z) {
  49296. this._maximum.z = this._positions32[idx + 2];
  49297. }
  49298. }
  49299. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  49300. if (!this._computeParticleVertex) {
  49301. this._normal.x = this._fixedNormal32[idx];
  49302. this._normal.y = this._fixedNormal32[idx + 1];
  49303. this._normal.z = this._fixedNormal32[idx + 2];
  49304. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  49305. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  49306. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  49307. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49308. 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;
  49309. 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;
  49310. }
  49311. if (this._computeParticleColor && this._particle.color) {
  49312. this._colors32[colidx] = this._particle.color.r;
  49313. this._colors32[colidx + 1] = this._particle.color.g;
  49314. this._colors32[colidx + 2] = this._particle.color.b;
  49315. this._colors32[colidx + 3] = this._particle.color.a;
  49316. }
  49317. if (this._computeParticleTexture) {
  49318. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49319. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49320. }
  49321. }
  49322. }
  49323. else {
  49324. this._particle._stillInvisible = true; // mark the particle as invisible
  49325. for (pt = 0; pt < this._shape.length; pt++) {
  49326. idx = index + pt * 3;
  49327. colidx = colorIndex + pt * 4;
  49328. uvidx = uvIndex + pt * 2;
  49329. this._positions32[idx] = 0.0;
  49330. this._positions32[idx + 1] = 0.0;
  49331. this._positions32[idx + 2] = 0.0;
  49332. this._normals32[idx] = 0.0;
  49333. this._normals32[idx + 1] = 0.0;
  49334. this._normals32[idx + 2] = 0.0;
  49335. if (this._computeParticleColor && this._particle.color) {
  49336. this._colors32[colidx] = this._particle.color.r;
  49337. this._colors32[colidx + 1] = this._particle.color.g;
  49338. this._colors32[colidx + 2] = this._particle.color.b;
  49339. this._colors32[colidx + 3] = this._particle.color.a;
  49340. }
  49341. if (this._computeParticleTexture) {
  49342. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49343. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49344. }
  49345. }
  49346. }
  49347. // if the particle intersections must be computed : update the bbInfo
  49348. if (this._particlesIntersect) {
  49349. var bInfo = this._particle._boundingInfo;
  49350. var bBox = bInfo.boundingBox;
  49351. var bSphere = bInfo.boundingSphere;
  49352. if (!this._bSphereOnly) {
  49353. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49354. for (var b = 0; b < bBox.vectors.length; b++) {
  49355. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49356. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49357. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49358. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49359. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49360. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49361. 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;
  49362. 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;
  49363. 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;
  49364. }
  49365. bBox._update(this.mesh._worldMatrix);
  49366. }
  49367. // place and scale the particle bouding sphere in the SPS local system, then update it
  49368. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49369. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49370. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49371. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49372. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49373. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49374. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49375. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49376. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49377. 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));
  49378. bSphere._update(this.mesh._worldMatrix);
  49379. }
  49380. // increment indexes for the next particle
  49381. index = idx + 3;
  49382. colorIndex = colidx + 4;
  49383. uvIndex = uvidx + 2;
  49384. }
  49385. // if the VBO must be updated
  49386. if (update) {
  49387. if (this._computeParticleColor) {
  49388. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49389. }
  49390. if (this._computeParticleTexture) {
  49391. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49392. }
  49393. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49394. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  49395. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  49396. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49397. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  49398. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  49399. for (var i = 0; i < this._normals32.length; i++) {
  49400. this._fixedNormal32[i] = this._normals32[i];
  49401. }
  49402. }
  49403. if (!this.mesh.areNormalsFrozen) {
  49404. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49405. }
  49406. }
  49407. if (this._depthSort && this._depthSortParticles) {
  49408. this.depthSortedParticles.sort(this._depthSortFunction);
  49409. var dspl = this.depthSortedParticles.length;
  49410. var sorted = 0;
  49411. var lind = 0;
  49412. var sind = 0;
  49413. var sid = 0;
  49414. for (sorted = 0; sorted < dspl; sorted++) {
  49415. lind = this.depthSortedParticles[sorted].indicesLength;
  49416. sind = this.depthSortedParticles[sorted].ind;
  49417. for (var i = 0; i < lind; i++) {
  49418. this._indices32[sid] = this._indices[sind + i];
  49419. sid++;
  49420. }
  49421. }
  49422. this.mesh.updateIndices(this._indices32);
  49423. }
  49424. }
  49425. if (this._computeBoundingBox) {
  49426. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49427. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49428. }
  49429. this.afterUpdateParticles(start, end, update);
  49430. return this;
  49431. };
  49432. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49433. this._halfroll = this._roll * 0.5;
  49434. this._halfpitch = this._pitch * 0.5;
  49435. this._halfyaw = this._yaw * 0.5;
  49436. this._sinRoll = Math.sin(this._halfroll);
  49437. this._cosRoll = Math.cos(this._halfroll);
  49438. this._sinPitch = Math.sin(this._halfpitch);
  49439. this._cosPitch = Math.cos(this._halfpitch);
  49440. this._sinYaw = Math.sin(this._halfyaw);
  49441. this._cosYaw = Math.cos(this._halfyaw);
  49442. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  49443. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  49444. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  49445. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  49446. };
  49447. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49448. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49449. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49450. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49451. this._rotMatrix.m[3] = 0;
  49452. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49453. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49454. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49455. this._rotMatrix.m[7] = 0;
  49456. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49457. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49458. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49459. this._rotMatrix.m[11] = 0;
  49460. this._rotMatrix.m[12] = 0;
  49461. this._rotMatrix.m[13] = 0;
  49462. this._rotMatrix.m[14] = 0;
  49463. this._rotMatrix.m[15] = 1.0;
  49464. };
  49465. /**
  49466. * Disposes the SPS.
  49467. */
  49468. SolidParticleSystem.prototype.dispose = function () {
  49469. this.mesh.dispose();
  49470. this.vars = null;
  49471. // drop references to internal big arrays for the GC
  49472. this._positions = null;
  49473. this._indices = null;
  49474. this._normals = null;
  49475. this._uvs = null;
  49476. this._colors = null;
  49477. this._indices32 = null;
  49478. this._positions32 = null;
  49479. this._normals32 = null;
  49480. this._fixedNormal32 = null;
  49481. this._uvs32 = null;
  49482. this._colors32 = null;
  49483. this.pickedParticles = null;
  49484. };
  49485. /**
  49486. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49487. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49488. * @returns the SPS.
  49489. */
  49490. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49491. if (!this._isVisibilityBoxLocked) {
  49492. this.mesh.refreshBoundingInfo();
  49493. }
  49494. return this;
  49495. };
  49496. /**
  49497. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49498. * @param size the size (float) of the visibility box
  49499. * note : this doesn't lock the SPS mesh bounding box.
  49500. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49501. */
  49502. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49503. var vis = size / 2;
  49504. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49505. };
  49506. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49507. /**
  49508. * Gets whether the SPS as always visible or not
  49509. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49510. */
  49511. get: function () {
  49512. return this._alwaysVisible;
  49513. },
  49514. /**
  49515. * Sets the SPS as always visible or not
  49516. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49517. */
  49518. set: function (val) {
  49519. this._alwaysVisible = val;
  49520. this.mesh.alwaysSelectAsActiveMesh = val;
  49521. },
  49522. enumerable: true,
  49523. configurable: true
  49524. });
  49525. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49526. /**
  49527. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49528. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49529. */
  49530. get: function () {
  49531. return this._isVisibilityBoxLocked;
  49532. },
  49533. /**
  49534. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49535. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49536. */
  49537. set: function (val) {
  49538. this._isVisibilityBoxLocked = val;
  49539. var boundingInfo = this.mesh.getBoundingInfo();
  49540. boundingInfo.isLocked = val;
  49541. },
  49542. enumerable: true,
  49543. configurable: true
  49544. });
  49545. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49546. /**
  49547. * Gets if `setParticles()` computes the particle rotations or not.
  49548. * Default value : true. The SPS is faster when it's set to false.
  49549. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49550. */
  49551. get: function () {
  49552. return this._computeParticleRotation;
  49553. },
  49554. /**
  49555. * Tells to `setParticles()` to compute the particle rotations or not.
  49556. * Default value : true. The SPS is faster when it's set to false.
  49557. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49558. */
  49559. set: function (val) {
  49560. this._computeParticleRotation = val;
  49561. },
  49562. enumerable: true,
  49563. configurable: true
  49564. });
  49565. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49566. /**
  49567. * Gets if `setParticles()` computes the particle colors or not.
  49568. * Default value : true. The SPS is faster when it's set to false.
  49569. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49570. */
  49571. get: function () {
  49572. return this._computeParticleColor;
  49573. },
  49574. /**
  49575. * Tells to `setParticles()` to compute the particle colors or not.
  49576. * Default value : true. The SPS is faster when it's set to false.
  49577. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49578. */
  49579. set: function (val) {
  49580. this._computeParticleColor = val;
  49581. },
  49582. enumerable: true,
  49583. configurable: true
  49584. });
  49585. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49586. /**
  49587. * Gets if `setParticles()` computes the particle textures or not.
  49588. * Default value : true. The SPS is faster when it's set to false.
  49589. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49590. */
  49591. get: function () {
  49592. return this._computeParticleTexture;
  49593. },
  49594. set: function (val) {
  49595. this._computeParticleTexture = val;
  49596. },
  49597. enumerable: true,
  49598. configurable: true
  49599. });
  49600. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49601. /**
  49602. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  49603. * Default value : false. The SPS is faster when it's set to false.
  49604. * Note : the particle custom vertex positions aren't stored values.
  49605. */
  49606. get: function () {
  49607. return this._computeParticleVertex;
  49608. },
  49609. /**
  49610. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49611. * Default value : false. The SPS is faster when it's set to false.
  49612. * Note : the particle custom vertex positions aren't stored values.
  49613. */
  49614. set: function (val) {
  49615. this._computeParticleVertex = val;
  49616. },
  49617. enumerable: true,
  49618. configurable: true
  49619. });
  49620. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49621. /**
  49622. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  49623. */
  49624. get: function () {
  49625. return this._computeBoundingBox;
  49626. },
  49627. /**
  49628. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49629. */
  49630. set: function (val) {
  49631. this._computeBoundingBox = val;
  49632. },
  49633. enumerable: true,
  49634. configurable: true
  49635. });
  49636. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  49637. /**
  49638. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  49639. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  49640. * Default : `true`
  49641. */
  49642. get: function () {
  49643. return this._depthSortParticles;
  49644. },
  49645. /**
  49646. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  49647. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  49648. * Default : `true`
  49649. */
  49650. set: function (val) {
  49651. this._depthSortParticles = val;
  49652. },
  49653. enumerable: true,
  49654. configurable: true
  49655. });
  49656. // =======================================================================
  49657. // Particle behavior logic
  49658. // these following methods may be overwritten by the user to fit his needs
  49659. /**
  49660. * This function does nothing. It may be overwritten to set all the particle first values.
  49661. * The SPS doesn't call this function, you may have to call it by your own.
  49662. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49663. */
  49664. SolidParticleSystem.prototype.initParticles = function () {
  49665. };
  49666. /**
  49667. * This function does nothing. It may be overwritten to recycle a particle.
  49668. * The SPS doesn't call this function, you may have to call it by your own.
  49669. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49670. * @param particle The particle to recycle
  49671. * @returns the recycled particle
  49672. */
  49673. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49674. return particle;
  49675. };
  49676. /**
  49677. * Updates a particle : this function should be overwritten by the user.
  49678. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49679. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49680. * @example : just set a particle position or velocity and recycle conditions
  49681. * @param particle The particle to update
  49682. * @returns the updated particle
  49683. */
  49684. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49685. return particle;
  49686. };
  49687. /**
  49688. * Updates a vertex of a particle : it can be overwritten by the user.
  49689. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49690. * @param particle the current particle
  49691. * @param vertex the current index of the current particle
  49692. * @param pt the index of the current vertex in the particle shape
  49693. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49694. * @example : just set a vertex particle position
  49695. * @returns the updated vertex
  49696. */
  49697. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49698. return vertex;
  49699. };
  49700. /**
  49701. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49702. * This does nothing and may be overwritten by the user.
  49703. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49704. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49705. * @param update the boolean update value actually passed to setParticles()
  49706. */
  49707. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49708. };
  49709. /**
  49710. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49711. * This will be passed three parameters.
  49712. * This does nothing and may be overwritten by the user.
  49713. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49714. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49715. * @param update the boolean update value actually passed to setParticles()
  49716. */
  49717. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49718. };
  49719. return SolidParticleSystem;
  49720. }());
  49721. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49722. })(BABYLON || (BABYLON = {}));
  49723. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  49724. var BABYLON;
  49725. (function (BABYLON) {
  49726. var ShaderMaterial = /** @class */ (function (_super) {
  49727. __extends(ShaderMaterial, _super);
  49728. function ShaderMaterial(name, scene, shaderPath, options) {
  49729. var _this = _super.call(this, name, scene) || this;
  49730. _this._textures = {};
  49731. _this._textureArrays = {};
  49732. _this._floats = {};
  49733. _this._ints = {};
  49734. _this._floatsArrays = {};
  49735. _this._colors3 = {};
  49736. _this._colors3Arrays = {};
  49737. _this._colors4 = {};
  49738. _this._vectors2 = {};
  49739. _this._vectors3 = {};
  49740. _this._vectors4 = {};
  49741. _this._matrices = {};
  49742. _this._matrices3x3 = {};
  49743. _this._matrices2x2 = {};
  49744. _this._vectors2Arrays = {};
  49745. _this._vectors3Arrays = {};
  49746. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  49747. _this._shaderPath = shaderPath;
  49748. options.needAlphaBlending = options.needAlphaBlending || false;
  49749. options.needAlphaTesting = options.needAlphaTesting || false;
  49750. options.attributes = options.attributes || ["position", "normal", "uv"];
  49751. options.uniforms = options.uniforms || ["worldViewProjection"];
  49752. options.uniformBuffers = options.uniformBuffers || [];
  49753. options.samplers = options.samplers || [];
  49754. options.defines = options.defines || [];
  49755. _this._options = options;
  49756. return _this;
  49757. }
  49758. ShaderMaterial.prototype.getClassName = function () {
  49759. return "ShaderMaterial";
  49760. };
  49761. ShaderMaterial.prototype.needAlphaBlending = function () {
  49762. return this._options.needAlphaBlending;
  49763. };
  49764. ShaderMaterial.prototype.needAlphaTesting = function () {
  49765. return this._options.needAlphaTesting;
  49766. };
  49767. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  49768. if (this._options.uniforms.indexOf(uniformName) === -1) {
  49769. this._options.uniforms.push(uniformName);
  49770. }
  49771. };
  49772. ShaderMaterial.prototype.setTexture = function (name, texture) {
  49773. if (this._options.samplers.indexOf(name) === -1) {
  49774. this._options.samplers.push(name);
  49775. }
  49776. this._textures[name] = texture;
  49777. return this;
  49778. };
  49779. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  49780. if (this._options.samplers.indexOf(name) === -1) {
  49781. this._options.samplers.push(name);
  49782. }
  49783. this._checkUniform(name);
  49784. this._textureArrays[name] = textures;
  49785. return this;
  49786. };
  49787. ShaderMaterial.prototype.setFloat = function (name, value) {
  49788. this._checkUniform(name);
  49789. this._floats[name] = value;
  49790. return this;
  49791. };
  49792. ShaderMaterial.prototype.setInt = function (name, value) {
  49793. this._checkUniform(name);
  49794. this._ints[name] = value;
  49795. return this;
  49796. };
  49797. ShaderMaterial.prototype.setFloats = function (name, value) {
  49798. this._checkUniform(name);
  49799. this._floatsArrays[name] = value;
  49800. return this;
  49801. };
  49802. ShaderMaterial.prototype.setColor3 = function (name, value) {
  49803. this._checkUniform(name);
  49804. this._colors3[name] = value;
  49805. return this;
  49806. };
  49807. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  49808. this._checkUniform(name);
  49809. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  49810. color.toArray(arr, arr.length);
  49811. return arr;
  49812. }, []);
  49813. return this;
  49814. };
  49815. ShaderMaterial.prototype.setColor4 = function (name, value) {
  49816. this._checkUniform(name);
  49817. this._colors4[name] = value;
  49818. return this;
  49819. };
  49820. ShaderMaterial.prototype.setVector2 = function (name, value) {
  49821. this._checkUniform(name);
  49822. this._vectors2[name] = value;
  49823. return this;
  49824. };
  49825. ShaderMaterial.prototype.setVector3 = function (name, value) {
  49826. this._checkUniform(name);
  49827. this._vectors3[name] = value;
  49828. return this;
  49829. };
  49830. ShaderMaterial.prototype.setVector4 = function (name, value) {
  49831. this._checkUniform(name);
  49832. this._vectors4[name] = value;
  49833. return this;
  49834. };
  49835. ShaderMaterial.prototype.setMatrix = function (name, value) {
  49836. this._checkUniform(name);
  49837. this._matrices[name] = value;
  49838. return this;
  49839. };
  49840. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  49841. this._checkUniform(name);
  49842. this._matrices3x3[name] = value;
  49843. return this;
  49844. };
  49845. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  49846. this._checkUniform(name);
  49847. this._matrices2x2[name] = value;
  49848. return this;
  49849. };
  49850. ShaderMaterial.prototype.setArray2 = function (name, value) {
  49851. this._checkUniform(name);
  49852. this._vectors2Arrays[name] = value;
  49853. return this;
  49854. };
  49855. ShaderMaterial.prototype.setArray3 = function (name, value) {
  49856. this._checkUniform(name);
  49857. this._vectors3Arrays[name] = value;
  49858. return this;
  49859. };
  49860. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  49861. if (!mesh) {
  49862. return true;
  49863. }
  49864. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  49865. return false;
  49866. }
  49867. return false;
  49868. };
  49869. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  49870. var scene = this.getScene();
  49871. var engine = scene.getEngine();
  49872. if (!this.checkReadyOnEveryCall) {
  49873. if (this._renderId === scene.getRenderId()) {
  49874. if (this._checkCache(scene, mesh, useInstances)) {
  49875. return true;
  49876. }
  49877. }
  49878. }
  49879. // Instances
  49880. var defines = [];
  49881. var attribs = [];
  49882. var fallbacks = new BABYLON.EffectFallbacks();
  49883. if (useInstances) {
  49884. defines.push("#define INSTANCES");
  49885. }
  49886. for (var index = 0; index < this._options.defines.length; index++) {
  49887. defines.push(this._options.defines[index]);
  49888. }
  49889. for (var index = 0; index < this._options.attributes.length; index++) {
  49890. attribs.push(this._options.attributes[index]);
  49891. }
  49892. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  49893. attribs.push(BABYLON.VertexBuffer.ColorKind);
  49894. defines.push("#define VERTEXCOLOR");
  49895. }
  49896. // Bones
  49897. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  49898. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49899. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49900. if (mesh.numBoneInfluencers > 4) {
  49901. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49902. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49903. }
  49904. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49905. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49906. fallbacks.addCPUSkinningFallback(0, mesh);
  49907. if (this._options.uniforms.indexOf("mBones") === -1) {
  49908. this._options.uniforms.push("mBones");
  49909. }
  49910. }
  49911. else {
  49912. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49913. }
  49914. // Textures
  49915. for (var name in this._textures) {
  49916. if (!this._textures[name].isReady()) {
  49917. return false;
  49918. }
  49919. }
  49920. // Alpha test
  49921. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  49922. defines.push("#define ALPHATEST");
  49923. }
  49924. var previousEffect = this._effect;
  49925. var join = defines.join("\n");
  49926. this._effect = engine.createEffect(this._shaderPath, {
  49927. attributes: attribs,
  49928. uniformsNames: this._options.uniforms,
  49929. uniformBuffersNames: this._options.uniformBuffers,
  49930. samplers: this._options.samplers,
  49931. defines: join,
  49932. fallbacks: fallbacks,
  49933. onCompiled: this.onCompiled,
  49934. onError: this.onError
  49935. }, engine);
  49936. if (!this._effect.isReady()) {
  49937. return false;
  49938. }
  49939. if (previousEffect !== this._effect) {
  49940. scene.resetCachedMaterial();
  49941. }
  49942. this._renderId = scene.getRenderId();
  49943. return true;
  49944. };
  49945. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  49946. var scene = this.getScene();
  49947. if (!this._effect) {
  49948. return;
  49949. }
  49950. if (this._options.uniforms.indexOf("world") !== -1) {
  49951. this._effect.setMatrix("world", world);
  49952. }
  49953. if (this._options.uniforms.indexOf("worldView") !== -1) {
  49954. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  49955. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  49956. }
  49957. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  49958. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  49959. }
  49960. };
  49961. ShaderMaterial.prototype.bind = function (world, mesh) {
  49962. // Std values
  49963. this.bindOnlyWorldMatrix(world);
  49964. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  49965. if (this._options.uniforms.indexOf("view") !== -1) {
  49966. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  49967. }
  49968. if (this._options.uniforms.indexOf("projection") !== -1) {
  49969. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  49970. }
  49971. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  49972. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  49973. }
  49974. // Bones
  49975. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  49976. var name;
  49977. // Texture
  49978. for (name in this._textures) {
  49979. this._effect.setTexture(name, this._textures[name]);
  49980. }
  49981. // Texture arrays
  49982. for (name in this._textureArrays) {
  49983. this._effect.setTextureArray(name, this._textureArrays[name]);
  49984. }
  49985. // Int
  49986. for (name in this._ints) {
  49987. this._effect.setInt(name, this._ints[name]);
  49988. }
  49989. // Float
  49990. for (name in this._floats) {
  49991. this._effect.setFloat(name, this._floats[name]);
  49992. }
  49993. // Floats
  49994. for (name in this._floatsArrays) {
  49995. this._effect.setArray(name, this._floatsArrays[name]);
  49996. }
  49997. // Color3
  49998. for (name in this._colors3) {
  49999. this._effect.setColor3(name, this._colors3[name]);
  50000. }
  50001. for (name in this._colors3Arrays) {
  50002. this._effect.setArray3(name, this._colors3Arrays[name]);
  50003. }
  50004. // Color4
  50005. for (name in this._colors4) {
  50006. var color = this._colors4[name];
  50007. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50008. }
  50009. // Vector2
  50010. for (name in this._vectors2) {
  50011. this._effect.setVector2(name, this._vectors2[name]);
  50012. }
  50013. // Vector3
  50014. for (name in this._vectors3) {
  50015. this._effect.setVector3(name, this._vectors3[name]);
  50016. }
  50017. // Vector4
  50018. for (name in this._vectors4) {
  50019. this._effect.setVector4(name, this._vectors4[name]);
  50020. }
  50021. // Matrix
  50022. for (name in this._matrices) {
  50023. this._effect.setMatrix(name, this._matrices[name]);
  50024. }
  50025. // Matrix 3x3
  50026. for (name in this._matrices3x3) {
  50027. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  50028. }
  50029. // Matrix 2x2
  50030. for (name in this._matrices2x2) {
  50031. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  50032. }
  50033. // Vector2Array
  50034. for (name in this._vectors2Arrays) {
  50035. this._effect.setArray2(name, this._vectors2Arrays[name]);
  50036. }
  50037. // Vector3Array
  50038. for (name in this._vectors3Arrays) {
  50039. this._effect.setArray3(name, this._vectors3Arrays[name]);
  50040. }
  50041. }
  50042. this._afterBind(mesh);
  50043. };
  50044. ShaderMaterial.prototype.getActiveTextures = function () {
  50045. var activeTextures = _super.prototype.getActiveTextures.call(this);
  50046. for (var name in this._textures) {
  50047. activeTextures.push(this._textures[name]);
  50048. }
  50049. for (var name in this._textureArrays) {
  50050. var array = this._textureArrays[name];
  50051. for (var index = 0; index < array.length; index++) {
  50052. activeTextures.push(array[index]);
  50053. }
  50054. }
  50055. return activeTextures;
  50056. };
  50057. ShaderMaterial.prototype.hasTexture = function (texture) {
  50058. if (_super.prototype.hasTexture.call(this, texture)) {
  50059. return true;
  50060. }
  50061. for (var name in this._textures) {
  50062. if (this._textures[name] === texture) {
  50063. return true;
  50064. }
  50065. }
  50066. for (var name in this._textureArrays) {
  50067. var array = this._textureArrays[name];
  50068. for (var index = 0; index < array.length; index++) {
  50069. if (array[index] === texture) {
  50070. return true;
  50071. }
  50072. }
  50073. }
  50074. return false;
  50075. };
  50076. ShaderMaterial.prototype.clone = function (name) {
  50077. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  50078. return newShaderMaterial;
  50079. };
  50080. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50081. if (forceDisposeTextures) {
  50082. var name;
  50083. for (name in this._textures) {
  50084. this._textures[name].dispose();
  50085. }
  50086. for (name in this._textureArrays) {
  50087. var array = this._textureArrays[name];
  50088. for (var index = 0; index < array.length; index++) {
  50089. array[index].dispose();
  50090. }
  50091. }
  50092. }
  50093. this._textures = {};
  50094. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50095. };
  50096. ShaderMaterial.prototype.serialize = function () {
  50097. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50098. serializationObject.customType = "BABYLON.ShaderMaterial";
  50099. serializationObject.options = this._options;
  50100. serializationObject.shaderPath = this._shaderPath;
  50101. var name;
  50102. // Texture
  50103. serializationObject.textures = {};
  50104. for (name in this._textures) {
  50105. serializationObject.textures[name] = this._textures[name].serialize();
  50106. }
  50107. // Texture arrays
  50108. serializationObject.textureArrays = {};
  50109. for (name in this._textureArrays) {
  50110. serializationObject.textureArrays[name] = [];
  50111. var array = this._textureArrays[name];
  50112. for (var index = 0; index < array.length; index++) {
  50113. serializationObject.textureArrays[name].push(array[index].serialize());
  50114. }
  50115. }
  50116. // Float
  50117. serializationObject.floats = {};
  50118. for (name in this._floats) {
  50119. serializationObject.floats[name] = this._floats[name];
  50120. }
  50121. // Float s
  50122. serializationObject.FloatArrays = {};
  50123. for (name in this._floatsArrays) {
  50124. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  50125. }
  50126. // Color3
  50127. serializationObject.colors3 = {};
  50128. for (name in this._colors3) {
  50129. serializationObject.colors3[name] = this._colors3[name].asArray();
  50130. }
  50131. // Color3 array
  50132. serializationObject.colors3Arrays = {};
  50133. for (name in this._colors3Arrays) {
  50134. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  50135. }
  50136. // Color4
  50137. serializationObject.colors4 = {};
  50138. for (name in this._colors4) {
  50139. serializationObject.colors4[name] = this._colors4[name].asArray();
  50140. }
  50141. // Vector2
  50142. serializationObject.vectors2 = {};
  50143. for (name in this._vectors2) {
  50144. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  50145. }
  50146. // Vector3
  50147. serializationObject.vectors3 = {};
  50148. for (name in this._vectors3) {
  50149. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  50150. }
  50151. // Vector4
  50152. serializationObject.vectors4 = {};
  50153. for (name in this._vectors4) {
  50154. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  50155. }
  50156. // Matrix
  50157. serializationObject.matrices = {};
  50158. for (name in this._matrices) {
  50159. serializationObject.matrices[name] = this._matrices[name].asArray();
  50160. }
  50161. // Matrix 3x3
  50162. serializationObject.matrices3x3 = {};
  50163. for (name in this._matrices3x3) {
  50164. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  50165. }
  50166. // Matrix 2x2
  50167. serializationObject.matrices2x2 = {};
  50168. for (name in this._matrices2x2) {
  50169. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  50170. }
  50171. // Vector2Array
  50172. serializationObject.vectors2Arrays = {};
  50173. for (name in this._vectors2Arrays) {
  50174. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  50175. }
  50176. // Vector3Array
  50177. serializationObject.vectors3Arrays = {};
  50178. for (name in this._vectors3Arrays) {
  50179. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  50180. }
  50181. return serializationObject;
  50182. };
  50183. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  50184. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  50185. var name;
  50186. // Texture
  50187. for (name in source.textures) {
  50188. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  50189. }
  50190. // Texture arrays
  50191. for (name in source.textureArrays) {
  50192. var array = source.textureArrays[name];
  50193. var textureArray = new Array();
  50194. for (var index = 0; index < array.length; index++) {
  50195. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  50196. }
  50197. material.setTextureArray(name, textureArray);
  50198. }
  50199. // Float
  50200. for (name in source.floats) {
  50201. material.setFloat(name, source.floats[name]);
  50202. }
  50203. // Float s
  50204. for (name in source.floatsArrays) {
  50205. material.setFloats(name, source.floatsArrays[name]);
  50206. }
  50207. // Color3
  50208. for (name in source.colors3) {
  50209. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  50210. }
  50211. // Color3 arrays
  50212. for (name in source.colors3Arrays) {
  50213. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  50214. if (i % 3 === 0) {
  50215. arr.push([num]);
  50216. }
  50217. else {
  50218. arr[arr.length - 1].push(num);
  50219. }
  50220. return arr;
  50221. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  50222. material.setColor3Array(name, colors);
  50223. }
  50224. // Color4
  50225. for (name in source.colors4) {
  50226. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  50227. }
  50228. // Vector2
  50229. for (name in source.vectors2) {
  50230. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  50231. }
  50232. // Vector3
  50233. for (name in source.vectors3) {
  50234. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  50235. }
  50236. // Vector4
  50237. for (name in source.vectors4) {
  50238. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  50239. }
  50240. // Matrix
  50241. for (name in source.matrices) {
  50242. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  50243. }
  50244. // Matrix 3x3
  50245. for (name in source.matrices3x3) {
  50246. material.setMatrix3x3(name, source.matrices3x3[name]);
  50247. }
  50248. // Matrix 2x2
  50249. for (name in source.matrices2x2) {
  50250. material.setMatrix2x2(name, source.matrices2x2[name]);
  50251. }
  50252. // Vector2Array
  50253. for (name in source.vectors2Arrays) {
  50254. material.setArray2(name, source.vectors2Arrays[name]);
  50255. }
  50256. // Vector3Array
  50257. for (name in source.vectors3Arrays) {
  50258. material.setArray3(name, source.vectors3Arrays[name]);
  50259. }
  50260. return material;
  50261. };
  50262. return ShaderMaterial;
  50263. }(BABYLON.Material));
  50264. BABYLON.ShaderMaterial = ShaderMaterial;
  50265. })(BABYLON || (BABYLON = {}));
  50266. //# sourceMappingURL=babylon.shaderMaterial.js.map
  50267. var BABYLON;
  50268. (function (BABYLON) {
  50269. var GroundMesh = /** @class */ (function (_super) {
  50270. __extends(GroundMesh, _super);
  50271. function GroundMesh(name, scene) {
  50272. var _this = _super.call(this, name, scene) || this;
  50273. _this.generateOctree = false;
  50274. return _this;
  50275. }
  50276. GroundMesh.prototype.getClassName = function () {
  50277. return "GroundMesh";
  50278. };
  50279. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  50280. get: function () {
  50281. return Math.min(this._subdivisionsX, this._subdivisionsY);
  50282. },
  50283. enumerable: true,
  50284. configurable: true
  50285. });
  50286. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  50287. get: function () {
  50288. return this._subdivisionsX;
  50289. },
  50290. enumerable: true,
  50291. configurable: true
  50292. });
  50293. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  50294. get: function () {
  50295. return this._subdivisionsY;
  50296. },
  50297. enumerable: true,
  50298. configurable: true
  50299. });
  50300. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  50301. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  50302. this._subdivisionsX = chunksCount;
  50303. this._subdivisionsY = chunksCount;
  50304. this.subdivide(chunksCount);
  50305. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  50306. };
  50307. /**
  50308. * Returns a height (y) value in the Worl system :
  50309. * the ground altitude at the coordinates (x, z) expressed in the World system.
  50310. * Returns the ground y position if (x, z) are outside the ground surface.
  50311. */
  50312. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  50313. var world = this.getWorldMatrix();
  50314. var invMat = BABYLON.Tmp.Matrix[5];
  50315. world.invertToRef(invMat);
  50316. var tmpVect = BABYLON.Tmp.Vector3[8];
  50317. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  50318. x = tmpVect.x;
  50319. z = tmpVect.z;
  50320. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50321. return this.position.y;
  50322. }
  50323. if (!this._heightQuads || this._heightQuads.length == 0) {
  50324. this._initHeightQuads();
  50325. this._computeHeightQuads();
  50326. }
  50327. var facet = this._getFacetAt(x, z);
  50328. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  50329. // return y in the World system
  50330. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  50331. return tmpVect.y;
  50332. };
  50333. /**
  50334. * Returns a normalized vector (Vector3) orthogonal to the ground
  50335. * at the ground coordinates (x, z) expressed in the World system.
  50336. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  50337. */
  50338. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  50339. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  50340. this.getNormalAtCoordinatesToRef(x, z, normal);
  50341. return normal;
  50342. };
  50343. /**
  50344. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  50345. * at the ground coordinates (x, z) expressed in the World system.
  50346. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  50347. * Returns the GroundMesh.
  50348. */
  50349. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  50350. var world = this.getWorldMatrix();
  50351. var tmpMat = BABYLON.Tmp.Matrix[5];
  50352. world.invertToRef(tmpMat);
  50353. var tmpVect = BABYLON.Tmp.Vector3[8];
  50354. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  50355. x = tmpVect.x;
  50356. z = tmpVect.z;
  50357. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50358. return this;
  50359. }
  50360. if (!this._heightQuads || this._heightQuads.length == 0) {
  50361. this._initHeightQuads();
  50362. this._computeHeightQuads();
  50363. }
  50364. var facet = this._getFacetAt(x, z);
  50365. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  50366. return this;
  50367. };
  50368. /**
  50369. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  50370. * if the ground has been updated.
  50371. * This can be used in the render loop.
  50372. * Returns the GroundMesh.
  50373. */
  50374. GroundMesh.prototype.updateCoordinateHeights = function () {
  50375. if (!this._heightQuads || this._heightQuads.length == 0) {
  50376. this._initHeightQuads();
  50377. }
  50378. this._computeHeightQuads();
  50379. return this;
  50380. };
  50381. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  50382. GroundMesh.prototype._getFacetAt = function (x, z) {
  50383. // retrieve col and row from x, z coordinates in the ground local system
  50384. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  50385. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  50386. var quad = this._heightQuads[row * this._subdivisionsX + col];
  50387. var facet;
  50388. if (z < quad.slope.x * x + quad.slope.y) {
  50389. facet = quad.facet1;
  50390. }
  50391. else {
  50392. facet = quad.facet2;
  50393. }
  50394. return facet;
  50395. };
  50396. // Creates and populates the heightMap array with "facet" elements :
  50397. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  50398. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50399. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50400. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50401. // Returns the GroundMesh.
  50402. GroundMesh.prototype._initHeightQuads = function () {
  50403. var subdivisionsX = this._subdivisionsX;
  50404. var subdivisionsY = this._subdivisionsY;
  50405. this._heightQuads = new Array();
  50406. for (var row = 0; row < subdivisionsY; row++) {
  50407. for (var col = 0; col < subdivisionsX; col++) {
  50408. 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) };
  50409. this._heightQuads[row * subdivisionsX + col] = quad;
  50410. }
  50411. }
  50412. return this;
  50413. };
  50414. // Compute each quad element values and update the the heightMap array :
  50415. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50416. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50417. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50418. // Returns the GroundMesh.
  50419. GroundMesh.prototype._computeHeightQuads = function () {
  50420. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50421. if (!positions) {
  50422. return this;
  50423. }
  50424. var v1 = BABYLON.Tmp.Vector3[3];
  50425. var v2 = BABYLON.Tmp.Vector3[2];
  50426. var v3 = BABYLON.Tmp.Vector3[1];
  50427. var v4 = BABYLON.Tmp.Vector3[0];
  50428. var v1v2 = BABYLON.Tmp.Vector3[4];
  50429. var v1v3 = BABYLON.Tmp.Vector3[5];
  50430. var v1v4 = BABYLON.Tmp.Vector3[6];
  50431. var norm1 = BABYLON.Tmp.Vector3[7];
  50432. var norm2 = BABYLON.Tmp.Vector3[8];
  50433. var i = 0;
  50434. var j = 0;
  50435. var k = 0;
  50436. var cd = 0; // 2D slope coefficient : z = cd * x + h
  50437. var h = 0;
  50438. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  50439. var d2 = 0;
  50440. var subdivisionsX = this._subdivisionsX;
  50441. var subdivisionsY = this._subdivisionsY;
  50442. for (var row = 0; row < subdivisionsY; row++) {
  50443. for (var col = 0; col < subdivisionsX; col++) {
  50444. i = col * 3;
  50445. j = row * (subdivisionsX + 1) * 3;
  50446. k = (row + 1) * (subdivisionsX + 1) * 3;
  50447. v1.x = positions[j + i];
  50448. v1.y = positions[j + i + 1];
  50449. v1.z = positions[j + i + 2];
  50450. v2.x = positions[j + i + 3];
  50451. v2.y = positions[j + i + 4];
  50452. v2.z = positions[j + i + 5];
  50453. v3.x = positions[k + i];
  50454. v3.y = positions[k + i + 1];
  50455. v3.z = positions[k + i + 2];
  50456. v4.x = positions[k + i + 3];
  50457. v4.y = positions[k + i + 4];
  50458. v4.z = positions[k + i + 5];
  50459. // 2D slope V1V4
  50460. cd = (v4.z - v1.z) / (v4.x - v1.x);
  50461. h = v1.z - cd * v1.x; // v1 belongs to the slope
  50462. // facet equations :
  50463. // we compute each facet normal vector
  50464. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  50465. // we compute the value d by applying the equation to v1 which belongs to the plane
  50466. // then we store the facet equation in a Vector4
  50467. v2.subtractToRef(v1, v1v2);
  50468. v3.subtractToRef(v1, v1v3);
  50469. v4.subtractToRef(v1, v1v4);
  50470. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  50471. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  50472. norm1.normalize();
  50473. norm2.normalize();
  50474. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  50475. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  50476. var quad = this._heightQuads[row * subdivisionsX + col];
  50477. quad.slope.copyFromFloats(cd, h);
  50478. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  50479. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  50480. }
  50481. }
  50482. return this;
  50483. };
  50484. GroundMesh.prototype.serialize = function (serializationObject) {
  50485. _super.prototype.serialize.call(this, serializationObject);
  50486. serializationObject.subdivisionsX = this._subdivisionsX;
  50487. serializationObject.subdivisionsY = this._subdivisionsY;
  50488. serializationObject.minX = this._minX;
  50489. serializationObject.maxX = this._maxX;
  50490. serializationObject.minZ = this._minZ;
  50491. serializationObject.maxZ = this._maxZ;
  50492. serializationObject.width = this._width;
  50493. serializationObject.height = this._height;
  50494. };
  50495. GroundMesh.Parse = function (parsedMesh, scene) {
  50496. var result = new GroundMesh(parsedMesh.name, scene);
  50497. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  50498. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  50499. result._minX = parsedMesh.minX;
  50500. result._maxX = parsedMesh.maxX;
  50501. result._minZ = parsedMesh.minZ;
  50502. result._maxZ = parsedMesh.maxZ;
  50503. result._width = parsedMesh.width;
  50504. result._height = parsedMesh.height;
  50505. return result;
  50506. };
  50507. return GroundMesh;
  50508. }(BABYLON.Mesh));
  50509. BABYLON.GroundMesh = GroundMesh;
  50510. })(BABYLON || (BABYLON = {}));
  50511. //# sourceMappingURL=babylon.groundMesh.js.map
  50512. var BABYLON;
  50513. (function (BABYLON) {
  50514. /**
  50515. * Creates an instance based on a source mesh.
  50516. */
  50517. var InstancedMesh = /** @class */ (function (_super) {
  50518. __extends(InstancedMesh, _super);
  50519. function InstancedMesh(name, source) {
  50520. var _this = _super.call(this, name, source.getScene()) || this;
  50521. source.instances.push(_this);
  50522. _this._sourceMesh = source;
  50523. _this.position.copyFrom(source.position);
  50524. _this.rotation.copyFrom(source.rotation);
  50525. _this.scaling.copyFrom(source.scaling);
  50526. if (source.rotationQuaternion) {
  50527. _this.rotationQuaternion = source.rotationQuaternion.clone();
  50528. }
  50529. _this.infiniteDistance = source.infiniteDistance;
  50530. _this.setPivotMatrix(source.getPivotMatrix());
  50531. _this.refreshBoundingInfo();
  50532. _this._syncSubMeshes();
  50533. return _this;
  50534. }
  50535. /**
  50536. * Returns the string "InstancedMesh".
  50537. */
  50538. InstancedMesh.prototype.getClassName = function () {
  50539. return "InstancedMesh";
  50540. };
  50541. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  50542. // Methods
  50543. get: function () {
  50544. return this._sourceMesh.receiveShadows;
  50545. },
  50546. enumerable: true,
  50547. configurable: true
  50548. });
  50549. Object.defineProperty(InstancedMesh.prototype, "material", {
  50550. get: function () {
  50551. return this._sourceMesh.material;
  50552. },
  50553. enumerable: true,
  50554. configurable: true
  50555. });
  50556. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  50557. get: function () {
  50558. return this._sourceMesh.visibility;
  50559. },
  50560. enumerable: true,
  50561. configurable: true
  50562. });
  50563. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  50564. get: function () {
  50565. return this._sourceMesh.skeleton;
  50566. },
  50567. enumerable: true,
  50568. configurable: true
  50569. });
  50570. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  50571. get: function () {
  50572. return this._sourceMesh.renderingGroupId;
  50573. },
  50574. enumerable: true,
  50575. configurable: true
  50576. });
  50577. /**
  50578. * Returns the total number of vertices (integer).
  50579. */
  50580. InstancedMesh.prototype.getTotalVertices = function () {
  50581. return this._sourceMesh.getTotalVertices();
  50582. };
  50583. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  50584. get: function () {
  50585. return this._sourceMesh;
  50586. },
  50587. enumerable: true,
  50588. configurable: true
  50589. });
  50590. /**
  50591. * Is this node ready to be used/rendered
  50592. * @return {boolean} is it ready
  50593. */
  50594. InstancedMesh.prototype.isReady = function () {
  50595. return this._sourceMesh.isReady(true);
  50596. };
  50597. /**
  50598. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  50599. */
  50600. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  50601. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  50602. };
  50603. /**
  50604. * Sets the vertex data of the mesh geometry for the requested `kind`.
  50605. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  50606. * The `data` are either a numeric array either a Float32Array.
  50607. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  50608. * 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).
  50609. * Note that a new underlying VertexBuffer object is created each call.
  50610. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  50611. *
  50612. * Possible `kind` values :
  50613. * - BABYLON.VertexBuffer.PositionKind
  50614. * - BABYLON.VertexBuffer.UVKind
  50615. * - BABYLON.VertexBuffer.UV2Kind
  50616. * - BABYLON.VertexBuffer.UV3Kind
  50617. * - BABYLON.VertexBuffer.UV4Kind
  50618. * - BABYLON.VertexBuffer.UV5Kind
  50619. * - BABYLON.VertexBuffer.UV6Kind
  50620. * - BABYLON.VertexBuffer.ColorKind
  50621. * - BABYLON.VertexBuffer.MatricesIndicesKind
  50622. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  50623. * - BABYLON.VertexBuffer.MatricesWeightsKind
  50624. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  50625. *
  50626. * Returns the Mesh.
  50627. */
  50628. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  50629. if (this.sourceMesh) {
  50630. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  50631. }
  50632. return this.sourceMesh;
  50633. };
  50634. /**
  50635. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  50636. * If the mesh has no geometry, it is simply returned as it is.
  50637. * The `data` are either a numeric array either a Float32Array.
  50638. * No new underlying VertexBuffer object is created.
  50639. * 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.
  50640. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  50641. *
  50642. * Possible `kind` values :
  50643. * - BABYLON.VertexBuffer.PositionKind
  50644. * - BABYLON.VertexBuffer.UVKind
  50645. * - BABYLON.VertexBuffer.UV2Kind
  50646. * - BABYLON.VertexBuffer.UV3Kind
  50647. * - BABYLON.VertexBuffer.UV4Kind
  50648. * - BABYLON.VertexBuffer.UV5Kind
  50649. * - BABYLON.VertexBuffer.UV6Kind
  50650. * - BABYLON.VertexBuffer.ColorKind
  50651. * - BABYLON.VertexBuffer.MatricesIndicesKind
  50652. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  50653. * - BABYLON.VertexBuffer.MatricesWeightsKind
  50654. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  50655. *
  50656. * Returns the Mesh.
  50657. */
  50658. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  50659. if (this.sourceMesh) {
  50660. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  50661. }
  50662. return this.sourceMesh;
  50663. };
  50664. /**
  50665. * Sets the mesh indices.
  50666. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  50667. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  50668. * This method creates a new index buffer each call.
  50669. * Returns the Mesh.
  50670. */
  50671. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  50672. if (totalVertices === void 0) { totalVertices = null; }
  50673. if (this.sourceMesh) {
  50674. this.sourceMesh.setIndices(indices, totalVertices);
  50675. }
  50676. return this.sourceMesh;
  50677. };
  50678. /**
  50679. * Boolean : True if the mesh owns the requested kind of data.
  50680. */
  50681. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  50682. return this._sourceMesh.isVerticesDataPresent(kind);
  50683. };
  50684. /**
  50685. * Returns an array of indices (IndicesArray).
  50686. */
  50687. InstancedMesh.prototype.getIndices = function () {
  50688. return this._sourceMesh.getIndices();
  50689. };
  50690. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  50691. get: function () {
  50692. return this._sourceMesh._positions;
  50693. },
  50694. enumerable: true,
  50695. configurable: true
  50696. });
  50697. /**
  50698. * Sets a new updated BoundingInfo to the mesh.
  50699. * Returns the mesh.
  50700. */
  50701. InstancedMesh.prototype.refreshBoundingInfo = function () {
  50702. var meshBB = this._sourceMesh.getBoundingInfo();
  50703. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  50704. this._updateBoundingInfo();
  50705. return this;
  50706. };
  50707. InstancedMesh.prototype._preActivate = function () {
  50708. if (this._currentLOD) {
  50709. this._currentLOD._preActivate();
  50710. }
  50711. return this;
  50712. };
  50713. InstancedMesh.prototype._activate = function (renderId) {
  50714. if (this._currentLOD) {
  50715. this._currentLOD._registerInstanceForRenderId(this, renderId);
  50716. }
  50717. return this;
  50718. };
  50719. /**
  50720. * Returns the current associated LOD AbstractMesh.
  50721. */
  50722. InstancedMesh.prototype.getLOD = function (camera) {
  50723. if (!camera) {
  50724. return this;
  50725. }
  50726. var boundingInfo = this.getBoundingInfo();
  50727. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  50728. if (this._currentLOD === this.sourceMesh) {
  50729. return this;
  50730. }
  50731. return this._currentLOD;
  50732. };
  50733. InstancedMesh.prototype._syncSubMeshes = function () {
  50734. this.releaseSubMeshes();
  50735. if (this._sourceMesh.subMeshes) {
  50736. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  50737. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  50738. }
  50739. }
  50740. return this;
  50741. };
  50742. InstancedMesh.prototype._generatePointsArray = function () {
  50743. return this._sourceMesh._generatePointsArray();
  50744. };
  50745. /**
  50746. * Creates a new InstancedMesh from the current mesh.
  50747. * - name (string) : the cloned mesh name
  50748. * - newParent (optional Node) : the optional Node to parent the clone to.
  50749. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  50750. *
  50751. * Returns the clone.
  50752. */
  50753. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  50754. var result = this._sourceMesh.createInstance(name);
  50755. // Deep copy
  50756. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  50757. // Bounding info
  50758. this.refreshBoundingInfo();
  50759. // Parent
  50760. if (newParent) {
  50761. result.parent = newParent;
  50762. }
  50763. if (!doNotCloneChildren) {
  50764. // Children
  50765. for (var index = 0; index < this.getScene().meshes.length; index++) {
  50766. var mesh = this.getScene().meshes[index];
  50767. if (mesh.parent === this) {
  50768. mesh.clone(mesh.name, result);
  50769. }
  50770. }
  50771. }
  50772. result.computeWorldMatrix(true);
  50773. return result;
  50774. };
  50775. /**
  50776. * Disposes the InstancedMesh.
  50777. * Returns nothing.
  50778. */
  50779. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  50780. // Remove from mesh
  50781. var index = this._sourceMesh.instances.indexOf(this);
  50782. this._sourceMesh.instances.splice(index, 1);
  50783. _super.prototype.dispose.call(this, doNotRecurse);
  50784. };
  50785. return InstancedMesh;
  50786. }(BABYLON.AbstractMesh));
  50787. BABYLON.InstancedMesh = InstancedMesh;
  50788. })(BABYLON || (BABYLON = {}));
  50789. //# sourceMappingURL=babylon.instancedMesh.js.map
  50790. var BABYLON;
  50791. (function (BABYLON) {
  50792. var LinesMesh = /** @class */ (function (_super) {
  50793. __extends(LinesMesh, _super);
  50794. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  50795. if (scene === void 0) { scene = null; }
  50796. if (parent === void 0) { parent = null; }
  50797. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  50798. _this.useVertexColor = useVertexColor;
  50799. _this.useVertexAlpha = useVertexAlpha;
  50800. _this.color = new BABYLON.Color3(1, 1, 1);
  50801. _this.alpha = 1;
  50802. if (source) {
  50803. _this.color = source.color.clone();
  50804. _this.alpha = source.alpha;
  50805. _this.useVertexColor = source.useVertexColor;
  50806. _this.useVertexAlpha = source.useVertexAlpha;
  50807. }
  50808. _this._intersectionThreshold = 0.1;
  50809. var defines = [];
  50810. var options = {
  50811. attributes: [BABYLON.VertexBuffer.PositionKind],
  50812. uniforms: ["world", "viewProjection"],
  50813. needAlphaBlending: true,
  50814. defines: defines
  50815. };
  50816. if (useVertexAlpha === false) {
  50817. options.needAlphaBlending = false;
  50818. }
  50819. if (!useVertexColor) {
  50820. options.uniforms.push("color");
  50821. }
  50822. else {
  50823. options.defines.push("#define VERTEXCOLOR");
  50824. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  50825. }
  50826. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  50827. return _this;
  50828. }
  50829. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  50830. /**
  50831. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  50832. * This margin is expressed in world space coordinates, so its value may vary.
  50833. * Default value is 0.1
  50834. * @returns the intersection Threshold value.
  50835. */
  50836. get: function () {
  50837. return this._intersectionThreshold;
  50838. },
  50839. /**
  50840. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  50841. * This margin is expressed in world space coordinates, so its value may vary.
  50842. * @param value the new threshold to apply
  50843. */
  50844. set: function (value) {
  50845. if (this._intersectionThreshold === value) {
  50846. return;
  50847. }
  50848. this._intersectionThreshold = value;
  50849. if (this.geometry) {
  50850. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  50851. }
  50852. },
  50853. enumerable: true,
  50854. configurable: true
  50855. });
  50856. /**
  50857. * Returns the string "LineMesh"
  50858. */
  50859. LinesMesh.prototype.getClassName = function () {
  50860. return "LinesMesh";
  50861. };
  50862. Object.defineProperty(LinesMesh.prototype, "material", {
  50863. get: function () {
  50864. return this._colorShader;
  50865. },
  50866. set: function (value) {
  50867. // Do nothing
  50868. },
  50869. enumerable: true,
  50870. configurable: true
  50871. });
  50872. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  50873. get: function () {
  50874. return false;
  50875. },
  50876. enumerable: true,
  50877. configurable: true
  50878. });
  50879. LinesMesh.prototype.createInstance = function (name) {
  50880. throw new Error("LinesMeshes do not support createInstance.");
  50881. };
  50882. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  50883. if (!this._geometry) {
  50884. return this;
  50885. }
  50886. // VBOs
  50887. this._geometry._bind(this._colorShader.getEffect());
  50888. // Color
  50889. if (!this.useVertexColor) {
  50890. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  50891. }
  50892. return this;
  50893. };
  50894. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  50895. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  50896. return this;
  50897. }
  50898. var engine = this.getScene().getEngine();
  50899. // Draw order
  50900. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  50901. return this;
  50902. };
  50903. LinesMesh.prototype.dispose = function (doNotRecurse) {
  50904. this._colorShader.dispose();
  50905. _super.prototype.dispose.call(this, doNotRecurse);
  50906. };
  50907. /**
  50908. * Returns a new LineMesh object cloned from the current one.
  50909. */
  50910. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  50911. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  50912. };
  50913. return LinesMesh;
  50914. }(BABYLON.Mesh));
  50915. BABYLON.LinesMesh = LinesMesh;
  50916. })(BABYLON || (BABYLON = {}));
  50917. //# sourceMappingURL=babylon.linesMesh.js.map
  50918. var BABYLON;
  50919. (function (BABYLON) {
  50920. var MeshBuilder = /** @class */ (function () {
  50921. function MeshBuilder() {
  50922. }
  50923. MeshBuilder.updateSideOrientation = function (orientation) {
  50924. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  50925. return BABYLON.Mesh.DOUBLESIDE;
  50926. }
  50927. if (orientation === undefined || orientation === null) {
  50928. return BABYLON.Mesh.FRONTSIDE;
  50929. }
  50930. return orientation;
  50931. };
  50932. /**
  50933. * Creates a box mesh.
  50934. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  50935. * The parameter `size` sets the size (float) of each box side (default 1).
  50936. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  50937. * 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).
  50938. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50939. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50940. * 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).
  50941. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50943. */
  50944. MeshBuilder.CreateBox = function (name, options, scene) {
  50945. if (scene === void 0) { scene = null; }
  50946. var box = new BABYLON.Mesh(name, scene);
  50947. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50948. box._originalBuilderSideOrientation = options.sideOrientation;
  50949. var vertexData = BABYLON.VertexData.CreateBox(options);
  50950. vertexData.applyToMesh(box, options.updatable);
  50951. return box;
  50952. };
  50953. /**
  50954. * Creates a sphere mesh.
  50955. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  50956. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  50957. * 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`).
  50958. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  50959. * 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
  50960. * 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).
  50961. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50962. * 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).
  50963. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50965. */
  50966. MeshBuilder.CreateSphere = function (name, options, scene) {
  50967. var sphere = new BABYLON.Mesh(name, scene);
  50968. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50969. sphere._originalBuilderSideOrientation = options.sideOrientation;
  50970. var vertexData = BABYLON.VertexData.CreateSphere(options);
  50971. vertexData.applyToMesh(sphere, options.updatable);
  50972. return sphere;
  50973. };
  50974. /**
  50975. * Creates a plane polygonal mesh. By default, this is a disc.
  50976. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  50977. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  50978. * 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.
  50979. * 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
  50980. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50981. * 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).
  50982. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50984. */
  50985. MeshBuilder.CreateDisc = function (name, options, scene) {
  50986. if (scene === void 0) { scene = null; }
  50987. var disc = new BABYLON.Mesh(name, scene);
  50988. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50989. disc._originalBuilderSideOrientation = options.sideOrientation;
  50990. var vertexData = BABYLON.VertexData.CreateDisc(options);
  50991. vertexData.applyToMesh(disc, options.updatable);
  50992. return disc;
  50993. };
  50994. /**
  50995. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  50996. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  50997. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  50998. * 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`).
  50999. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  51000. * 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.
  51001. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51002. * 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).
  51003. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51004. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51005. */
  51006. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  51007. var sphere = new BABYLON.Mesh(name, scene);
  51008. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51009. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51010. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  51011. vertexData.applyToMesh(sphere, options.updatable);
  51012. return sphere;
  51013. };
  51014. ;
  51015. /**
  51016. * Creates a ribbon mesh.
  51017. * 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.
  51018. *
  51019. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  51020. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  51021. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  51022. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  51023. * 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.
  51024. * 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.
  51025. * 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
  51026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51027. * 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).
  51028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51029. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51030. * 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.
  51031. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  51032. * 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
  51033. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  51034. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  51035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51036. */
  51037. MeshBuilder.CreateRibbon = function (name, options, scene) {
  51038. if (scene === void 0) { scene = null; }
  51039. var pathArray = options.pathArray;
  51040. var closeArray = options.closeArray;
  51041. var closePath = options.closePath;
  51042. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51043. var instance = options.instance;
  51044. var updatable = options.updatable;
  51045. if (instance) {
  51046. // positionFunction : ribbon case
  51047. // only pathArray and sideOrientation parameters are taken into account for positions update
  51048. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  51049. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  51050. var positionFunction = function (positions) {
  51051. var minlg = pathArray[0].length;
  51052. var i = 0;
  51053. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  51054. for (var si = 1; si <= ns; si++) {
  51055. for (var p = 0; p < pathArray.length; p++) {
  51056. var path = pathArray[p];
  51057. var l = path.length;
  51058. minlg = (minlg < l) ? minlg : l;
  51059. var j = 0;
  51060. while (j < minlg) {
  51061. positions[i] = path[j].x;
  51062. positions[i + 1] = path[j].y;
  51063. positions[i + 2] = path[j].z;
  51064. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  51065. BABYLON.Tmp.Vector3[0].x = path[j].x;
  51066. }
  51067. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  51068. BABYLON.Tmp.Vector3[1].x = path[j].x;
  51069. }
  51070. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  51071. BABYLON.Tmp.Vector3[0].y = path[j].y;
  51072. }
  51073. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  51074. BABYLON.Tmp.Vector3[1].y = path[j].y;
  51075. }
  51076. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  51077. BABYLON.Tmp.Vector3[0].z = path[j].z;
  51078. }
  51079. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  51080. BABYLON.Tmp.Vector3[1].z = path[j].z;
  51081. }
  51082. j++;
  51083. i += 3;
  51084. }
  51085. if (instance._closePath) {
  51086. positions[i] = path[0].x;
  51087. positions[i + 1] = path[0].y;
  51088. positions[i + 2] = path[0].z;
  51089. i += 3;
  51090. }
  51091. }
  51092. }
  51093. };
  51094. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51095. positionFunction(positions);
  51096. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  51097. instance._boundingInfo.update(instance._worldMatrix);
  51098. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51099. if (options.colors) {
  51100. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51101. for (var c = 0; c < options.colors.length; c++) {
  51102. colors[c * 4] = options.colors[c].r;
  51103. colors[c * 4 + 1] = options.colors[c].g;
  51104. colors[c * 4 + 2] = options.colors[c].b;
  51105. colors[c * 4 + 3] = options.colors[c].a;
  51106. }
  51107. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  51108. }
  51109. if (options.uvs) {
  51110. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51111. for (var i = 0; i < options.uvs.length; i++) {
  51112. uvs[i * 2] = options.uvs[i].x;
  51113. uvs[i * 2 + 1] = options.uvs[i].y;
  51114. }
  51115. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  51116. }
  51117. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  51118. var indices = instance.getIndices();
  51119. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51120. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  51121. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  51122. if (instance._closePath) {
  51123. var indexFirst = 0;
  51124. var indexLast = 0;
  51125. for (var p = 0; p < pathArray.length; p++) {
  51126. indexFirst = instance._idx[p] * 3;
  51127. if (p + 1 < pathArray.length) {
  51128. indexLast = (instance._idx[p + 1] - 1) * 3;
  51129. }
  51130. else {
  51131. indexLast = normals.length - 3;
  51132. }
  51133. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  51134. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  51135. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  51136. normals[indexLast] = normals[indexFirst];
  51137. normals[indexLast + 1] = normals[indexFirst + 1];
  51138. normals[indexLast + 2] = normals[indexFirst + 2];
  51139. }
  51140. }
  51141. if (!(instance.areNormalsFrozen)) {
  51142. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  51143. }
  51144. }
  51145. return instance;
  51146. }
  51147. else {
  51148. var ribbon = new BABYLON.Mesh(name, scene);
  51149. ribbon._originalBuilderSideOrientation = sideOrientation;
  51150. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  51151. if (closePath) {
  51152. ribbon._idx = vertexData._idx;
  51153. }
  51154. ribbon._closePath = closePath;
  51155. ribbon._closeArray = closeArray;
  51156. vertexData.applyToMesh(ribbon, updatable);
  51157. return ribbon;
  51158. }
  51159. };
  51160. /**
  51161. * Creates a cylinder or a cone mesh.
  51162. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  51163. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  51164. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  51165. * 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.
  51166. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  51167. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  51168. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  51169. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  51170. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  51171. * 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).
  51172. * 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
  51173. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  51174. * 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
  51175. * 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.
  51176. * If `enclose` is false, a ring surface is one element.
  51177. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  51178. * 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
  51179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51180. * 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).
  51181. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51183. */
  51184. MeshBuilder.CreateCylinder = function (name, options, scene) {
  51185. var cylinder = new BABYLON.Mesh(name, scene);
  51186. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51187. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  51188. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  51189. vertexData.applyToMesh(cylinder, options.updatable);
  51190. return cylinder;
  51191. };
  51192. /**
  51193. * Creates a torus mesh.
  51194. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  51195. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  51196. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  51197. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  51198. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51199. * 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).
  51200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51202. */
  51203. MeshBuilder.CreateTorus = function (name, options, scene) {
  51204. var torus = new BABYLON.Mesh(name, scene);
  51205. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51206. torus._originalBuilderSideOrientation = options.sideOrientation;
  51207. var vertexData = BABYLON.VertexData.CreateTorus(options);
  51208. vertexData.applyToMesh(torus, options.updatable);
  51209. return torus;
  51210. };
  51211. /**
  51212. * Creates a torus knot mesh.
  51213. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  51214. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  51215. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  51216. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  51217. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  51218. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51219. * 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).
  51220. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51221. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51222. */
  51223. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  51224. var torusKnot = new BABYLON.Mesh(name, scene);
  51225. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51226. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  51227. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  51228. vertexData.applyToMesh(torusKnot, options.updatable);
  51229. return torusKnot;
  51230. };
  51231. /**
  51232. * Creates a line system mesh.
  51233. * A line system is a pool of many lines gathered in a single mesh.
  51234. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  51235. * 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.
  51236. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  51237. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  51238. * 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
  51239. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  51240. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  51241. * 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
  51242. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  51243. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51244. */
  51245. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  51246. var instance = options.instance;
  51247. var lines = options.lines;
  51248. var colors = options.colors;
  51249. if (instance) {
  51250. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51251. var vertexColor;
  51252. var lineColors;
  51253. if (colors) {
  51254. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51255. }
  51256. var i = 0;
  51257. var c = 0;
  51258. for (var l = 0; l < lines.length; l++) {
  51259. var points = lines[l];
  51260. for (var p = 0; p < points.length; p++) {
  51261. positions[i] = points[p].x;
  51262. positions[i + 1] = points[p].y;
  51263. positions[i + 2] = points[p].z;
  51264. if (colors && vertexColor) {
  51265. lineColors = colors[l];
  51266. vertexColor[c] = lineColors[p].r;
  51267. vertexColor[c + 1] = lineColors[p].g;
  51268. vertexColor[c + 2] = lineColors[p].b;
  51269. vertexColor[c + 3] = lineColors[p].a;
  51270. c += 4;
  51271. }
  51272. i += 3;
  51273. }
  51274. }
  51275. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51276. if (colors && vertexColor) {
  51277. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  51278. }
  51279. return instance;
  51280. }
  51281. // line system creation
  51282. var useVertexColor = (colors) ? true : false;
  51283. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  51284. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  51285. vertexData.applyToMesh(lineSystem, options.updatable);
  51286. return lineSystem;
  51287. };
  51288. /**
  51289. * Creates a line mesh.
  51290. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  51291. * 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.
  51292. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51293. * The parameter `points` is an array successive Vector3.
  51294. * 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
  51295. * The optional parameter `colors` is an array of successive Color4, one per line point.
  51296. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  51297. * When updating an instance, remember that only point positions can change, not the number of points.
  51298. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51299. */
  51300. MeshBuilder.CreateLines = function (name, options, scene) {
  51301. if (scene === void 0) { scene = null; }
  51302. var colors = (options.colors) ? [options.colors] : null;
  51303. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  51304. return lines;
  51305. };
  51306. /**
  51307. * Creates a dashed line mesh.
  51308. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  51309. * 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.
  51310. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51311. * The parameter `points` is an array successive Vector3.
  51312. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  51313. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  51314. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  51315. * 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
  51316. * When updating an instance, remember that only point positions can change, not the number of points.
  51317. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51318. */
  51319. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  51320. if (scene === void 0) { scene = null; }
  51321. var points = options.points;
  51322. var instance = options.instance;
  51323. var gapSize = options.gapSize || 1;
  51324. var dashSize = options.dashSize || 3;
  51325. if (instance) {
  51326. var positionFunction = function (positions) {
  51327. var curvect = BABYLON.Vector3.Zero();
  51328. var nbSeg = positions.length / 6;
  51329. var lg = 0;
  51330. var nb = 0;
  51331. var shft = 0;
  51332. var dashshft = 0;
  51333. var curshft = 0;
  51334. var p = 0;
  51335. var i = 0;
  51336. var j = 0;
  51337. for (i = 0; i < points.length - 1; i++) {
  51338. points[i + 1].subtractToRef(points[i], curvect);
  51339. lg += curvect.length();
  51340. }
  51341. shft = lg / nbSeg;
  51342. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  51343. for (i = 0; i < points.length - 1; i++) {
  51344. points[i + 1].subtractToRef(points[i], curvect);
  51345. nb = Math.floor(curvect.length() / shft);
  51346. curvect.normalize();
  51347. j = 0;
  51348. while (j < nb && p < positions.length) {
  51349. curshft = shft * j;
  51350. positions[p] = points[i].x + curshft * curvect.x;
  51351. positions[p + 1] = points[i].y + curshft * curvect.y;
  51352. positions[p + 2] = points[i].z + curshft * curvect.z;
  51353. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  51354. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  51355. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  51356. p += 6;
  51357. j++;
  51358. }
  51359. }
  51360. while (p < positions.length) {
  51361. positions[p] = points[i].x;
  51362. positions[p + 1] = points[i].y;
  51363. positions[p + 2] = points[i].z;
  51364. p += 3;
  51365. }
  51366. };
  51367. instance.updateMeshPositions(positionFunction, false);
  51368. return instance;
  51369. }
  51370. // dashed lines creation
  51371. var dashedLines = new BABYLON.LinesMesh(name, scene);
  51372. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  51373. vertexData.applyToMesh(dashedLines, options.updatable);
  51374. dashedLines.dashSize = dashSize;
  51375. dashedLines.gapSize = gapSize;
  51376. return dashedLines;
  51377. };
  51378. /**
  51379. * Creates an extruded shape mesh.
  51380. * 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.
  51381. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  51382. *
  51383. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51384. * 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
  51385. * extruded along the Z axis.
  51386. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51387. * 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.
  51388. * The parameter `scale` (float, default 1) is the value to scale the shape.
  51389. * 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
  51390. * 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
  51391. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51392. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51393. * 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).
  51394. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51395. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51397. */
  51398. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  51399. if (scene === void 0) { scene = null; }
  51400. var path = options.path;
  51401. var shape = options.shape;
  51402. var scale = options.scale || 1;
  51403. var rotation = options.rotation || 0;
  51404. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51405. var updatable = options.updatable;
  51406. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51407. var instance = options.instance || null;
  51408. var invertUV = options.invertUV || false;
  51409. 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);
  51410. };
  51411. /**
  51412. * Creates an custom extruded shape mesh.
  51413. * 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.
  51414. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  51415. *
  51416. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51417. * 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
  51418. * extruded along the Z axis.
  51419. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51420. * 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
  51421. * and the distance of this point from the begining of the path :
  51422. * ```javascript
  51423. * var rotationFunction = function(i, distance) {
  51424. * // do things
  51425. * return rotationValue; }
  51426. * ```
  51427. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  51428. * 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
  51429. * and the distance of this point from the begining of the path :
  51430. * ```javascript
  51431. * var scaleFunction = function(i, distance) {
  51432. * // do things
  51433. * return scaleValue;}
  51434. * ```
  51435. * It must returns a float value that will be the scale value applied to the shape on each path point.
  51436. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  51437. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  51438. * 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
  51439. * 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
  51440. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51441. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51442. * 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).
  51443. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51444. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51446. */
  51447. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  51448. var path = options.path;
  51449. var shape = options.shape;
  51450. var scaleFunction = options.scaleFunction || (function () { return 1; });
  51451. var rotationFunction = options.rotationFunction || (function () { return 0; });
  51452. var ribbonCloseArray = options.ribbonCloseArray || false;
  51453. var ribbonClosePath = options.ribbonClosePath || false;
  51454. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51455. var updatable = options.updatable;
  51456. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51457. var instance = options.instance;
  51458. var invertUV = options.invertUV || false;
  51459. 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);
  51460. };
  51461. /**
  51462. * Creates lathe mesh.
  51463. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  51464. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  51465. *
  51466. * 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
  51467. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  51468. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  51469. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  51470. * 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.
  51471. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  51472. * 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
  51473. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51474. * 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).
  51475. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51476. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51478. */
  51479. MeshBuilder.CreateLathe = function (name, options, scene) {
  51480. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  51481. var closed = (options.closed === undefined) ? true : options.closed;
  51482. var shape = options.shape;
  51483. var radius = options.radius || 1;
  51484. var tessellation = options.tessellation || 64;
  51485. var updatable = options.updatable;
  51486. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51487. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51488. var pi2 = Math.PI * 2;
  51489. var paths = new Array();
  51490. var invertUV = options.invertUV || false;
  51491. var i = 0;
  51492. var p = 0;
  51493. var step = pi2 / tessellation * arc;
  51494. var rotated;
  51495. var path = new Array();
  51496. ;
  51497. for (i = 0; i <= tessellation; i++) {
  51498. var path = [];
  51499. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  51500. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  51501. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  51502. }
  51503. for (p = 0; p < shape.length; p++) {
  51504. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  51505. path.push(rotated);
  51506. }
  51507. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  51508. 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));
  51509. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  51510. }
  51511. paths.push(path);
  51512. }
  51513. // lathe ribbon
  51514. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51515. return lathe;
  51516. };
  51517. /**
  51518. * Creates a plane mesh.
  51519. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51520. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  51521. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  51522. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  51523. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51524. * 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).
  51525. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51527. */
  51528. MeshBuilder.CreatePlane = function (name, options, scene) {
  51529. var plane = new BABYLON.Mesh(name, scene);
  51530. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51531. plane._originalBuilderSideOrientation = options.sideOrientation;
  51532. var vertexData = BABYLON.VertexData.CreatePlane(options);
  51533. vertexData.applyToMesh(plane, options.updatable);
  51534. if (options.sourcePlane) {
  51535. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  51536. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  51537. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  51538. plane.rotate(vectorProduct, product);
  51539. }
  51540. return plane;
  51541. };
  51542. /**
  51543. * Creates a ground mesh.
  51544. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51545. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  51546. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  51547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51548. */
  51549. MeshBuilder.CreateGround = function (name, options, scene) {
  51550. var ground = new BABYLON.GroundMesh(name, scene);
  51551. ground._setReady(false);
  51552. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  51553. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  51554. ground._width = options.width || 1;
  51555. ground._height = options.height || 1;
  51556. ground._maxX = ground._width / 2;
  51557. ground._maxZ = ground._height / 2;
  51558. ground._minX = -ground._maxX;
  51559. ground._minZ = -ground._maxZ;
  51560. var vertexData = BABYLON.VertexData.CreateGround(options);
  51561. vertexData.applyToMesh(ground, options.updatable);
  51562. ground._setReady(true);
  51563. return ground;
  51564. };
  51565. /**
  51566. * Creates a tiled ground mesh.
  51567. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  51568. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  51569. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  51570. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  51571. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  51572. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  51573. * numbers of subdivisions on the ground width and height of each tile.
  51574. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51575. */
  51576. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  51577. var tiledGround = new BABYLON.Mesh(name, scene);
  51578. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  51579. vertexData.applyToMesh(tiledGround, options.updatable);
  51580. return tiledGround;
  51581. };
  51582. /**
  51583. * Creates a ground mesh from a height map.
  51584. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  51585. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  51586. * The parameter `url` sets the URL of the height map image resource.
  51587. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  51588. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  51589. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  51590. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  51591. * 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.
  51592. * 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).
  51593. * This function is passed the newly built mesh :
  51594. * ```javascript
  51595. * function(mesh) { // do things
  51596. * return; }
  51597. * ```
  51598. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51599. */
  51600. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  51601. var width = options.width || 10.0;
  51602. var height = options.height || 10.0;
  51603. var subdivisions = options.subdivisions || 1 | 0;
  51604. var minHeight = options.minHeight || 0.0;
  51605. var maxHeight = options.maxHeight || 1.0;
  51606. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  51607. var updatable = options.updatable;
  51608. var onReady = options.onReady;
  51609. var ground = new BABYLON.GroundMesh(name, scene);
  51610. ground._subdivisionsX = subdivisions;
  51611. ground._subdivisionsY = subdivisions;
  51612. ground._width = width;
  51613. ground._height = height;
  51614. ground._maxX = ground._width / 2.0;
  51615. ground._maxZ = ground._height / 2.0;
  51616. ground._minX = -ground._maxX;
  51617. ground._minZ = -ground._maxZ;
  51618. ground._setReady(false);
  51619. var onload = function (img) {
  51620. // Getting height map data
  51621. var canvas = document.createElement("canvas");
  51622. var context = canvas.getContext("2d");
  51623. if (!context) {
  51624. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  51625. }
  51626. if (scene.isDisposed) {
  51627. return;
  51628. }
  51629. var bufferWidth = img.width;
  51630. var bufferHeight = img.height;
  51631. canvas.width = bufferWidth;
  51632. canvas.height = bufferHeight;
  51633. context.drawImage(img, 0, 0);
  51634. // Create VertexData from map data
  51635. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  51636. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  51637. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  51638. width: width, height: height,
  51639. subdivisions: subdivisions,
  51640. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  51641. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  51642. });
  51643. vertexData.applyToMesh(ground, updatable);
  51644. ground._setReady(true);
  51645. //execute ready callback, if set
  51646. if (onReady) {
  51647. onReady(ground);
  51648. }
  51649. };
  51650. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  51651. return ground;
  51652. };
  51653. /**
  51654. * Creates a polygon mesh.
  51655. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  51656. * 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.
  51657. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51658. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51659. * 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).
  51660. * Remember you can only change the shape positions, not their number when updating a polygon.
  51661. */
  51662. MeshBuilder.CreatePolygon = function (name, options, scene) {
  51663. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51664. var shape = options.shape;
  51665. var holes = options.holes || [];
  51666. var depth = options.depth || 0;
  51667. var contours = [];
  51668. var hole = [];
  51669. for (var i = 0; i < shape.length; i++) {
  51670. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  51671. }
  51672. var epsilon = 0.00000001;
  51673. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  51674. contours.pop();
  51675. }
  51676. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  51677. for (var hNb = 0; hNb < holes.length; hNb++) {
  51678. hole = [];
  51679. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  51680. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  51681. }
  51682. polygonTriangulation.addHole(hole);
  51683. }
  51684. var polygon = polygonTriangulation.build(options.updatable, depth);
  51685. polygon._originalBuilderSideOrientation = options.sideOrientation;
  51686. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  51687. vertexData.applyToMesh(polygon, options.updatable);
  51688. return polygon;
  51689. };
  51690. ;
  51691. /**
  51692. * Creates an extruded polygon mesh, with depth in the Y direction.
  51693. * 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).
  51694. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51695. */
  51696. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  51697. return MeshBuilder.CreatePolygon(name, options, scene);
  51698. };
  51699. ;
  51700. /**
  51701. * Creates a tube mesh.
  51702. * 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.
  51703. *
  51704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  51705. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  51706. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  51707. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  51708. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  51709. * 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.
  51710. * It must return a radius value (positive float) :
  51711. * ```javascript
  51712. * var radiusFunction = function(i, distance) {
  51713. * // do things
  51714. * return radius; }
  51715. * ```
  51716. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  51717. * 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
  51718. * 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
  51719. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51720. * 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).
  51721. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51722. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51724. */
  51725. MeshBuilder.CreateTube = function (name, options, scene) {
  51726. var path = options.path;
  51727. var instance = options.instance;
  51728. var radius = 1.0;
  51729. if (instance) {
  51730. radius = instance.radius;
  51731. }
  51732. if (options.radius !== undefined) {
  51733. radius = options.radius;
  51734. }
  51735. ;
  51736. var tessellation = options.tessellation || 64 | 0;
  51737. var radiusFunction = options.radiusFunction || null;
  51738. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51739. var invertUV = options.invertUV || false;
  51740. var updatable = options.updatable;
  51741. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51742. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  51743. // tube geometry
  51744. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  51745. var tangents = path3D.getTangents();
  51746. var normals = path3D.getNormals();
  51747. var distances = path3D.getDistances();
  51748. var pi2 = Math.PI * 2;
  51749. var step = pi2 / tessellation * arc;
  51750. var returnRadius = function () { return radius; };
  51751. var radiusFunctionFinal = radiusFunction || returnRadius;
  51752. var circlePath;
  51753. var rad;
  51754. var normal;
  51755. var rotated;
  51756. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  51757. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  51758. for (var i = 0; i < path.length; i++) {
  51759. rad = radiusFunctionFinal(i, distances[i]); // current radius
  51760. circlePath = Array(); // current circle array
  51761. normal = normals[i]; // current normal
  51762. for (var t = 0; t < tessellation; t++) {
  51763. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  51764. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  51765. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  51766. rotated.scaleInPlace(rad).addInPlace(path[i]);
  51767. circlePath[t] = rotated;
  51768. }
  51769. circlePaths[index] = circlePath;
  51770. index++;
  51771. }
  51772. // cap
  51773. var capPath = function (nbPoints, pathIndex) {
  51774. var pointCap = Array();
  51775. for (var i = 0; i < nbPoints; i++) {
  51776. pointCap.push(path[pathIndex]);
  51777. }
  51778. return pointCap;
  51779. };
  51780. switch (cap) {
  51781. case BABYLON.Mesh.NO_CAP:
  51782. break;
  51783. case BABYLON.Mesh.CAP_START:
  51784. circlePaths[0] = capPath(tessellation, 0);
  51785. circlePaths[1] = circlePaths[2].slice(0);
  51786. break;
  51787. case BABYLON.Mesh.CAP_END:
  51788. circlePaths[index] = circlePaths[index - 1].slice(0);
  51789. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  51790. break;
  51791. case BABYLON.Mesh.CAP_ALL:
  51792. circlePaths[0] = capPath(tessellation, 0);
  51793. circlePaths[1] = circlePaths[2].slice(0);
  51794. circlePaths[index] = circlePaths[index - 1].slice(0);
  51795. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  51796. break;
  51797. default:
  51798. break;
  51799. }
  51800. return circlePaths;
  51801. };
  51802. var path3D;
  51803. var pathArray;
  51804. if (instance) {
  51805. var arc = options.arc || instance.arc;
  51806. path3D = (instance.path3D).update(path);
  51807. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  51808. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  51809. instance.path3D = path3D;
  51810. instance.pathArray = pathArray;
  51811. instance.arc = arc;
  51812. instance.radius = radius;
  51813. return instance;
  51814. }
  51815. // tube creation
  51816. path3D = new BABYLON.Path3D(path);
  51817. var newPathArray = new Array();
  51818. cap = (cap < 0 || cap > 3) ? 0 : cap;
  51819. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  51820. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51821. tube.pathArray = pathArray;
  51822. tube.path3D = path3D;
  51823. tube.tessellation = tessellation;
  51824. tube.cap = cap;
  51825. tube.arc = options.arc;
  51826. tube.radius = radius;
  51827. return tube;
  51828. };
  51829. /**
  51830. * Creates a polyhedron mesh.
  51831. *
  51832. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  51833. * 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
  51834. * to choose the wanted type.
  51835. * The parameter `size` (positive float, default 1) sets the polygon size.
  51836. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  51837. * 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`.
  51838. * 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
  51839. * 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)`).
  51840. * 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
  51841. * 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.
  51842. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51843. * 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).
  51844. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51846. */
  51847. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  51848. var polyhedron = new BABYLON.Mesh(name, scene);
  51849. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51850. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  51851. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  51852. vertexData.applyToMesh(polyhedron, options.updatable);
  51853. return polyhedron;
  51854. };
  51855. /**
  51856. * Creates a decal mesh.
  51857. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  51858. * 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.
  51859. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  51860. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  51861. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  51862. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  51863. */
  51864. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  51865. var indices = sourceMesh.getIndices();
  51866. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51867. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51868. var position = options.position || BABYLON.Vector3.Zero();
  51869. var normal = options.normal || BABYLON.Vector3.Up();
  51870. var size = options.size || BABYLON.Vector3.One();
  51871. var angle = options.angle || 0;
  51872. // Getting correct rotation
  51873. if (!normal) {
  51874. var target = new BABYLON.Vector3(0, 0, 1);
  51875. var camera = sourceMesh.getScene().activeCamera;
  51876. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  51877. normal = camera.globalPosition.subtract(cameraWorldTarget);
  51878. }
  51879. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  51880. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  51881. var pitch = Math.atan2(normal.y, len);
  51882. // Matrix
  51883. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  51884. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  51885. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  51886. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  51887. var vertexData = new BABYLON.VertexData();
  51888. vertexData.indices = [];
  51889. vertexData.positions = [];
  51890. vertexData.normals = [];
  51891. vertexData.uvs = [];
  51892. var currentVertexDataIndex = 0;
  51893. var extractDecalVector3 = function (indexId) {
  51894. var result = new BABYLON.PositionNormalVertex();
  51895. if (!indices || !positions || !normals) {
  51896. return result;
  51897. }
  51898. var vertexId = indices[indexId];
  51899. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  51900. // Send vector to decal local world
  51901. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  51902. // Get normal
  51903. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  51904. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  51905. return result;
  51906. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  51907. var clip = function (vertices, axis) {
  51908. if (vertices.length === 0) {
  51909. return vertices;
  51910. }
  51911. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  51912. var clipVertices = function (v0, v1) {
  51913. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  51914. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  51915. };
  51916. var result = new Array();
  51917. for (var index = 0; index < vertices.length; index += 3) {
  51918. var v1Out;
  51919. var v2Out;
  51920. var v3Out;
  51921. var total = 0;
  51922. var nV1 = null;
  51923. var nV2 = null;
  51924. var nV3 = null;
  51925. var nV4 = null;
  51926. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  51927. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  51928. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  51929. v1Out = d1 > 0;
  51930. v2Out = d2 > 0;
  51931. v3Out = d3 > 0;
  51932. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  51933. switch (total) {
  51934. case 0:
  51935. result.push(vertices[index]);
  51936. result.push(vertices[index + 1]);
  51937. result.push(vertices[index + 2]);
  51938. break;
  51939. case 1:
  51940. if (v1Out) {
  51941. nV1 = vertices[index + 1];
  51942. nV2 = vertices[index + 2];
  51943. nV3 = clipVertices(vertices[index], nV1);
  51944. nV4 = clipVertices(vertices[index], nV2);
  51945. }
  51946. if (v2Out) {
  51947. nV1 = vertices[index];
  51948. nV2 = vertices[index + 2];
  51949. nV3 = clipVertices(vertices[index + 1], nV1);
  51950. nV4 = clipVertices(vertices[index + 1], nV2);
  51951. result.push(nV3);
  51952. result.push(nV2.clone());
  51953. result.push(nV1.clone());
  51954. result.push(nV2.clone());
  51955. result.push(nV3.clone());
  51956. result.push(nV4);
  51957. break;
  51958. }
  51959. if (v3Out) {
  51960. nV1 = vertices[index];
  51961. nV2 = vertices[index + 1];
  51962. nV3 = clipVertices(vertices[index + 2], nV1);
  51963. nV4 = clipVertices(vertices[index + 2], nV2);
  51964. }
  51965. if (nV1 && nV2 && nV3 && nV4) {
  51966. result.push(nV1.clone());
  51967. result.push(nV2.clone());
  51968. result.push(nV3);
  51969. result.push(nV4);
  51970. result.push(nV3.clone());
  51971. result.push(nV2.clone());
  51972. }
  51973. break;
  51974. case 2:
  51975. if (!v1Out) {
  51976. nV1 = vertices[index].clone();
  51977. nV2 = clipVertices(nV1, vertices[index + 1]);
  51978. nV3 = clipVertices(nV1, vertices[index + 2]);
  51979. result.push(nV1);
  51980. result.push(nV2);
  51981. result.push(nV3);
  51982. }
  51983. if (!v2Out) {
  51984. nV1 = vertices[index + 1].clone();
  51985. nV2 = clipVertices(nV1, vertices[index + 2]);
  51986. nV3 = clipVertices(nV1, vertices[index]);
  51987. result.push(nV1);
  51988. result.push(nV2);
  51989. result.push(nV3);
  51990. }
  51991. if (!v3Out) {
  51992. nV1 = vertices[index + 2].clone();
  51993. nV2 = clipVertices(nV1, vertices[index]);
  51994. nV3 = clipVertices(nV1, vertices[index + 1]);
  51995. result.push(nV1);
  51996. result.push(nV2);
  51997. result.push(nV3);
  51998. }
  51999. break;
  52000. case 3:
  52001. break;
  52002. }
  52003. }
  52004. return result;
  52005. };
  52006. for (var index = 0; index < indices.length; index += 3) {
  52007. var faceVertices = new Array();
  52008. faceVertices.push(extractDecalVector3(index));
  52009. faceVertices.push(extractDecalVector3(index + 1));
  52010. faceVertices.push(extractDecalVector3(index + 2));
  52011. // Clip
  52012. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  52013. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  52014. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  52015. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  52016. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  52017. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  52018. if (faceVertices.length === 0) {
  52019. continue;
  52020. }
  52021. // Add UVs and get back to world
  52022. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  52023. var vertex = faceVertices[vIndex];
  52024. //TODO check for Int32Array | Uint32Array | Uint16Array
  52025. vertexData.indices.push(currentVertexDataIndex);
  52026. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  52027. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  52028. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  52029. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  52030. currentVertexDataIndex++;
  52031. }
  52032. }
  52033. // Return mesh
  52034. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  52035. vertexData.applyToMesh(decal);
  52036. decal.position = position.clone();
  52037. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  52038. return decal;
  52039. };
  52040. // Privates
  52041. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  52042. // extrusion geometry
  52043. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  52044. var tangents = path3D.getTangents();
  52045. var normals = path3D.getNormals();
  52046. var binormals = path3D.getBinormals();
  52047. var distances = path3D.getDistances();
  52048. var angle = 0;
  52049. var returnScale = function () { return scale !== null ? scale : 1; };
  52050. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  52051. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  52052. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  52053. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52054. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52055. for (var i = 0; i < curve.length; i++) {
  52056. var shapePath = new Array();
  52057. var angleStep = rotate(i, distances[i]);
  52058. var scaleRatio = scl(i, distances[i]);
  52059. for (var p = 0; p < shape.length; p++) {
  52060. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  52061. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  52062. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  52063. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  52064. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  52065. shapePath[p] = rotated;
  52066. }
  52067. shapePaths[index] = shapePath;
  52068. angle += angleStep;
  52069. index++;
  52070. }
  52071. // cap
  52072. var capPath = function (shapePath) {
  52073. var pointCap = Array();
  52074. var barycenter = BABYLON.Vector3.Zero();
  52075. var i;
  52076. for (i = 0; i < shapePath.length; i++) {
  52077. barycenter.addInPlace(shapePath[i]);
  52078. }
  52079. barycenter.scaleInPlace(1.0 / shapePath.length);
  52080. for (i = 0; i < shapePath.length; i++) {
  52081. pointCap.push(barycenter);
  52082. }
  52083. return pointCap;
  52084. };
  52085. switch (cap) {
  52086. case BABYLON.Mesh.NO_CAP:
  52087. break;
  52088. case BABYLON.Mesh.CAP_START:
  52089. shapePaths[0] = capPath(shapePaths[2]);
  52090. shapePaths[1] = shapePaths[2];
  52091. break;
  52092. case BABYLON.Mesh.CAP_END:
  52093. shapePaths[index] = shapePaths[index - 1];
  52094. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52095. break;
  52096. case BABYLON.Mesh.CAP_ALL:
  52097. shapePaths[0] = capPath(shapePaths[2]);
  52098. shapePaths[1] = shapePaths[2];
  52099. shapePaths[index] = shapePaths[index - 1];
  52100. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52101. break;
  52102. default:
  52103. break;
  52104. }
  52105. return shapePaths;
  52106. };
  52107. var path3D;
  52108. var pathArray;
  52109. if (instance) {
  52110. path3D = (instance.path3D).update(curve);
  52111. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  52112. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  52113. return instance;
  52114. }
  52115. // extruded shape creation
  52116. path3D = new BABYLON.Path3D(curve);
  52117. var newShapePaths = new Array();
  52118. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52119. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  52120. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  52121. extrudedGeneric.pathArray = pathArray;
  52122. extrudedGeneric.path3D = path3D;
  52123. extrudedGeneric.cap = cap;
  52124. return extrudedGeneric;
  52125. };
  52126. return MeshBuilder;
  52127. }());
  52128. BABYLON.MeshBuilder = MeshBuilder;
  52129. })(BABYLON || (BABYLON = {}));
  52130. //# sourceMappingURL=babylon.meshBuilder.js.map
  52131. var BABYLON;
  52132. (function (BABYLON) {
  52133. var AudioEngine = /** @class */ (function () {
  52134. function AudioEngine() {
  52135. this._audioContext = null;
  52136. this._audioContextInitialized = false;
  52137. this.canUseWebAudio = false;
  52138. this.WarnedWebAudioUnsupported = false;
  52139. this.unlocked = false;
  52140. this.isMP3supported = false;
  52141. this.isOGGsupported = false;
  52142. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  52143. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  52144. this.canUseWebAudio = true;
  52145. }
  52146. var audioElem = document.createElement('audio');
  52147. try {
  52148. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  52149. this.isMP3supported = true;
  52150. }
  52151. }
  52152. catch (e) {
  52153. // protect error during capability check.
  52154. }
  52155. try {
  52156. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  52157. this.isOGGsupported = true;
  52158. }
  52159. }
  52160. catch (e) {
  52161. // protect error during capability check.
  52162. }
  52163. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  52164. this._unlockiOSaudio();
  52165. }
  52166. else {
  52167. this.unlocked = true;
  52168. }
  52169. }
  52170. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  52171. get: function () {
  52172. if (!this._audioContextInitialized) {
  52173. this._initializeAudioContext();
  52174. }
  52175. return this._audioContext;
  52176. },
  52177. enumerable: true,
  52178. configurable: true
  52179. });
  52180. AudioEngine.prototype._unlockiOSaudio = function () {
  52181. var _this = this;
  52182. var unlockaudio = function () {
  52183. if (!_this.audioContext) {
  52184. return;
  52185. }
  52186. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  52187. var source = _this.audioContext.createBufferSource();
  52188. source.buffer = buffer;
  52189. source.connect(_this.audioContext.destination);
  52190. source.start(0);
  52191. setTimeout(function () {
  52192. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  52193. _this.unlocked = true;
  52194. window.removeEventListener('touchend', unlockaudio, false);
  52195. if (_this.onAudioUnlocked) {
  52196. _this.onAudioUnlocked();
  52197. }
  52198. }
  52199. }, 0);
  52200. };
  52201. window.addEventListener('touchend', unlockaudio, false);
  52202. };
  52203. AudioEngine.prototype._initializeAudioContext = function () {
  52204. try {
  52205. if (this.canUseWebAudio) {
  52206. this._audioContext = new AudioContext();
  52207. // create a global volume gain node
  52208. this.masterGain = this._audioContext.createGain();
  52209. this.masterGain.gain.value = 1;
  52210. this.masterGain.connect(this._audioContext.destination);
  52211. this._audioContextInitialized = true;
  52212. }
  52213. }
  52214. catch (e) {
  52215. this.canUseWebAudio = false;
  52216. BABYLON.Tools.Error("Web Audio: " + e.message);
  52217. }
  52218. };
  52219. AudioEngine.prototype.dispose = function () {
  52220. if (this.canUseWebAudio && this._audioContextInitialized) {
  52221. if (this._connectedAnalyser && this._audioContext) {
  52222. this._connectedAnalyser.stopDebugCanvas();
  52223. this._connectedAnalyser.dispose();
  52224. this.masterGain.disconnect();
  52225. this.masterGain.connect(this._audioContext.destination);
  52226. this._connectedAnalyser = null;
  52227. }
  52228. this.masterGain.gain.value = 1;
  52229. }
  52230. this.WarnedWebAudioUnsupported = false;
  52231. };
  52232. AudioEngine.prototype.getGlobalVolume = function () {
  52233. if (this.canUseWebAudio && this._audioContextInitialized) {
  52234. return this.masterGain.gain.value;
  52235. }
  52236. else {
  52237. return -1;
  52238. }
  52239. };
  52240. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  52241. if (this.canUseWebAudio && this._audioContextInitialized) {
  52242. this.masterGain.gain.value = newVolume;
  52243. }
  52244. };
  52245. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  52246. if (this._connectedAnalyser) {
  52247. this._connectedAnalyser.stopDebugCanvas();
  52248. }
  52249. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  52250. this._connectedAnalyser = analyser;
  52251. this.masterGain.disconnect();
  52252. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  52253. }
  52254. };
  52255. return AudioEngine;
  52256. }());
  52257. BABYLON.AudioEngine = AudioEngine;
  52258. })(BABYLON || (BABYLON = {}));
  52259. //# sourceMappingURL=babylon.audioEngine.js.map
  52260. var BABYLON;
  52261. (function (BABYLON) {
  52262. var Sound = /** @class */ (function () {
  52263. /**
  52264. * Create a sound and attach it to a scene
  52265. * @param name Name of your sound
  52266. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  52267. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  52268. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  52269. */
  52270. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  52271. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  52272. var _this = this;
  52273. this.autoplay = false;
  52274. this.loop = false;
  52275. this.useCustomAttenuation = false;
  52276. this.spatialSound = false;
  52277. this.refDistance = 1;
  52278. this.rolloffFactor = 1;
  52279. this.maxDistance = 100;
  52280. this.distanceModel = "linear";
  52281. this._panningModel = "equalpower";
  52282. this._playbackRate = 1;
  52283. this._streaming = false;
  52284. this._startTime = 0;
  52285. this._startOffset = 0;
  52286. this._position = BABYLON.Vector3.Zero();
  52287. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  52288. this._volume = 1;
  52289. this._isReadyToPlay = false;
  52290. this.isPlaying = false;
  52291. this.isPaused = false;
  52292. this._isDirectional = false;
  52293. // Used if you'd like to create a directional sound.
  52294. // If not set, the sound will be omnidirectional
  52295. this._coneInnerAngle = 360;
  52296. this._coneOuterAngle = 360;
  52297. this._coneOuterGain = 0;
  52298. this._isOutputConnected = false;
  52299. this._urlType = "Unknown";
  52300. this.name = name;
  52301. this._scene = scene;
  52302. this._readyToPlayCallback = readyToPlayCallback;
  52303. // Default custom attenuation function is a linear attenuation
  52304. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  52305. if (currentDistance < maxDistance) {
  52306. return currentVolume * (1 - currentDistance / maxDistance);
  52307. }
  52308. else {
  52309. return 0;
  52310. }
  52311. };
  52312. if (options) {
  52313. this.autoplay = options.autoplay || false;
  52314. this.loop = options.loop || false;
  52315. // if volume === 0, we need another way to check this option
  52316. if (options.volume !== undefined) {
  52317. this._volume = options.volume;
  52318. }
  52319. this.spatialSound = options.spatialSound || false;
  52320. this.maxDistance = options.maxDistance || 100;
  52321. this.useCustomAttenuation = options.useCustomAttenuation || false;
  52322. this.rolloffFactor = options.rolloffFactor || 1;
  52323. this.refDistance = options.refDistance || 1;
  52324. this.distanceModel = options.distanceModel || "linear";
  52325. this._playbackRate = options.playbackRate || 1;
  52326. this._streaming = options.streaming || false;
  52327. }
  52328. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52329. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  52330. this._soundGain.gain.value = this._volume;
  52331. this._inputAudioNode = this._soundGain;
  52332. this._ouputAudioNode = this._soundGain;
  52333. if (this.spatialSound) {
  52334. this._createSpatialParameters();
  52335. }
  52336. this._scene.mainSoundTrack.AddSound(this);
  52337. var validParameter = true;
  52338. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  52339. if (urlOrArrayBuffer) {
  52340. if (typeof (urlOrArrayBuffer) === "string")
  52341. this._urlType = "String";
  52342. if (Array.isArray(urlOrArrayBuffer))
  52343. this._urlType = "Array";
  52344. if (urlOrArrayBuffer instanceof ArrayBuffer)
  52345. this._urlType = "ArrayBuffer";
  52346. var urls = [];
  52347. var codecSupportedFound = false;
  52348. switch (this._urlType) {
  52349. case "ArrayBuffer":
  52350. if (urlOrArrayBuffer.byteLength > 0) {
  52351. codecSupportedFound = true;
  52352. this._soundLoaded(urlOrArrayBuffer);
  52353. }
  52354. break;
  52355. case "String":
  52356. urls.push(urlOrArrayBuffer);
  52357. case "Array":
  52358. if (urls.length === 0)
  52359. urls = urlOrArrayBuffer;
  52360. // If we found a supported format, we load it immediately and stop the loop
  52361. for (var i = 0; i < urls.length; i++) {
  52362. var url = urls[i];
  52363. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  52364. codecSupportedFound = true;
  52365. }
  52366. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  52367. codecSupportedFound = true;
  52368. }
  52369. if (url.indexOf(".wav", url.length - 4) !== -1) {
  52370. codecSupportedFound = true;
  52371. }
  52372. if (url.indexOf("blob:") !== -1) {
  52373. codecSupportedFound = true;
  52374. }
  52375. if (codecSupportedFound) {
  52376. // Loading sound using XHR2
  52377. if (!this._streaming) {
  52378. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  52379. }
  52380. else {
  52381. this._htmlAudioElement = new Audio(url);
  52382. this._htmlAudioElement.controls = false;
  52383. this._htmlAudioElement.loop = this.loop;
  52384. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  52385. this._htmlAudioElement.preload = "auto";
  52386. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  52387. _this._isReadyToPlay = true;
  52388. if (_this.autoplay) {
  52389. _this.play();
  52390. }
  52391. if (_this._readyToPlayCallback) {
  52392. _this._readyToPlayCallback();
  52393. }
  52394. });
  52395. document.body.appendChild(this._htmlAudioElement);
  52396. }
  52397. break;
  52398. }
  52399. }
  52400. break;
  52401. default:
  52402. validParameter = false;
  52403. break;
  52404. }
  52405. if (!validParameter) {
  52406. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  52407. }
  52408. else {
  52409. if (!codecSupportedFound) {
  52410. this._isReadyToPlay = true;
  52411. // Simulating a ready to play event to avoid breaking code path
  52412. if (this._readyToPlayCallback) {
  52413. window.setTimeout(function () {
  52414. if (_this._readyToPlayCallback) {
  52415. _this._readyToPlayCallback();
  52416. }
  52417. }, 1000);
  52418. }
  52419. }
  52420. }
  52421. }
  52422. }
  52423. else {
  52424. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  52425. this._scene.mainSoundTrack.AddSound(this);
  52426. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  52427. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  52428. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  52429. }
  52430. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  52431. if (this._readyToPlayCallback) {
  52432. window.setTimeout(function () {
  52433. if (_this._readyToPlayCallback) {
  52434. _this._readyToPlayCallback();
  52435. }
  52436. }, 1000);
  52437. }
  52438. }
  52439. }
  52440. Sound.prototype.dispose = function () {
  52441. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  52442. if (this.isPlaying) {
  52443. this.stop();
  52444. }
  52445. this._isReadyToPlay = false;
  52446. if (this.soundTrackId === -1) {
  52447. this._scene.mainSoundTrack.RemoveSound(this);
  52448. }
  52449. else {
  52450. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  52451. }
  52452. if (this._soundGain) {
  52453. this._soundGain.disconnect();
  52454. this._soundGain = null;
  52455. }
  52456. if (this._soundPanner) {
  52457. this._soundPanner.disconnect();
  52458. this._soundPanner = null;
  52459. }
  52460. if (this._soundSource) {
  52461. this._soundSource.disconnect();
  52462. this._soundSource = null;
  52463. }
  52464. this._audioBuffer = null;
  52465. if (this._htmlAudioElement) {
  52466. this._htmlAudioElement.pause();
  52467. this._htmlAudioElement.src = "";
  52468. document.body.removeChild(this._htmlAudioElement);
  52469. }
  52470. if (this._connectedMesh && this._registerFunc) {
  52471. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52472. this._connectedMesh = null;
  52473. }
  52474. }
  52475. };
  52476. Sound.prototype.isReady = function () {
  52477. return this._isReadyToPlay;
  52478. };
  52479. Sound.prototype._soundLoaded = function (audioData) {
  52480. var _this = this;
  52481. if (!BABYLON.Engine.audioEngine.audioContext) {
  52482. return;
  52483. }
  52484. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  52485. _this._audioBuffer = buffer;
  52486. _this._isReadyToPlay = true;
  52487. if (_this.autoplay) {
  52488. _this.play();
  52489. }
  52490. if (_this._readyToPlayCallback) {
  52491. _this._readyToPlayCallback();
  52492. }
  52493. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  52494. };
  52495. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  52496. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52497. this._audioBuffer = audioBuffer;
  52498. this._isReadyToPlay = true;
  52499. }
  52500. };
  52501. Sound.prototype.updateOptions = function (options) {
  52502. if (options) {
  52503. this.loop = options.loop || this.loop;
  52504. this.maxDistance = options.maxDistance || this.maxDistance;
  52505. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  52506. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  52507. this.refDistance = options.refDistance || this.refDistance;
  52508. this.distanceModel = options.distanceModel || this.distanceModel;
  52509. this._playbackRate = options.playbackRate || this._playbackRate;
  52510. this._updateSpatialParameters();
  52511. if (this.isPlaying) {
  52512. if (this._streaming) {
  52513. this._htmlAudioElement.playbackRate = this._playbackRate;
  52514. }
  52515. else {
  52516. if (this._soundSource) {
  52517. this._soundSource.playbackRate.value = this._playbackRate;
  52518. }
  52519. }
  52520. }
  52521. }
  52522. };
  52523. Sound.prototype._createSpatialParameters = function () {
  52524. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52525. if (this._scene.headphone) {
  52526. this._panningModel = "HRTF";
  52527. }
  52528. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  52529. this._updateSpatialParameters();
  52530. this._soundPanner.connect(this._ouputAudioNode);
  52531. this._inputAudioNode = this._soundPanner;
  52532. }
  52533. };
  52534. Sound.prototype._updateSpatialParameters = function () {
  52535. if (this.spatialSound && this._soundPanner) {
  52536. if (this.useCustomAttenuation) {
  52537. // Tricks to disable in a way embedded Web Audio attenuation
  52538. this._soundPanner.distanceModel = "linear";
  52539. this._soundPanner.maxDistance = Number.MAX_VALUE;
  52540. this._soundPanner.refDistance = 1;
  52541. this._soundPanner.rolloffFactor = 1;
  52542. this._soundPanner.panningModel = this._panningModel;
  52543. }
  52544. else {
  52545. this._soundPanner.distanceModel = this.distanceModel;
  52546. this._soundPanner.maxDistance = this.maxDistance;
  52547. this._soundPanner.refDistance = this.refDistance;
  52548. this._soundPanner.rolloffFactor = this.rolloffFactor;
  52549. this._soundPanner.panningModel = this._panningModel;
  52550. }
  52551. }
  52552. };
  52553. Sound.prototype.switchPanningModelToHRTF = function () {
  52554. this._panningModel = "HRTF";
  52555. this._switchPanningModel();
  52556. };
  52557. Sound.prototype.switchPanningModelToEqualPower = function () {
  52558. this._panningModel = "equalpower";
  52559. this._switchPanningModel();
  52560. };
  52561. Sound.prototype._switchPanningModel = function () {
  52562. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52563. this._soundPanner.panningModel = this._panningModel;
  52564. }
  52565. };
  52566. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  52567. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52568. if (this._isOutputConnected) {
  52569. this._ouputAudioNode.disconnect();
  52570. }
  52571. this._ouputAudioNode.connect(soundTrackAudioNode);
  52572. this._isOutputConnected = true;
  52573. }
  52574. };
  52575. /**
  52576. * Transform this sound into a directional source
  52577. * @param coneInnerAngle Size of the inner cone in degree
  52578. * @param coneOuterAngle Size of the outer cone in degree
  52579. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  52580. */
  52581. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  52582. if (coneOuterAngle < coneInnerAngle) {
  52583. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  52584. return;
  52585. }
  52586. this._coneInnerAngle = coneInnerAngle;
  52587. this._coneOuterAngle = coneOuterAngle;
  52588. this._coneOuterGain = coneOuterGain;
  52589. this._isDirectional = true;
  52590. if (this.isPlaying && this.loop) {
  52591. this.stop();
  52592. this.play();
  52593. }
  52594. };
  52595. Sound.prototype.setPosition = function (newPosition) {
  52596. this._position = newPosition;
  52597. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52598. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  52599. }
  52600. };
  52601. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  52602. this._localDirection = newLocalDirection;
  52603. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  52604. this._updateDirection();
  52605. }
  52606. };
  52607. Sound.prototype._updateDirection = function () {
  52608. if (!this._connectedMesh || !this._soundPanner) {
  52609. return;
  52610. }
  52611. var mat = this._connectedMesh.getWorldMatrix();
  52612. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  52613. direction.normalize();
  52614. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  52615. };
  52616. Sound.prototype.updateDistanceFromListener = function () {
  52617. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  52618. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  52619. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  52620. }
  52621. };
  52622. Sound.prototype.setAttenuationFunction = function (callback) {
  52623. this._customAttenuationFunction = callback;
  52624. };
  52625. /**
  52626. * Play the sound
  52627. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  52628. * @param offset (optional) Start the sound setting it at a specific time
  52629. */
  52630. Sound.prototype.play = function (time, offset) {
  52631. var _this = this;
  52632. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  52633. try {
  52634. if (this._startOffset < 0) {
  52635. time = -this._startOffset;
  52636. this._startOffset = 0;
  52637. }
  52638. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  52639. if (!this._soundSource || !this._streamingSource) {
  52640. if (this.spatialSound && this._soundPanner) {
  52641. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  52642. if (this._isDirectional) {
  52643. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  52644. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  52645. this._soundPanner.coneOuterGain = this._coneOuterGain;
  52646. if (this._connectedMesh) {
  52647. this._updateDirection();
  52648. }
  52649. else {
  52650. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  52651. }
  52652. }
  52653. }
  52654. }
  52655. if (this._streaming) {
  52656. if (!this._streamingSource) {
  52657. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  52658. this._htmlAudioElement.onended = function () { _this._onended(); };
  52659. this._htmlAudioElement.playbackRate = this._playbackRate;
  52660. }
  52661. this._streamingSource.disconnect();
  52662. this._streamingSource.connect(this._inputAudioNode);
  52663. this._htmlAudioElement.play();
  52664. }
  52665. else {
  52666. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  52667. this._soundSource.buffer = this._audioBuffer;
  52668. this._soundSource.connect(this._inputAudioNode);
  52669. this._soundSource.loop = this.loop;
  52670. this._soundSource.playbackRate.value = this._playbackRate;
  52671. this._soundSource.onended = function () { _this._onended(); };
  52672. if (this._soundSource.buffer) {
  52673. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  52674. }
  52675. }
  52676. this._startTime = startTime;
  52677. this.isPlaying = true;
  52678. this.isPaused = false;
  52679. }
  52680. catch (ex) {
  52681. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  52682. }
  52683. }
  52684. };
  52685. Sound.prototype._onended = function () {
  52686. this.isPlaying = false;
  52687. if (this.onended) {
  52688. this.onended();
  52689. }
  52690. };
  52691. /**
  52692. * Stop the sound
  52693. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  52694. */
  52695. Sound.prototype.stop = function (time) {
  52696. if (this.isPlaying) {
  52697. if (this._streaming) {
  52698. this._htmlAudioElement.pause();
  52699. // Test needed for Firefox or it will generate an Invalid State Error
  52700. if (this._htmlAudioElement.currentTime > 0) {
  52701. this._htmlAudioElement.currentTime = 0;
  52702. }
  52703. }
  52704. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  52705. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  52706. this._soundSource.stop(stopTime);
  52707. this._soundSource.onended = function () { };
  52708. if (!this.isPaused) {
  52709. this._startOffset = 0;
  52710. }
  52711. }
  52712. this.isPlaying = false;
  52713. }
  52714. };
  52715. Sound.prototype.pause = function () {
  52716. if (this.isPlaying) {
  52717. this.isPaused = true;
  52718. if (this._streaming) {
  52719. this._htmlAudioElement.pause();
  52720. }
  52721. else if (BABYLON.Engine.audioEngine.audioContext) {
  52722. this.stop(0);
  52723. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  52724. }
  52725. }
  52726. };
  52727. Sound.prototype.setVolume = function (newVolume, time) {
  52728. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  52729. if (time && BABYLON.Engine.audioEngine.audioContext) {
  52730. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  52731. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  52732. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  52733. }
  52734. else {
  52735. this._soundGain.gain.value = newVolume;
  52736. }
  52737. }
  52738. this._volume = newVolume;
  52739. };
  52740. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  52741. this._playbackRate = newPlaybackRate;
  52742. if (this.isPlaying) {
  52743. if (this._streaming) {
  52744. this._htmlAudioElement.playbackRate = this._playbackRate;
  52745. }
  52746. else if (this._soundSource) {
  52747. this._soundSource.playbackRate.value = this._playbackRate;
  52748. }
  52749. }
  52750. };
  52751. Sound.prototype.getVolume = function () {
  52752. return this._volume;
  52753. };
  52754. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  52755. var _this = this;
  52756. if (this._connectedMesh && this._registerFunc) {
  52757. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52758. this._registerFunc = null;
  52759. }
  52760. this._connectedMesh = meshToConnectTo;
  52761. if (!this.spatialSound) {
  52762. this.spatialSound = true;
  52763. this._createSpatialParameters();
  52764. if (this.isPlaying && this.loop) {
  52765. this.stop();
  52766. this.play();
  52767. }
  52768. }
  52769. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  52770. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  52771. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  52772. };
  52773. Sound.prototype.detachFromMesh = function () {
  52774. if (this._connectedMesh && this._registerFunc) {
  52775. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52776. this._registerFunc = null;
  52777. this._connectedMesh = null;
  52778. }
  52779. };
  52780. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  52781. if (!node.getBoundingInfo) {
  52782. return;
  52783. }
  52784. var mesh = node;
  52785. var boundingInfo = mesh.getBoundingInfo();
  52786. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  52787. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  52788. this._updateDirection();
  52789. }
  52790. };
  52791. Sound.prototype.clone = function () {
  52792. var _this = this;
  52793. if (!this._streaming) {
  52794. var setBufferAndRun = function () {
  52795. if (_this._isReadyToPlay) {
  52796. clonedSound._audioBuffer = _this.getAudioBuffer();
  52797. clonedSound._isReadyToPlay = true;
  52798. if (clonedSound.autoplay) {
  52799. clonedSound.play();
  52800. }
  52801. }
  52802. else {
  52803. window.setTimeout(setBufferAndRun, 300);
  52804. }
  52805. };
  52806. var currentOptions = {
  52807. autoplay: this.autoplay, loop: this.loop,
  52808. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  52809. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  52810. refDistance: this.refDistance, distanceModel: this.distanceModel
  52811. };
  52812. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  52813. if (this.useCustomAttenuation) {
  52814. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  52815. }
  52816. clonedSound.setPosition(this._position);
  52817. clonedSound.setPlaybackRate(this._playbackRate);
  52818. setBufferAndRun();
  52819. return clonedSound;
  52820. }
  52821. else {
  52822. return null;
  52823. }
  52824. };
  52825. Sound.prototype.getAudioBuffer = function () {
  52826. return this._audioBuffer;
  52827. };
  52828. Sound.prototype.serialize = function () {
  52829. var serializationObject = {
  52830. name: this.name,
  52831. url: this.name,
  52832. autoplay: this.autoplay,
  52833. loop: this.loop,
  52834. volume: this._volume,
  52835. spatialSound: this.spatialSound,
  52836. maxDistance: this.maxDistance,
  52837. rolloffFactor: this.rolloffFactor,
  52838. refDistance: this.refDistance,
  52839. distanceModel: this.distanceModel,
  52840. playbackRate: this._playbackRate,
  52841. panningModel: this._panningModel,
  52842. soundTrackId: this.soundTrackId
  52843. };
  52844. if (this.spatialSound) {
  52845. if (this._connectedMesh)
  52846. serializationObject.connectedMeshId = this._connectedMesh.id;
  52847. serializationObject.position = this._position.asArray();
  52848. serializationObject.refDistance = this.refDistance;
  52849. serializationObject.distanceModel = this.distanceModel;
  52850. serializationObject.isDirectional = this._isDirectional;
  52851. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  52852. serializationObject.coneInnerAngle = this._coneInnerAngle;
  52853. serializationObject.coneOuterAngle = this._coneOuterAngle;
  52854. serializationObject.coneOuterGain = this._coneOuterGain;
  52855. }
  52856. return serializationObject;
  52857. };
  52858. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  52859. var soundName = parsedSound.name;
  52860. var soundUrl;
  52861. if (parsedSound.url) {
  52862. soundUrl = rootUrl + parsedSound.url;
  52863. }
  52864. else {
  52865. soundUrl = rootUrl + soundName;
  52866. }
  52867. var options = {
  52868. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  52869. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  52870. rolloffFactor: parsedSound.rolloffFactor,
  52871. refDistance: parsedSound.refDistance,
  52872. distanceModel: parsedSound.distanceModel,
  52873. playbackRate: parsedSound.playbackRate
  52874. };
  52875. var newSound;
  52876. if (!sourceSound) {
  52877. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  52878. scene._addPendingData(newSound);
  52879. }
  52880. else {
  52881. var setBufferAndRun = function () {
  52882. if (sourceSound._isReadyToPlay) {
  52883. newSound._audioBuffer = sourceSound.getAudioBuffer();
  52884. newSound._isReadyToPlay = true;
  52885. if (newSound.autoplay) {
  52886. newSound.play();
  52887. }
  52888. }
  52889. else {
  52890. window.setTimeout(setBufferAndRun, 300);
  52891. }
  52892. };
  52893. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  52894. setBufferAndRun();
  52895. }
  52896. if (parsedSound.position) {
  52897. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  52898. newSound.setPosition(soundPosition);
  52899. }
  52900. if (parsedSound.isDirectional) {
  52901. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  52902. if (parsedSound.localDirectionToMesh) {
  52903. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  52904. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  52905. }
  52906. }
  52907. if (parsedSound.connectedMeshId) {
  52908. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  52909. if (connectedMesh) {
  52910. newSound.attachToMesh(connectedMesh);
  52911. }
  52912. }
  52913. return newSound;
  52914. };
  52915. return Sound;
  52916. }());
  52917. BABYLON.Sound = Sound;
  52918. })(BABYLON || (BABYLON = {}));
  52919. //# sourceMappingURL=babylon.sound.js.map
  52920. var BABYLON;
  52921. (function (BABYLON) {
  52922. var SoundTrack = /** @class */ (function () {
  52923. function SoundTrack(scene, options) {
  52924. this.id = -1;
  52925. this._isMainTrack = false;
  52926. this._isInitialized = false;
  52927. this._scene = scene;
  52928. this.soundCollection = new Array();
  52929. this._options = options;
  52930. if (!this._isMainTrack) {
  52931. this._scene.soundTracks.push(this);
  52932. this.id = this._scene.soundTracks.length - 1;
  52933. }
  52934. }
  52935. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  52936. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52937. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  52938. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  52939. if (this._options) {
  52940. if (this._options.volume) {
  52941. this._outputAudioNode.gain.value = this._options.volume;
  52942. }
  52943. if (this._options.mainTrack) {
  52944. this._isMainTrack = this._options.mainTrack;
  52945. }
  52946. }
  52947. this._isInitialized = true;
  52948. }
  52949. };
  52950. SoundTrack.prototype.dispose = function () {
  52951. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52952. if (this._connectedAnalyser) {
  52953. this._connectedAnalyser.stopDebugCanvas();
  52954. }
  52955. while (this.soundCollection.length) {
  52956. this.soundCollection[0].dispose();
  52957. }
  52958. if (this._outputAudioNode) {
  52959. this._outputAudioNode.disconnect();
  52960. }
  52961. this._outputAudioNode = null;
  52962. }
  52963. };
  52964. SoundTrack.prototype.AddSound = function (sound) {
  52965. if (!this._isInitialized) {
  52966. this._initializeSoundTrackAudioGraph();
  52967. }
  52968. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  52969. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  52970. }
  52971. if (sound.soundTrackId) {
  52972. if (sound.soundTrackId === -1) {
  52973. this._scene.mainSoundTrack.RemoveSound(sound);
  52974. }
  52975. else {
  52976. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  52977. }
  52978. }
  52979. this.soundCollection.push(sound);
  52980. sound.soundTrackId = this.id;
  52981. };
  52982. SoundTrack.prototype.RemoveSound = function (sound) {
  52983. var index = this.soundCollection.indexOf(sound);
  52984. if (index !== -1) {
  52985. this.soundCollection.splice(index, 1);
  52986. }
  52987. };
  52988. SoundTrack.prototype.setVolume = function (newVolume) {
  52989. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  52990. this._outputAudioNode.gain.value = newVolume;
  52991. }
  52992. };
  52993. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  52994. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52995. for (var i = 0; i < this.soundCollection.length; i++) {
  52996. this.soundCollection[i].switchPanningModelToHRTF();
  52997. }
  52998. }
  52999. };
  53000. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  53001. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53002. for (var i = 0; i < this.soundCollection.length; i++) {
  53003. this.soundCollection[i].switchPanningModelToEqualPower();
  53004. }
  53005. }
  53006. };
  53007. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  53008. if (this._connectedAnalyser) {
  53009. this._connectedAnalyser.stopDebugCanvas();
  53010. }
  53011. this._connectedAnalyser = analyser;
  53012. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53013. this._outputAudioNode.disconnect();
  53014. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  53015. }
  53016. };
  53017. return SoundTrack;
  53018. }());
  53019. BABYLON.SoundTrack = SoundTrack;
  53020. })(BABYLON || (BABYLON = {}));
  53021. //# sourceMappingURL=babylon.soundtrack.js.map
  53022. var BABYLON;
  53023. (function (BABYLON) {
  53024. var Analyser = /** @class */ (function () {
  53025. function Analyser(scene) {
  53026. this.SMOOTHING = 0.75;
  53027. this.FFT_SIZE = 512;
  53028. this.BARGRAPHAMPLITUDE = 256;
  53029. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53030. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53031. this._scene = scene;
  53032. this._audioEngine = BABYLON.Engine.audioEngine;
  53033. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  53034. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53035. this._webAudioAnalyser.minDecibels = -140;
  53036. this._webAudioAnalyser.maxDecibels = 0;
  53037. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53038. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53039. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53040. }
  53041. }
  53042. Analyser.prototype.getFrequencyBinCount = function () {
  53043. if (this._audioEngine.canUseWebAudio) {
  53044. return this._webAudioAnalyser.frequencyBinCount;
  53045. }
  53046. else {
  53047. return 0;
  53048. }
  53049. };
  53050. Analyser.prototype.getByteFrequencyData = function () {
  53051. if (this._audioEngine.canUseWebAudio) {
  53052. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53053. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53054. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53055. }
  53056. return this._byteFreqs;
  53057. };
  53058. Analyser.prototype.getByteTimeDomainData = function () {
  53059. if (this._audioEngine.canUseWebAudio) {
  53060. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53061. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53062. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53063. }
  53064. return this._byteTime;
  53065. };
  53066. Analyser.prototype.getFloatFrequencyData = function () {
  53067. if (this._audioEngine.canUseWebAudio) {
  53068. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53069. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53070. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53071. }
  53072. return this._floatFreqs;
  53073. };
  53074. Analyser.prototype.drawDebugCanvas = function () {
  53075. var _this = this;
  53076. if (this._audioEngine.canUseWebAudio) {
  53077. if (!this._debugCanvas) {
  53078. this._debugCanvas = document.createElement("canvas");
  53079. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53080. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53081. this._debugCanvas.style.position = "absolute";
  53082. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53083. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53084. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53085. document.body.appendChild(this._debugCanvas);
  53086. this._registerFunc = function () {
  53087. _this.drawDebugCanvas();
  53088. };
  53089. this._scene.registerBeforeRender(this._registerFunc);
  53090. }
  53091. if (this._registerFunc && this._debugCanvasContext) {
  53092. var workingArray = this.getByteFrequencyData();
  53093. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53094. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53095. // Draw the frequency domain chart.
  53096. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53097. var value = workingArray[i];
  53098. var percent = value / this.BARGRAPHAMPLITUDE;
  53099. var height = this.DEBUGCANVASSIZE.height * percent;
  53100. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53101. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53102. var hue = i / this.getFrequencyBinCount() * 360;
  53103. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53104. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53105. }
  53106. }
  53107. }
  53108. };
  53109. Analyser.prototype.stopDebugCanvas = function () {
  53110. if (this._debugCanvas) {
  53111. if (this._registerFunc) {
  53112. this._scene.unregisterBeforeRender(this._registerFunc);
  53113. this._registerFunc = null;
  53114. }
  53115. document.body.removeChild(this._debugCanvas);
  53116. this._debugCanvas = null;
  53117. this._debugCanvasContext = null;
  53118. }
  53119. };
  53120. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53121. if (this._audioEngine.canUseWebAudio) {
  53122. inputAudioNode.connect(this._webAudioAnalyser);
  53123. this._webAudioAnalyser.connect(outputAudioNode);
  53124. }
  53125. };
  53126. Analyser.prototype.dispose = function () {
  53127. if (this._audioEngine.canUseWebAudio) {
  53128. this._webAudioAnalyser.disconnect();
  53129. }
  53130. };
  53131. return Analyser;
  53132. }());
  53133. BABYLON.Analyser = Analyser;
  53134. })(BABYLON || (BABYLON = {}));
  53135. //# sourceMappingURL=babylon.analyser.js.map
  53136. var BABYLON;
  53137. (function (BABYLON) {
  53138. var CubeTexture = /** @class */ (function (_super) {
  53139. __extends(CubeTexture, _super);
  53140. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  53141. if (extensions === void 0) { extensions = null; }
  53142. if (noMipmap === void 0) { noMipmap = false; }
  53143. if (files === void 0) { files = null; }
  53144. if (onLoad === void 0) { onLoad = null; }
  53145. if (onError === void 0) { onError = null; }
  53146. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  53147. if (prefiltered === void 0) { prefiltered = false; }
  53148. if (forcedExtension === void 0) { forcedExtension = null; }
  53149. var _this = _super.call(this, scene) || this;
  53150. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  53151. _this.name = rootUrl;
  53152. _this.url = rootUrl;
  53153. _this._noMipmap = noMipmap;
  53154. _this.hasAlpha = false;
  53155. _this._format = format;
  53156. _this._prefiltered = prefiltered;
  53157. _this.isCube = true;
  53158. _this._textureMatrix = BABYLON.Matrix.Identity();
  53159. if (prefiltered) {
  53160. _this.gammaSpace = false;
  53161. }
  53162. if (!rootUrl && !files) {
  53163. return _this;
  53164. }
  53165. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  53166. var lastDot = rootUrl.lastIndexOf(".");
  53167. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  53168. var isDDS = (extension === ".dds");
  53169. if (!files) {
  53170. if (!isDDS && !extensions) {
  53171. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  53172. }
  53173. files = [];
  53174. if (extensions) {
  53175. for (var index = 0; index < extensions.length; index++) {
  53176. files.push(rootUrl + extensions[index]);
  53177. }
  53178. }
  53179. }
  53180. _this._files = files;
  53181. if (!_this._texture) {
  53182. if (!scene.useDelayedTextureLoading) {
  53183. if (prefiltered) {
  53184. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  53185. }
  53186. else {
  53187. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  53188. }
  53189. }
  53190. else {
  53191. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53192. }
  53193. }
  53194. else if (onLoad) {
  53195. if (_this._texture.isReady) {
  53196. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  53197. }
  53198. else {
  53199. _this._texture.onLoadedObservable.add(onLoad);
  53200. }
  53201. }
  53202. return _this;
  53203. }
  53204. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  53205. return new CubeTexture("", scene, null, noMipmap, files);
  53206. };
  53207. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  53208. if (forcedExtension === void 0) { forcedExtension = null; }
  53209. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  53210. };
  53211. // Methods
  53212. CubeTexture.prototype.delayLoad = function () {
  53213. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53214. return;
  53215. }
  53216. var scene = this.getScene();
  53217. if (!scene) {
  53218. return;
  53219. }
  53220. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53221. this._texture = this._getFromCache(this.url, this._noMipmap);
  53222. if (!this._texture) {
  53223. if (this._prefiltered) {
  53224. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  53225. }
  53226. else {
  53227. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  53228. }
  53229. }
  53230. };
  53231. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  53232. return this._textureMatrix;
  53233. };
  53234. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  53235. this._textureMatrix = value;
  53236. };
  53237. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53238. var texture = BABYLON.SerializationHelper.Parse(function () {
  53239. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  53240. }, parsedTexture, scene);
  53241. // Animations
  53242. if (parsedTexture.animations) {
  53243. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  53244. var parsedAnimation = parsedTexture.animations[animationIndex];
  53245. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53246. }
  53247. }
  53248. return texture;
  53249. };
  53250. CubeTexture.prototype.clone = function () {
  53251. var _this = this;
  53252. return BABYLON.SerializationHelper.Clone(function () {
  53253. var scene = _this.getScene();
  53254. if (!scene) {
  53255. return _this;
  53256. }
  53257. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  53258. }, this);
  53259. };
  53260. return CubeTexture;
  53261. }(BABYLON.BaseTexture));
  53262. BABYLON.CubeTexture = CubeTexture;
  53263. })(BABYLON || (BABYLON = {}));
  53264. //# sourceMappingURL=babylon.cubeTexture.js.map
  53265. var BABYLON;
  53266. (function (BABYLON) {
  53267. var RenderTargetTexture = /** @class */ (function (_super) {
  53268. __extends(RenderTargetTexture, _super);
  53269. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  53270. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  53271. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53272. if (isCube === void 0) { isCube = false; }
  53273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53274. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  53275. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  53276. if (isMulti === void 0) { isMulti = false; }
  53277. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  53278. _this.isCube = isCube;
  53279. /**
  53280. * Use this list to define the list of mesh you want to render.
  53281. */
  53282. _this.renderList = new Array();
  53283. _this.renderParticles = true;
  53284. _this.renderSprites = false;
  53285. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  53286. _this.ignoreCameraViewport = false;
  53287. // Events
  53288. /**
  53289. * An event triggered when the texture is unbind.
  53290. * @type {BABYLON.Observable}
  53291. */
  53292. _this.onBeforeBindObservable = new BABYLON.Observable();
  53293. /**
  53294. * An event triggered when the texture is unbind.
  53295. * @type {BABYLON.Observable}
  53296. */
  53297. _this.onAfterUnbindObservable = new BABYLON.Observable();
  53298. /**
  53299. * An event triggered before rendering the texture
  53300. * @type {BABYLON.Observable}
  53301. */
  53302. _this.onBeforeRenderObservable = new BABYLON.Observable();
  53303. /**
  53304. * An event triggered after rendering the texture
  53305. * @type {BABYLON.Observable}
  53306. */
  53307. _this.onAfterRenderObservable = new BABYLON.Observable();
  53308. /**
  53309. * An event triggered after the texture clear
  53310. * @type {BABYLON.Observable}
  53311. */
  53312. _this.onClearObservable = new BABYLON.Observable();
  53313. _this._currentRefreshId = -1;
  53314. _this._refreshRate = 1;
  53315. _this._samples = 1;
  53316. scene = _this.getScene();
  53317. if (!scene) {
  53318. return _this;
  53319. }
  53320. _this._engine = scene.getEngine();
  53321. _this.name = name;
  53322. _this.isRenderTarget = true;
  53323. _this._initialSizeParameter = size;
  53324. _this._processSizeParameter(size);
  53325. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  53326. });
  53327. _this._generateMipMaps = generateMipMaps ? true : false;
  53328. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  53329. // Rendering groups
  53330. _this._renderingManager = new BABYLON.RenderingManager(scene);
  53331. if (isMulti) {
  53332. return _this;
  53333. }
  53334. _this._renderTargetOptions = {
  53335. generateMipMaps: generateMipMaps,
  53336. type: type,
  53337. samplingMode: samplingMode,
  53338. generateDepthBuffer: generateDepthBuffer,
  53339. generateStencilBuffer: generateStencilBuffer
  53340. };
  53341. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  53342. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53343. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53344. }
  53345. if (isCube) {
  53346. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  53347. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  53348. _this._textureMatrix = BABYLON.Matrix.Identity();
  53349. }
  53350. else {
  53351. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  53352. }
  53353. return _this;
  53354. }
  53355. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  53356. get: function () {
  53357. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  53358. },
  53359. enumerable: true,
  53360. configurable: true
  53361. });
  53362. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  53363. get: function () {
  53364. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  53365. },
  53366. enumerable: true,
  53367. configurable: true
  53368. });
  53369. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  53370. get: function () {
  53371. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  53372. },
  53373. enumerable: true,
  53374. configurable: true
  53375. });
  53376. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  53377. set: function (callback) {
  53378. if (this._onAfterUnbindObserver) {
  53379. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  53380. }
  53381. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  53382. },
  53383. enumerable: true,
  53384. configurable: true
  53385. });
  53386. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  53387. set: function (callback) {
  53388. if (this._onBeforeRenderObserver) {
  53389. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53390. }
  53391. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53392. },
  53393. enumerable: true,
  53394. configurable: true
  53395. });
  53396. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  53397. set: function (callback) {
  53398. if (this._onAfterRenderObserver) {
  53399. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53400. }
  53401. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53402. },
  53403. enumerable: true,
  53404. configurable: true
  53405. });
  53406. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  53407. set: function (callback) {
  53408. if (this._onClearObserver) {
  53409. this.onClearObservable.remove(this._onClearObserver);
  53410. }
  53411. this._onClearObserver = this.onClearObservable.add(callback);
  53412. },
  53413. enumerable: true,
  53414. configurable: true
  53415. });
  53416. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  53417. get: function () {
  53418. return this._renderTargetOptions;
  53419. },
  53420. enumerable: true,
  53421. configurable: true
  53422. });
  53423. RenderTargetTexture.prototype._onRatioRescale = function () {
  53424. if (this._sizeRatio) {
  53425. this.resize(this._initialSizeParameter);
  53426. }
  53427. };
  53428. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  53429. if (size.ratio) {
  53430. this._sizeRatio = size.ratio;
  53431. this._size = {
  53432. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  53433. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  53434. };
  53435. }
  53436. else {
  53437. this._size = size;
  53438. }
  53439. };
  53440. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  53441. get: function () {
  53442. return this._samples;
  53443. },
  53444. set: function (value) {
  53445. if (this._samples === value) {
  53446. return;
  53447. }
  53448. var scene = this.getScene();
  53449. if (!scene) {
  53450. return;
  53451. }
  53452. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  53453. },
  53454. enumerable: true,
  53455. configurable: true
  53456. });
  53457. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  53458. this._currentRefreshId = -1;
  53459. };
  53460. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  53461. get: function () {
  53462. return this._refreshRate;
  53463. },
  53464. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  53465. set: function (value) {
  53466. this._refreshRate = value;
  53467. this.resetRefreshCounter();
  53468. },
  53469. enumerable: true,
  53470. configurable: true
  53471. });
  53472. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  53473. if (!this._postProcessManager) {
  53474. var scene = this.getScene();
  53475. if (!scene) {
  53476. return;
  53477. }
  53478. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  53479. this._postProcesses = new Array();
  53480. }
  53481. this._postProcesses.push(postProcess);
  53482. this._postProcesses[0].autoClear = false;
  53483. };
  53484. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  53485. if (!this._postProcesses) {
  53486. return;
  53487. }
  53488. if (dispose) {
  53489. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  53490. var postProcess = _a[_i];
  53491. postProcess.dispose();
  53492. }
  53493. }
  53494. this._postProcesses = [];
  53495. };
  53496. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  53497. if (!this._postProcesses) {
  53498. return;
  53499. }
  53500. var index = this._postProcesses.indexOf(postProcess);
  53501. if (index === -1) {
  53502. return;
  53503. }
  53504. this._postProcesses.splice(index, 1);
  53505. if (this._postProcesses.length > 0) {
  53506. this._postProcesses[0].autoClear = false;
  53507. }
  53508. };
  53509. RenderTargetTexture.prototype._shouldRender = function () {
  53510. if (this._currentRefreshId === -1) {
  53511. this._currentRefreshId = 1;
  53512. return true;
  53513. }
  53514. if (this.refreshRate === this._currentRefreshId) {
  53515. this._currentRefreshId = 1;
  53516. return true;
  53517. }
  53518. this._currentRefreshId++;
  53519. return false;
  53520. };
  53521. RenderTargetTexture.prototype.getRenderSize = function () {
  53522. if (this._size.width) {
  53523. return this._size.width;
  53524. }
  53525. return this._size;
  53526. };
  53527. RenderTargetTexture.prototype.getRenderWidth = function () {
  53528. if (this._size.width) {
  53529. return this._size.width;
  53530. }
  53531. return this._size;
  53532. };
  53533. RenderTargetTexture.prototype.getRenderHeight = function () {
  53534. if (this._size.width) {
  53535. return this._size.height;
  53536. }
  53537. return this._size;
  53538. };
  53539. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  53540. get: function () {
  53541. return true;
  53542. },
  53543. enumerable: true,
  53544. configurable: true
  53545. });
  53546. RenderTargetTexture.prototype.scale = function (ratio) {
  53547. var newSize = this.getRenderSize() * ratio;
  53548. this.resize(newSize);
  53549. };
  53550. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  53551. if (this.isCube) {
  53552. return this._textureMatrix;
  53553. }
  53554. return _super.prototype.getReflectionTextureMatrix.call(this);
  53555. };
  53556. RenderTargetTexture.prototype.resize = function (size) {
  53557. this.releaseInternalTexture();
  53558. var scene = this.getScene();
  53559. if (!scene) {
  53560. return;
  53561. }
  53562. this._processSizeParameter(size);
  53563. if (this.isCube) {
  53564. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  53565. }
  53566. else {
  53567. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  53568. }
  53569. };
  53570. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  53571. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  53572. if (dumpForDebug === void 0) { dumpForDebug = false; }
  53573. var scene = this.getScene();
  53574. if (!scene) {
  53575. return;
  53576. }
  53577. var engine = scene.getEngine();
  53578. if (this.useCameraPostProcesses !== undefined) {
  53579. useCameraPostProcess = this.useCameraPostProcesses;
  53580. }
  53581. if (this._waitingRenderList) {
  53582. this.renderList = [];
  53583. for (var index = 0; index < this._waitingRenderList.length; index++) {
  53584. var id = this._waitingRenderList[index];
  53585. var mesh_1 = scene.getMeshByID(id);
  53586. if (mesh_1) {
  53587. this.renderList.push(mesh_1);
  53588. }
  53589. }
  53590. delete this._waitingRenderList;
  53591. }
  53592. // Is predicate defined?
  53593. if (this.renderListPredicate) {
  53594. if (this.renderList) {
  53595. this.renderList.splice(0); // Clear previous renderList
  53596. }
  53597. else {
  53598. this.renderList = [];
  53599. }
  53600. var scene = this.getScene();
  53601. if (!scene) {
  53602. return;
  53603. }
  53604. var sceneMeshes = scene.meshes;
  53605. for (var index = 0; index < sceneMeshes.length; index++) {
  53606. var mesh = sceneMeshes[index];
  53607. if (this.renderListPredicate(mesh)) {
  53608. this.renderList.push(mesh);
  53609. }
  53610. }
  53611. }
  53612. this.onBeforeBindObservable.notifyObservers(this);
  53613. // Set custom projection.
  53614. // Needs to be before binding to prevent changing the aspect ratio.
  53615. var camera;
  53616. if (this.activeCamera) {
  53617. camera = this.activeCamera;
  53618. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  53619. if (this.activeCamera !== scene.activeCamera) {
  53620. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  53621. }
  53622. }
  53623. else {
  53624. camera = scene.activeCamera;
  53625. if (camera) {
  53626. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  53627. }
  53628. }
  53629. // Prepare renderingManager
  53630. this._renderingManager.reset();
  53631. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  53632. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  53633. var sceneRenderId = scene.getRenderId();
  53634. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  53635. var mesh = currentRenderList[meshIndex];
  53636. if (mesh) {
  53637. if (!mesh.isReady()) {
  53638. // Reset _currentRefreshId
  53639. this.resetRefreshCounter();
  53640. continue;
  53641. }
  53642. mesh._preActivateForIntermediateRendering(sceneRenderId);
  53643. var isMasked = void 0;
  53644. if (!this.renderList && camera) {
  53645. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  53646. }
  53647. else {
  53648. isMasked = false;
  53649. }
  53650. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  53651. mesh._activate(sceneRenderId);
  53652. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  53653. var subMesh = mesh.subMeshes[subIndex];
  53654. scene._activeIndices.addCount(subMesh.indexCount, false);
  53655. this._renderingManager.dispatch(subMesh, mesh);
  53656. }
  53657. }
  53658. }
  53659. }
  53660. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  53661. var particleSystem = scene.particleSystems[particleIndex];
  53662. var emitter = particleSystem.emitter;
  53663. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  53664. continue;
  53665. }
  53666. if (currentRenderList.indexOf(emitter) >= 0) {
  53667. this._renderingManager.dispatchParticles(particleSystem);
  53668. }
  53669. }
  53670. if (this.isCube) {
  53671. for (var face = 0; face < 6; face++) {
  53672. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  53673. scene.incrementRenderId();
  53674. scene.resetCachedMaterial();
  53675. }
  53676. }
  53677. else {
  53678. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  53679. }
  53680. this.onAfterUnbindObservable.notifyObservers(this);
  53681. if (scene.activeCamera) {
  53682. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  53683. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  53684. }
  53685. engine.setViewport(scene.activeCamera.viewport);
  53686. }
  53687. scene.resetCachedMaterial();
  53688. };
  53689. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  53690. var minimum = 128;
  53691. var x = renderDimension * scale;
  53692. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  53693. // Ensure we don't exceed the render dimension (while staying POT)
  53694. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  53695. };
  53696. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  53697. var _this = this;
  53698. if (!this._texture) {
  53699. return;
  53700. }
  53701. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  53702. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  53703. });
  53704. };
  53705. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  53706. var scene = this.getScene();
  53707. if (!scene) {
  53708. return;
  53709. }
  53710. var engine = scene.getEngine();
  53711. if (!this._texture) {
  53712. return;
  53713. }
  53714. // Bind
  53715. if (this._postProcessManager) {
  53716. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  53717. }
  53718. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  53719. if (this._texture) {
  53720. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  53721. }
  53722. }
  53723. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  53724. // Clear
  53725. if (this.onClearObservable.hasObservers()) {
  53726. this.onClearObservable.notifyObservers(engine);
  53727. }
  53728. else {
  53729. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  53730. }
  53731. if (!this._doNotChangeAspectRatio) {
  53732. scene.updateTransformMatrix(true);
  53733. }
  53734. // Render
  53735. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  53736. if (this._postProcessManager) {
  53737. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  53738. }
  53739. else if (useCameraPostProcess) {
  53740. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  53741. }
  53742. if (!this._doNotChangeAspectRatio) {
  53743. scene.updateTransformMatrix(true);
  53744. }
  53745. // Dump ?
  53746. if (dumpForDebug) {
  53747. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  53748. }
  53749. // Unbind
  53750. if (!this.isCube || faceIndex === 5) {
  53751. if (this.isCube) {
  53752. if (faceIndex === 5) {
  53753. engine.generateMipMapsForCubemap(this._texture);
  53754. }
  53755. }
  53756. this.unbindFrameBuffer(engine, faceIndex);
  53757. }
  53758. else {
  53759. this.onAfterRenderObservable.notifyObservers(faceIndex);
  53760. }
  53761. };
  53762. /**
  53763. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  53764. * This allowed control for front to back rendering or reversly depending of the special needs.
  53765. *
  53766. * @param renderingGroupId The rendering group id corresponding to its index
  53767. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  53768. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  53769. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  53770. */
  53771. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  53772. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  53773. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  53774. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  53775. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  53776. };
  53777. /**
  53778. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  53779. *
  53780. * @param renderingGroupId The rendering group id corresponding to its index
  53781. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  53782. */
  53783. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  53784. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  53785. };
  53786. RenderTargetTexture.prototype.clone = function () {
  53787. var textureSize = this.getSize();
  53788. 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);
  53789. // Base texture
  53790. newTexture.hasAlpha = this.hasAlpha;
  53791. newTexture.level = this.level;
  53792. // RenderTarget Texture
  53793. newTexture.coordinatesMode = this.coordinatesMode;
  53794. if (this.renderList) {
  53795. newTexture.renderList = this.renderList.slice(0);
  53796. }
  53797. return newTexture;
  53798. };
  53799. RenderTargetTexture.prototype.serialize = function () {
  53800. if (!this.name) {
  53801. return null;
  53802. }
  53803. var serializationObject = _super.prototype.serialize.call(this);
  53804. serializationObject.renderTargetSize = this.getRenderSize();
  53805. serializationObject.renderList = [];
  53806. if (this.renderList) {
  53807. for (var index = 0; index < this.renderList.length; index++) {
  53808. serializationObject.renderList.push(this.renderList[index].id);
  53809. }
  53810. }
  53811. return serializationObject;
  53812. };
  53813. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  53814. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  53815. var objBuffer = this.getInternalTexture();
  53816. var scene = this.getScene();
  53817. if (objBuffer && scene) {
  53818. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  53819. }
  53820. };
  53821. RenderTargetTexture.prototype.dispose = function () {
  53822. if (this._postProcessManager) {
  53823. this._postProcessManager.dispose();
  53824. this._postProcessManager = null;
  53825. }
  53826. this.clearPostProcesses(true);
  53827. if (this._resizeObserver) {
  53828. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  53829. this._resizeObserver = null;
  53830. }
  53831. this.renderList = null;
  53832. // Remove from custom render targets
  53833. var scene = this.getScene();
  53834. if (!scene) {
  53835. return;
  53836. }
  53837. var index = scene.customRenderTargets.indexOf(this);
  53838. if (index >= 0) {
  53839. scene.customRenderTargets.splice(index, 1);
  53840. }
  53841. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  53842. var camera = _a[_i];
  53843. index = camera.customRenderTargets.indexOf(this);
  53844. if (index >= 0) {
  53845. camera.customRenderTargets.splice(index, 1);
  53846. }
  53847. }
  53848. _super.prototype.dispose.call(this);
  53849. };
  53850. RenderTargetTexture.prototype._rebuild = function () {
  53851. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  53852. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  53853. }
  53854. if (this._postProcessManager) {
  53855. this._postProcessManager._rebuild();
  53856. }
  53857. };
  53858. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  53859. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  53860. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  53861. return RenderTargetTexture;
  53862. }(BABYLON.Texture));
  53863. BABYLON.RenderTargetTexture = RenderTargetTexture;
  53864. })(BABYLON || (BABYLON = {}));
  53865. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  53866. var BABYLON;
  53867. (function (BABYLON) {
  53868. ;
  53869. var MultiRenderTarget = /** @class */ (function (_super) {
  53870. __extends(MultiRenderTarget, _super);
  53871. function MultiRenderTarget(name, size, count, scene, options) {
  53872. var _this = this;
  53873. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  53874. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  53875. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  53876. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  53877. _this._engine = scene.getEngine();
  53878. if (!_this.isSupported) {
  53879. _this.dispose();
  53880. return;
  53881. }
  53882. var types = [];
  53883. var samplingModes = [];
  53884. for (var i = 0; i < count; i++) {
  53885. if (options && options.types && options.types[i] !== undefined) {
  53886. types.push(options.types[i]);
  53887. }
  53888. else {
  53889. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53890. }
  53891. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  53892. samplingModes.push(options.samplingModes[i]);
  53893. }
  53894. else {
  53895. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53896. }
  53897. }
  53898. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  53899. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  53900. _this._size = size;
  53901. _this._multiRenderTargetOptions = {
  53902. samplingModes: samplingModes,
  53903. generateMipMaps: generateMipMaps,
  53904. generateDepthBuffer: generateDepthBuffer,
  53905. generateStencilBuffer: generateStencilBuffer,
  53906. generateDepthTexture: generateDepthTexture,
  53907. types: types,
  53908. textureCount: count
  53909. };
  53910. _this._createInternalTextures();
  53911. _this._createTextures();
  53912. return _this;
  53913. }
  53914. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  53915. get: function () {
  53916. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  53917. },
  53918. enumerable: true,
  53919. configurable: true
  53920. });
  53921. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  53922. get: function () {
  53923. return this._textures;
  53924. },
  53925. enumerable: true,
  53926. configurable: true
  53927. });
  53928. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  53929. get: function () {
  53930. return this._textures[this._textures.length - 1];
  53931. },
  53932. enumerable: true,
  53933. configurable: true
  53934. });
  53935. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  53936. set: function (wrap) {
  53937. if (this._textures) {
  53938. for (var i = 0; i < this._textures.length; i++) {
  53939. this._textures[i].wrapU = wrap;
  53940. }
  53941. }
  53942. },
  53943. enumerable: true,
  53944. configurable: true
  53945. });
  53946. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  53947. set: function (wrap) {
  53948. if (this._textures) {
  53949. for (var i = 0; i < this._textures.length; i++) {
  53950. this._textures[i].wrapV = wrap;
  53951. }
  53952. }
  53953. },
  53954. enumerable: true,
  53955. configurable: true
  53956. });
  53957. MultiRenderTarget.prototype._rebuild = function () {
  53958. this.releaseInternalTextures();
  53959. this._createInternalTextures();
  53960. for (var i = 0; i < this._internalTextures.length; i++) {
  53961. var texture = this._textures[i];
  53962. texture._texture = this._internalTextures[i];
  53963. }
  53964. // Keeps references to frame buffer and stencil/depth buffer
  53965. this._texture = this._internalTextures[0];
  53966. };
  53967. MultiRenderTarget.prototype._createInternalTextures = function () {
  53968. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  53969. };
  53970. MultiRenderTarget.prototype._createTextures = function () {
  53971. this._textures = [];
  53972. for (var i = 0; i < this._internalTextures.length; i++) {
  53973. var texture = new BABYLON.Texture(null, this.getScene());
  53974. texture._texture = this._internalTextures[i];
  53975. this._textures.push(texture);
  53976. }
  53977. // Keeps references to frame buffer and stencil/depth buffer
  53978. this._texture = this._internalTextures[0];
  53979. };
  53980. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  53981. get: function () {
  53982. return this._samples;
  53983. },
  53984. set: function (value) {
  53985. if (this._samples === value) {
  53986. return;
  53987. }
  53988. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  53989. },
  53990. enumerable: true,
  53991. configurable: true
  53992. });
  53993. MultiRenderTarget.prototype.resize = function (size) {
  53994. this.releaseInternalTextures();
  53995. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  53996. this._createInternalTextures();
  53997. };
  53998. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  53999. var _this = this;
  54000. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  54001. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54002. });
  54003. };
  54004. MultiRenderTarget.prototype.dispose = function () {
  54005. this.releaseInternalTextures();
  54006. _super.prototype.dispose.call(this);
  54007. };
  54008. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  54009. if (!this._internalTextures) {
  54010. return;
  54011. }
  54012. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  54013. if (this._internalTextures[i] !== undefined) {
  54014. this._internalTextures[i].dispose();
  54015. this._internalTextures.splice(i, 1);
  54016. }
  54017. }
  54018. };
  54019. return MultiRenderTarget;
  54020. }(BABYLON.RenderTargetTexture));
  54021. BABYLON.MultiRenderTarget = MultiRenderTarget;
  54022. })(BABYLON || (BABYLON = {}));
  54023. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  54024. var BABYLON;
  54025. (function (BABYLON) {
  54026. var MirrorTexture = /** @class */ (function (_super) {
  54027. __extends(MirrorTexture, _super);
  54028. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  54029. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54031. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54032. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  54033. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  54034. _this._transformMatrix = BABYLON.Matrix.Zero();
  54035. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  54036. _this._adaptiveBlurKernel = 0;
  54037. _this._blurKernelX = 0;
  54038. _this._blurKernelY = 0;
  54039. _this._blurRatio = 1.0;
  54040. _this.ignoreCameraViewport = true;
  54041. _this.onBeforeRenderObservable.add(function () {
  54042. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  54043. _this._savedViewMatrix = scene.getViewMatrix();
  54044. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  54045. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  54046. scene.clipPlane = _this.mirrorPlane;
  54047. scene.getEngine().cullBackFaces = false;
  54048. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  54049. });
  54050. _this.onAfterRenderObservable.add(function () {
  54051. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  54052. scene.getEngine().cullBackFaces = true;
  54053. scene._mirroredCameraPosition = null;
  54054. delete scene.clipPlane;
  54055. });
  54056. return _this;
  54057. }
  54058. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  54059. get: function () {
  54060. return this._blurRatio;
  54061. },
  54062. set: function (value) {
  54063. if (this._blurRatio === value) {
  54064. return;
  54065. }
  54066. this._blurRatio = value;
  54067. this._preparePostProcesses();
  54068. },
  54069. enumerable: true,
  54070. configurable: true
  54071. });
  54072. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  54073. set: function (value) {
  54074. this._adaptiveBlurKernel = value;
  54075. this._autoComputeBlurKernel();
  54076. },
  54077. enumerable: true,
  54078. configurable: true
  54079. });
  54080. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  54081. set: function (value) {
  54082. this.blurKernelX = value;
  54083. this.blurKernelY = value;
  54084. },
  54085. enumerable: true,
  54086. configurable: true
  54087. });
  54088. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  54089. get: function () {
  54090. return this._blurKernelX;
  54091. },
  54092. set: function (value) {
  54093. if (this._blurKernelX === value) {
  54094. return;
  54095. }
  54096. this._blurKernelX = value;
  54097. this._preparePostProcesses();
  54098. },
  54099. enumerable: true,
  54100. configurable: true
  54101. });
  54102. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  54103. get: function () {
  54104. return this._blurKernelY;
  54105. },
  54106. set: function (value) {
  54107. if (this._blurKernelY === value) {
  54108. return;
  54109. }
  54110. this._blurKernelY = value;
  54111. this._preparePostProcesses();
  54112. },
  54113. enumerable: true,
  54114. configurable: true
  54115. });
  54116. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  54117. var engine = this.getScene().getEngine();
  54118. var dw = this.getRenderWidth() / engine.getRenderWidth();
  54119. var dh = this.getRenderHeight() / engine.getRenderHeight();
  54120. this.blurKernelX = this._adaptiveBlurKernel * dw;
  54121. this.blurKernelY = this._adaptiveBlurKernel * dh;
  54122. };
  54123. MirrorTexture.prototype._onRatioRescale = function () {
  54124. if (this._sizeRatio) {
  54125. this.resize(this._initialSizeParameter);
  54126. if (!this._adaptiveBlurKernel) {
  54127. this._preparePostProcesses();
  54128. }
  54129. }
  54130. if (this._adaptiveBlurKernel) {
  54131. this._autoComputeBlurKernel();
  54132. }
  54133. };
  54134. MirrorTexture.prototype._preparePostProcesses = function () {
  54135. this.clearPostProcesses(true);
  54136. if (this._blurKernelX && this._blurKernelY) {
  54137. var engine = this.getScene().getEngine();
  54138. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54139. 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);
  54140. this._blurX.autoClear = false;
  54141. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  54142. this._blurX.outputTexture = this._texture;
  54143. }
  54144. else {
  54145. this._blurX.alwaysForcePOT = true;
  54146. }
  54147. 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);
  54148. this._blurY.autoClear = false;
  54149. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  54150. this.addPostProcess(this._blurX);
  54151. this.addPostProcess(this._blurY);
  54152. }
  54153. else {
  54154. if (this._blurY) {
  54155. this.removePostProcess(this._blurY);
  54156. this._blurY.dispose();
  54157. this._blurY = null;
  54158. }
  54159. if (this._blurX) {
  54160. this.removePostProcess(this._blurX);
  54161. this._blurX.dispose();
  54162. this._blurX = null;
  54163. }
  54164. }
  54165. };
  54166. MirrorTexture.prototype.clone = function () {
  54167. var scene = this.getScene();
  54168. if (!scene) {
  54169. return this;
  54170. }
  54171. var textureSize = this.getSize();
  54172. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  54173. // Base texture
  54174. newTexture.hasAlpha = this.hasAlpha;
  54175. newTexture.level = this.level;
  54176. // Mirror Texture
  54177. newTexture.mirrorPlane = this.mirrorPlane.clone();
  54178. if (this.renderList) {
  54179. newTexture.renderList = this.renderList.slice(0);
  54180. }
  54181. return newTexture;
  54182. };
  54183. MirrorTexture.prototype.serialize = function () {
  54184. if (!this.name) {
  54185. return null;
  54186. }
  54187. var serializationObject = _super.prototype.serialize.call(this);
  54188. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  54189. return serializationObject;
  54190. };
  54191. return MirrorTexture;
  54192. }(BABYLON.RenderTargetTexture));
  54193. BABYLON.MirrorTexture = MirrorTexture;
  54194. })(BABYLON || (BABYLON = {}));
  54195. //# sourceMappingURL=babylon.mirrorTexture.js.map
  54196. var BABYLON;
  54197. (function (BABYLON) {
  54198. /**
  54199. * Creates a refraction texture used by refraction channel of the standard material.
  54200. * @param name the texture name
  54201. * @param size size of the underlying texture
  54202. * @param scene root scene
  54203. */
  54204. var RefractionTexture = /** @class */ (function (_super) {
  54205. __extends(RefractionTexture, _super);
  54206. function RefractionTexture(name, size, scene, generateMipMaps) {
  54207. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  54208. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  54209. _this.depth = 2.0;
  54210. _this.onBeforeRenderObservable.add(function () {
  54211. scene.clipPlane = _this.refractionPlane;
  54212. });
  54213. _this.onAfterRenderObservable.add(function () {
  54214. delete scene.clipPlane;
  54215. });
  54216. return _this;
  54217. }
  54218. RefractionTexture.prototype.clone = function () {
  54219. var scene = this.getScene();
  54220. if (!scene) {
  54221. return this;
  54222. }
  54223. var textureSize = this.getSize();
  54224. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  54225. // Base texture
  54226. newTexture.hasAlpha = this.hasAlpha;
  54227. newTexture.level = this.level;
  54228. // Refraction Texture
  54229. newTexture.refractionPlane = this.refractionPlane.clone();
  54230. if (this.renderList) {
  54231. newTexture.renderList = this.renderList.slice(0);
  54232. }
  54233. newTexture.depth = this.depth;
  54234. return newTexture;
  54235. };
  54236. RefractionTexture.prototype.serialize = function () {
  54237. if (!this.name) {
  54238. return null;
  54239. }
  54240. var serializationObject = _super.prototype.serialize.call(this);
  54241. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  54242. serializationObject.depth = this.depth;
  54243. return serializationObject;
  54244. };
  54245. return RefractionTexture;
  54246. }(BABYLON.RenderTargetTexture));
  54247. BABYLON.RefractionTexture = RefractionTexture;
  54248. })(BABYLON || (BABYLON = {}));
  54249. //# sourceMappingURL=babylon.refractionTexture.js.map
  54250. var BABYLON;
  54251. (function (BABYLON) {
  54252. var DynamicTexture = /** @class */ (function (_super) {
  54253. __extends(DynamicTexture, _super);
  54254. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  54255. if (scene === void 0) { scene = null; }
  54256. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54257. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54258. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  54259. _this.name = name;
  54260. _this._engine = _this.getScene().getEngine();
  54261. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54262. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54263. _this._generateMipMaps = generateMipMaps;
  54264. if (options.getContext) {
  54265. _this._canvas = options;
  54266. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54267. }
  54268. else {
  54269. _this._canvas = document.createElement("canvas");
  54270. if (options.width) {
  54271. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54272. }
  54273. else {
  54274. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  54275. }
  54276. }
  54277. var textureSize = _this.getSize();
  54278. _this._canvas.width = textureSize.width;
  54279. _this._canvas.height = textureSize.height;
  54280. _this._context = _this._canvas.getContext("2d");
  54281. return _this;
  54282. }
  54283. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  54284. get: function () {
  54285. return true;
  54286. },
  54287. enumerable: true,
  54288. configurable: true
  54289. });
  54290. DynamicTexture.prototype._recreate = function (textureSize) {
  54291. this._canvas.width = textureSize.width;
  54292. this._canvas.height = textureSize.height;
  54293. this.releaseInternalTexture();
  54294. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  54295. };
  54296. DynamicTexture.prototype.scale = function (ratio) {
  54297. var textureSize = this.getSize();
  54298. textureSize.width *= ratio;
  54299. textureSize.height *= ratio;
  54300. this._recreate(textureSize);
  54301. };
  54302. DynamicTexture.prototype.scaleTo = function (width, height) {
  54303. var textureSize = this.getSize();
  54304. textureSize.width = width;
  54305. textureSize.height = height;
  54306. this._recreate(textureSize);
  54307. };
  54308. DynamicTexture.prototype.getContext = function () {
  54309. return this._context;
  54310. };
  54311. DynamicTexture.prototype.clear = function () {
  54312. var size = this.getSize();
  54313. this._context.fillRect(0, 0, size.width, size.height);
  54314. };
  54315. DynamicTexture.prototype.update = function (invertY) {
  54316. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  54317. };
  54318. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  54319. if (update === void 0) { update = true; }
  54320. var size = this.getSize();
  54321. if (clearColor) {
  54322. this._context.fillStyle = clearColor;
  54323. this._context.fillRect(0, 0, size.width, size.height);
  54324. }
  54325. this._context.font = font;
  54326. if (x === null || x === undefined) {
  54327. var textSize = this._context.measureText(text);
  54328. x = (size.width - textSize.width) / 2;
  54329. }
  54330. if (y === null || y === undefined) {
  54331. var fontSize = parseInt((font.replace(/\D/g, '')));
  54332. ;
  54333. y = (size.height / 2) + (fontSize / 3.65);
  54334. }
  54335. this._context.fillStyle = color;
  54336. this._context.fillText(text, x, y);
  54337. if (update) {
  54338. this.update(invertY);
  54339. }
  54340. };
  54341. DynamicTexture.prototype.clone = function () {
  54342. var scene = this.getScene();
  54343. if (!scene) {
  54344. return this;
  54345. }
  54346. var textureSize = this.getSize();
  54347. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  54348. // Base texture
  54349. newTexture.hasAlpha = this.hasAlpha;
  54350. newTexture.level = this.level;
  54351. // Dynamic Texture
  54352. newTexture.wrapU = this.wrapU;
  54353. newTexture.wrapV = this.wrapV;
  54354. return newTexture;
  54355. };
  54356. DynamicTexture.prototype._rebuild = function () {
  54357. this.update();
  54358. };
  54359. return DynamicTexture;
  54360. }(BABYLON.Texture));
  54361. BABYLON.DynamicTexture = DynamicTexture;
  54362. })(BABYLON || (BABYLON = {}));
  54363. //# sourceMappingURL=babylon.dynamicTexture.js.map
  54364. var BABYLON;
  54365. (function (BABYLON) {
  54366. var VideoTexture = /** @class */ (function (_super) {
  54367. __extends(VideoTexture, _super);
  54368. /**
  54369. * Creates a video texture.
  54370. * Sample : https://doc.babylonjs.com/how_to/video_texture
  54371. * @param {string | null} name optional name, will detect from video source, if not defined
  54372. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  54373. * @param {BABYLON.Scene} scene is obviously the current scene.
  54374. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  54375. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  54376. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  54377. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  54378. */
  54379. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  54380. if (generateMipMaps === void 0) { generateMipMaps = false; }
  54381. if (invertY === void 0) { invertY = false; }
  54382. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54383. if (settings === void 0) { settings = {
  54384. autoPlay: true,
  54385. loop: true,
  54386. autoUpdateTexture: true,
  54387. }; }
  54388. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54389. _this._createInternalTexture = function () {
  54390. if (_this._texture != null) {
  54391. return;
  54392. }
  54393. if (!_this._engine.needPOTTextures ||
  54394. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  54395. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54396. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54397. }
  54398. else {
  54399. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54400. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54401. _this._generateMipMaps = false;
  54402. }
  54403. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  54404. _this._texture.width;
  54405. _this._updateInternalTexture();
  54406. _this._texture.isReady = true;
  54407. };
  54408. _this.reset = function () {
  54409. if (_this._texture == null) {
  54410. return;
  54411. }
  54412. _this._texture.dispose();
  54413. _this._texture = null;
  54414. };
  54415. _this._updateInternalTexture = function (e) {
  54416. if (_this._texture == null || !_this._texture.isReady) {
  54417. return;
  54418. }
  54419. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  54420. return;
  54421. }
  54422. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  54423. };
  54424. _this._engine = _this.getScene().getEngine();
  54425. _this._generateMipMaps = generateMipMaps;
  54426. _this._samplingMode = samplingMode;
  54427. _this.autoUpdateTexture = settings.autoUpdateTexture;
  54428. _this.name = name || _this._getName(src);
  54429. _this.video = _this._getVideo(src);
  54430. if (settings.autoPlay !== undefined) {
  54431. _this.video.autoplay = settings.autoPlay;
  54432. }
  54433. if (settings.loop !== undefined) {
  54434. _this.video.loop = settings.loop;
  54435. }
  54436. _this.video.addEventListener("canplay", _this._createInternalTexture);
  54437. _this.video.addEventListener("paused", _this._updateInternalTexture);
  54438. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  54439. _this.video.addEventListener("emptied", _this.reset);
  54440. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  54441. _this._createInternalTexture();
  54442. }
  54443. return _this;
  54444. }
  54445. VideoTexture.prototype._getName = function (src) {
  54446. if (src instanceof HTMLVideoElement) {
  54447. return src.currentSrc;
  54448. }
  54449. if (typeof src === "object") {
  54450. return src.toString();
  54451. }
  54452. return src;
  54453. };
  54454. ;
  54455. VideoTexture.prototype._getVideo = function (src) {
  54456. if (src instanceof HTMLVideoElement) {
  54457. return src;
  54458. }
  54459. var video = document.createElement("video");
  54460. if (typeof src === "string") {
  54461. video.src = src;
  54462. }
  54463. else {
  54464. src.forEach(function (url) {
  54465. var source = document.createElement("source");
  54466. source.src = url;
  54467. video.appendChild(source);
  54468. });
  54469. }
  54470. return video;
  54471. };
  54472. ;
  54473. /**
  54474. * Internal method to initiate `update`.
  54475. */
  54476. VideoTexture.prototype._rebuild = function () {
  54477. this.update();
  54478. };
  54479. /**
  54480. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  54481. */
  54482. VideoTexture.prototype.update = function () {
  54483. if (!this.autoUpdateTexture) {
  54484. // Expecting user to call `updateTexture` manually
  54485. return;
  54486. }
  54487. this.updateTexture(true);
  54488. };
  54489. /**
  54490. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  54491. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  54492. */
  54493. VideoTexture.prototype.updateTexture = function (isVisible) {
  54494. if (!isVisible) {
  54495. return;
  54496. }
  54497. if (this.video.paused) {
  54498. return;
  54499. }
  54500. this._updateInternalTexture();
  54501. };
  54502. /**
  54503. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  54504. * @param url New url.
  54505. */
  54506. VideoTexture.prototype.updateURL = function (url) {
  54507. this.video.src = url;
  54508. };
  54509. VideoTexture.prototype.dispose = function () {
  54510. _super.prototype.dispose.call(this);
  54511. this.video.removeEventListener("canplay", this._createInternalTexture);
  54512. this.video.removeEventListener("paused", this._updateInternalTexture);
  54513. this.video.removeEventListener("seeked", this._updateInternalTexture);
  54514. this.video.removeEventListener("emptied", this.reset);
  54515. };
  54516. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  54517. var video = document.createElement("video");
  54518. var constraintsDeviceId;
  54519. if (constraints && constraints.deviceId) {
  54520. constraintsDeviceId = {
  54521. exact: constraints.deviceId,
  54522. };
  54523. }
  54524. navigator.getUserMedia =
  54525. navigator.getUserMedia ||
  54526. navigator.webkitGetUserMedia ||
  54527. navigator.mozGetUserMedia ||
  54528. navigator.msGetUserMedia;
  54529. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  54530. if (navigator.getUserMedia) {
  54531. navigator.getUserMedia({
  54532. video: {
  54533. deviceId: constraintsDeviceId,
  54534. width: {
  54535. min: (constraints && constraints.minWidth) || 256,
  54536. max: (constraints && constraints.maxWidth) || 640,
  54537. },
  54538. height: {
  54539. min: (constraints && constraints.minHeight) || 256,
  54540. max: (constraints && constraints.maxHeight) || 480,
  54541. },
  54542. },
  54543. }, function (stream) {
  54544. if (video.mozSrcObject !== undefined) {
  54545. // hack for Firefox < 19
  54546. video.mozSrcObject = stream;
  54547. }
  54548. else {
  54549. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  54550. }
  54551. video.play();
  54552. if (onReady) {
  54553. onReady(new VideoTexture("video", video, scene, true, true));
  54554. }
  54555. }, function (e) {
  54556. BABYLON.Tools.Error(e.name);
  54557. });
  54558. }
  54559. };
  54560. return VideoTexture;
  54561. }(BABYLON.Texture));
  54562. BABYLON.VideoTexture = VideoTexture;
  54563. })(BABYLON || (BABYLON = {}));
  54564. //# sourceMappingURL=babylon.videoTexture.js.map
  54565. var BABYLON;
  54566. (function (BABYLON) {
  54567. var RawTexture = /** @class */ (function (_super) {
  54568. __extends(RawTexture, _super);
  54569. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  54570. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54571. if (invertY === void 0) { invertY = false; }
  54572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54573. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54574. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54575. _this.format = format;
  54576. _this._engine = scene.getEngine();
  54577. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  54578. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54579. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54580. return _this;
  54581. }
  54582. RawTexture.prototype.update = function (data) {
  54583. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  54584. };
  54585. // Statics
  54586. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54587. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54588. if (invertY === void 0) { invertY = false; }
  54589. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54590. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  54591. };
  54592. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54593. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54594. if (invertY === void 0) { invertY = false; }
  54595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54596. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54597. };
  54598. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54599. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54600. if (invertY === void 0) { invertY = false; }
  54601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54602. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54603. };
  54604. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  54605. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54606. if (invertY === void 0) { invertY = false; }
  54607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54608. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54609. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  54610. };
  54611. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  54612. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54613. if (invertY === void 0) { invertY = false; }
  54614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54615. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54616. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  54617. };
  54618. return RawTexture;
  54619. }(BABYLON.Texture));
  54620. BABYLON.RawTexture = RawTexture;
  54621. })(BABYLON || (BABYLON = {}));
  54622. //# sourceMappingURL=babylon.rawTexture.js.map
  54623. var BABYLON;
  54624. (function (BABYLON) {
  54625. var PostProcess = /** @class */ (function () {
  54626. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  54627. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  54628. if (defines === void 0) { defines = null; }
  54629. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54630. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  54631. if (blockCompilation === void 0) { blockCompilation = false; }
  54632. this.name = name;
  54633. this.width = -1;
  54634. this.height = -1;
  54635. this.autoClear = true;
  54636. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  54637. this.animations = new Array();
  54638. /*
  54639. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  54640. Can only be used on a single postprocess or on the last one of a chain.
  54641. */
  54642. this.enablePixelPerfectMode = false;
  54643. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  54644. this.alwaysForcePOT = false;
  54645. this.samples = 1;
  54646. this.adaptScaleToCurrentViewport = false;
  54647. this._reusable = false;
  54648. this._textures = new BABYLON.SmartArray(2);
  54649. this._currentRenderTextureInd = 0;
  54650. this._scaleRatio = new BABYLON.Vector2(1, 1);
  54651. this._texelSize = BABYLON.Vector2.Zero();
  54652. // Events
  54653. /**
  54654. * An event triggered when the postprocess is activated.
  54655. * @type {BABYLON.Observable}
  54656. */
  54657. this.onActivateObservable = new BABYLON.Observable();
  54658. /**
  54659. * An event triggered when the postprocess changes its size.
  54660. * @type {BABYLON.Observable}
  54661. */
  54662. this.onSizeChangedObservable = new BABYLON.Observable();
  54663. /**
  54664. * An event triggered when the postprocess applies its effect.
  54665. * @type {BABYLON.Observable}
  54666. */
  54667. this.onApplyObservable = new BABYLON.Observable();
  54668. /**
  54669. * An event triggered before rendering the postprocess
  54670. * @type {BABYLON.Observable}
  54671. */
  54672. this.onBeforeRenderObservable = new BABYLON.Observable();
  54673. /**
  54674. * An event triggered after rendering the postprocess
  54675. * @type {BABYLON.Observable}
  54676. */
  54677. this.onAfterRenderObservable = new BABYLON.Observable();
  54678. if (camera != null) {
  54679. this._camera = camera;
  54680. this._scene = camera.getScene();
  54681. camera.attachPostProcess(this);
  54682. this._engine = this._scene.getEngine();
  54683. this._scene.postProcesses.push(this);
  54684. }
  54685. else if (engine) {
  54686. this._engine = engine;
  54687. this._engine.postProcesses.push(this);
  54688. }
  54689. this._options = options;
  54690. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  54691. this._reusable = reusable || false;
  54692. this._textureType = textureType;
  54693. this._samplers = samplers || [];
  54694. this._samplers.push("textureSampler");
  54695. this._fragmentUrl = fragmentUrl;
  54696. this._vertexUrl = vertexUrl;
  54697. this._parameters = parameters || [];
  54698. this._parameters.push("scale");
  54699. this._indexParameters = indexParameters;
  54700. if (!blockCompilation) {
  54701. this.updateEffect(defines);
  54702. }
  54703. }
  54704. Object.defineProperty(PostProcess.prototype, "onActivate", {
  54705. set: function (callback) {
  54706. if (this._onActivateObserver) {
  54707. this.onActivateObservable.remove(this._onActivateObserver);
  54708. }
  54709. if (callback) {
  54710. this._onActivateObserver = this.onActivateObservable.add(callback);
  54711. }
  54712. },
  54713. enumerable: true,
  54714. configurable: true
  54715. });
  54716. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  54717. set: function (callback) {
  54718. if (this._onSizeChangedObserver) {
  54719. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  54720. }
  54721. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  54722. },
  54723. enumerable: true,
  54724. configurable: true
  54725. });
  54726. Object.defineProperty(PostProcess.prototype, "onApply", {
  54727. set: function (callback) {
  54728. if (this._onApplyObserver) {
  54729. this.onApplyObservable.remove(this._onApplyObserver);
  54730. }
  54731. this._onApplyObserver = this.onApplyObservable.add(callback);
  54732. },
  54733. enumerable: true,
  54734. configurable: true
  54735. });
  54736. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  54737. set: function (callback) {
  54738. if (this._onBeforeRenderObserver) {
  54739. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54740. }
  54741. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54742. },
  54743. enumerable: true,
  54744. configurable: true
  54745. });
  54746. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  54747. set: function (callback) {
  54748. if (this._onAfterRenderObserver) {
  54749. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54750. }
  54751. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54752. },
  54753. enumerable: true,
  54754. configurable: true
  54755. });
  54756. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  54757. get: function () {
  54758. return this._textures.data[this._currentRenderTextureInd];
  54759. },
  54760. set: function (value) {
  54761. this._forcedOutputTexture = value;
  54762. },
  54763. enumerable: true,
  54764. configurable: true
  54765. });
  54766. PostProcess.prototype.getCamera = function () {
  54767. return this._camera;
  54768. };
  54769. Object.defineProperty(PostProcess.prototype, "texelSize", {
  54770. get: function () {
  54771. if (this._shareOutputWithPostProcess) {
  54772. return this._shareOutputWithPostProcess.texelSize;
  54773. }
  54774. if (this._forcedOutputTexture) {
  54775. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  54776. }
  54777. return this._texelSize;
  54778. },
  54779. enumerable: true,
  54780. configurable: true
  54781. });
  54782. PostProcess.prototype.getEngine = function () {
  54783. return this._engine;
  54784. };
  54785. PostProcess.prototype.getEffect = function () {
  54786. return this._effect;
  54787. };
  54788. PostProcess.prototype.shareOutputWith = function (postProcess) {
  54789. this._disposeTextures();
  54790. this._shareOutputWithPostProcess = postProcess;
  54791. return this;
  54792. };
  54793. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  54794. if (defines === void 0) { defines = null; }
  54795. if (uniforms === void 0) { uniforms = null; }
  54796. if (samplers === void 0) { samplers = null; }
  54797. 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);
  54798. };
  54799. PostProcess.prototype.isReusable = function () {
  54800. return this._reusable;
  54801. };
  54802. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  54803. PostProcess.prototype.markTextureDirty = function () {
  54804. this.width = -1;
  54805. };
  54806. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  54807. var _this = this;
  54808. if (sourceTexture === void 0) { sourceTexture = null; }
  54809. camera = camera || this._camera;
  54810. var scene = camera.getScene();
  54811. var engine = scene.getEngine();
  54812. var maxSize = engine.getCaps().maxTextureSize;
  54813. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  54814. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  54815. var desiredWidth = (this._options.width || requiredWidth);
  54816. var desiredHeight = this._options.height || requiredHeight;
  54817. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  54818. if (this.adaptScaleToCurrentViewport) {
  54819. var currentViewport = engine.currentViewport;
  54820. if (currentViewport) {
  54821. desiredWidth *= currentViewport.width;
  54822. desiredHeight *= currentViewport.height;
  54823. }
  54824. }
  54825. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  54826. if (!this._options.width) {
  54827. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  54828. }
  54829. if (!this._options.height) {
  54830. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  54831. }
  54832. }
  54833. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  54834. if (this._textures.length > 0) {
  54835. for (var i = 0; i < this._textures.length; i++) {
  54836. this._engine._releaseTexture(this._textures.data[i]);
  54837. }
  54838. this._textures.reset();
  54839. }
  54840. this.width = desiredWidth;
  54841. this.height = desiredHeight;
  54842. var textureSize = { width: this.width, height: this.height };
  54843. var textureOptions = {
  54844. generateMipMaps: false,
  54845. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  54846. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  54847. samplingMode: this.renderTargetSamplingMode,
  54848. type: this._textureType
  54849. };
  54850. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  54851. if (this._reusable) {
  54852. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  54853. }
  54854. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  54855. this.onSizeChangedObservable.notifyObservers(this);
  54856. }
  54857. this._textures.forEach(function (texture) {
  54858. if (texture.samples !== _this.samples) {
  54859. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  54860. }
  54861. });
  54862. }
  54863. var target;
  54864. if (this._shareOutputWithPostProcess) {
  54865. target = this._shareOutputWithPostProcess.outputTexture;
  54866. }
  54867. else if (this._forcedOutputTexture) {
  54868. target = this._forcedOutputTexture;
  54869. this.width = this._forcedOutputTexture.width;
  54870. this.height = this._forcedOutputTexture.height;
  54871. }
  54872. else {
  54873. target = this.outputTexture;
  54874. }
  54875. if (this.enablePixelPerfectMode) {
  54876. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  54877. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  54878. }
  54879. else {
  54880. this._scaleRatio.copyFromFloats(1, 1);
  54881. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  54882. }
  54883. this.onActivateObservable.notifyObservers(camera);
  54884. // Clear
  54885. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  54886. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  54887. }
  54888. if (this._reusable) {
  54889. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  54890. }
  54891. };
  54892. Object.defineProperty(PostProcess.prototype, "isSupported", {
  54893. get: function () {
  54894. return this._effect.isSupported;
  54895. },
  54896. enumerable: true,
  54897. configurable: true
  54898. });
  54899. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  54900. get: function () {
  54901. if (this._shareOutputWithPostProcess) {
  54902. return this._shareOutputWithPostProcess.aspectRatio;
  54903. }
  54904. if (this._forcedOutputTexture) {
  54905. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  54906. }
  54907. return this.width / this.height;
  54908. },
  54909. enumerable: true,
  54910. configurable: true
  54911. });
  54912. /**
  54913. * Get a value indicating if the post-process is ready to be used
  54914. * @returns true if the post-process is ready (shader is compiled)
  54915. */
  54916. PostProcess.prototype.isReady = function () {
  54917. return this._effect && this._effect.isReady();
  54918. };
  54919. PostProcess.prototype.apply = function () {
  54920. // Check
  54921. if (!this._effect || !this._effect.isReady())
  54922. return null;
  54923. // States
  54924. this._engine.enableEffect(this._effect);
  54925. this._engine.setState(false);
  54926. this._engine.setDepthBuffer(false);
  54927. this._engine.setDepthWrite(false);
  54928. // Alpha
  54929. this._engine.setAlphaMode(this.alphaMode);
  54930. if (this.alphaConstants) {
  54931. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  54932. }
  54933. // Texture
  54934. var source;
  54935. if (this._shareOutputWithPostProcess) {
  54936. source = this._shareOutputWithPostProcess.outputTexture;
  54937. }
  54938. else if (this._forcedOutputTexture) {
  54939. source = this._forcedOutputTexture;
  54940. }
  54941. else {
  54942. source = this.outputTexture;
  54943. }
  54944. this._effect._bindTexture("textureSampler", source);
  54945. // Parameters
  54946. this._effect.setVector2("scale", this._scaleRatio);
  54947. this.onApplyObservable.notifyObservers(this._effect);
  54948. return this._effect;
  54949. };
  54950. PostProcess.prototype._disposeTextures = function () {
  54951. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  54952. return;
  54953. }
  54954. if (this._textures.length > 0) {
  54955. for (var i = 0; i < this._textures.length; i++) {
  54956. this._engine._releaseTexture(this._textures.data[i]);
  54957. }
  54958. }
  54959. this._textures.dispose();
  54960. };
  54961. PostProcess.prototype.dispose = function (camera) {
  54962. camera = camera || this._camera;
  54963. this._disposeTextures();
  54964. if (this._scene) {
  54965. var index_1 = this._scene.postProcesses.indexOf(this);
  54966. if (index_1 !== -1) {
  54967. this._scene.postProcesses.splice(index_1, 1);
  54968. }
  54969. }
  54970. else {
  54971. var index_2 = this._engine.postProcesses.indexOf(this);
  54972. if (index_2 !== -1) {
  54973. this._engine.postProcesses.splice(index_2, 1);
  54974. }
  54975. }
  54976. if (!camera) {
  54977. return;
  54978. }
  54979. camera.detachPostProcess(this);
  54980. var index = camera._postProcesses.indexOf(this);
  54981. if (index === 0 && camera._postProcesses.length > 0) {
  54982. this._camera._postProcesses[0].markTextureDirty();
  54983. }
  54984. this.onActivateObservable.clear();
  54985. this.onAfterRenderObservable.clear();
  54986. this.onApplyObservable.clear();
  54987. this.onBeforeRenderObservable.clear();
  54988. this.onSizeChangedObservable.clear();
  54989. };
  54990. return PostProcess;
  54991. }());
  54992. BABYLON.PostProcess = PostProcess;
  54993. })(BABYLON || (BABYLON = {}));
  54994. //# sourceMappingURL=babylon.postProcess.js.map
  54995. var BABYLON;
  54996. (function (BABYLON) {
  54997. var PassPostProcess = /** @class */ (function (_super) {
  54998. __extends(PassPostProcess, _super);
  54999. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55000. if (camera === void 0) { camera = null; }
  55001. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55002. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  55003. }
  55004. return PassPostProcess;
  55005. }(BABYLON.PostProcess));
  55006. BABYLON.PassPostProcess = PassPostProcess;
  55007. })(BABYLON || (BABYLON = {}));
  55008. //# sourceMappingURL=babylon.passPostProcess.js.map
  55009. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55010. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55011. s = arguments[i];
  55012. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55013. t[p] = s[p];
  55014. }
  55015. return t;
  55016. };
  55017. var BABYLON;
  55018. (function (BABYLON) {
  55019. var ShadowGenerator = /** @class */ (function () {
  55020. /**
  55021. * Creates a ShadowGenerator object.
  55022. * A ShadowGenerator is the required tool to use the shadows.
  55023. * Each light casting shadows needs to use its own ShadowGenerator.
  55024. * Required parameters :
  55025. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  55026. * - `light`: the light object generating the shadows.
  55027. * - `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.
  55028. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  55029. */
  55030. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  55031. // Members
  55032. this._bias = 0.00005;
  55033. this._blurBoxOffset = 1;
  55034. this._blurScale = 2;
  55035. this._blurKernel = 1;
  55036. this._useKernelBlur = false;
  55037. this._filter = ShadowGenerator.FILTER_NONE;
  55038. this._darkness = 0;
  55039. this._transparencyShadow = false;
  55040. /**
  55041. * Controls the extent to which the shadows fade out at the edge of the frustum
  55042. * Used only by directionals and spots
  55043. */
  55044. this.frustumEdgeFalloff = 0;
  55045. this.forceBackFacesOnly = false;
  55046. this._lightDirection = BABYLON.Vector3.Zero();
  55047. this._viewMatrix = BABYLON.Matrix.Zero();
  55048. this._projectionMatrix = BABYLON.Matrix.Zero();
  55049. this._transformMatrix = BABYLON.Matrix.Zero();
  55050. this._currentFaceIndex = 0;
  55051. this._currentFaceIndexCache = 0;
  55052. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  55053. this._mapSize = mapSize;
  55054. this._light = light;
  55055. this._scene = light.getScene();
  55056. light._shadowGenerator = this;
  55057. // Texture type fallback from float to int if not supported.
  55058. var caps = this._scene.getEngine().getCaps();
  55059. if (!useFullFloatFirst) {
  55060. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55061. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55062. }
  55063. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55064. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55065. }
  55066. else {
  55067. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55068. }
  55069. }
  55070. else {
  55071. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55072. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55073. }
  55074. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55075. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55076. }
  55077. else {
  55078. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55079. }
  55080. }
  55081. this._initializeGenerator();
  55082. }
  55083. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  55084. // Static
  55085. get: function () {
  55086. return ShadowGenerator._FILTER_NONE;
  55087. },
  55088. enumerable: true,
  55089. configurable: true
  55090. });
  55091. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  55092. get: function () {
  55093. return ShadowGenerator._FILTER_POISSONSAMPLING;
  55094. },
  55095. enumerable: true,
  55096. configurable: true
  55097. });
  55098. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  55099. get: function () {
  55100. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  55101. },
  55102. enumerable: true,
  55103. configurable: true
  55104. });
  55105. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  55106. get: function () {
  55107. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  55108. },
  55109. enumerable: true,
  55110. configurable: true
  55111. });
  55112. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  55113. get: function () {
  55114. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55115. },
  55116. enumerable: true,
  55117. configurable: true
  55118. });
  55119. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  55120. get: function () {
  55121. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55122. },
  55123. enumerable: true,
  55124. configurable: true
  55125. });
  55126. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  55127. get: function () {
  55128. return this._bias;
  55129. },
  55130. set: function (bias) {
  55131. this._bias = bias;
  55132. },
  55133. enumerable: true,
  55134. configurable: true
  55135. });
  55136. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  55137. get: function () {
  55138. return this._blurBoxOffset;
  55139. },
  55140. set: function (value) {
  55141. if (this._blurBoxOffset === value) {
  55142. return;
  55143. }
  55144. this._blurBoxOffset = value;
  55145. this._disposeBlurPostProcesses();
  55146. },
  55147. enumerable: true,
  55148. configurable: true
  55149. });
  55150. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  55151. get: function () {
  55152. return this._blurScale;
  55153. },
  55154. set: function (value) {
  55155. if (this._blurScale === value) {
  55156. return;
  55157. }
  55158. this._blurScale = value;
  55159. this._disposeBlurPostProcesses();
  55160. },
  55161. enumerable: true,
  55162. configurable: true
  55163. });
  55164. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  55165. get: function () {
  55166. return this._blurKernel;
  55167. },
  55168. set: function (value) {
  55169. if (this._blurKernel === value) {
  55170. return;
  55171. }
  55172. this._blurKernel = value;
  55173. this._disposeBlurPostProcesses();
  55174. },
  55175. enumerable: true,
  55176. configurable: true
  55177. });
  55178. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  55179. get: function () {
  55180. return this._useKernelBlur;
  55181. },
  55182. set: function (value) {
  55183. if (this._useKernelBlur === value) {
  55184. return;
  55185. }
  55186. this._useKernelBlur = value;
  55187. this._disposeBlurPostProcesses();
  55188. },
  55189. enumerable: true,
  55190. configurable: true
  55191. });
  55192. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  55193. get: function () {
  55194. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  55195. },
  55196. set: function (value) {
  55197. this._depthScale = value;
  55198. },
  55199. enumerable: true,
  55200. configurable: true
  55201. });
  55202. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  55203. get: function () {
  55204. return this._filter;
  55205. },
  55206. set: function (value) {
  55207. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  55208. if (this._light.needCube()) {
  55209. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55210. this.useExponentialShadowMap = true;
  55211. return;
  55212. }
  55213. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55214. this.useCloseExponentialShadowMap = true;
  55215. return;
  55216. }
  55217. }
  55218. if (this._filter === value) {
  55219. return;
  55220. }
  55221. this._filter = value;
  55222. this._disposeBlurPostProcesses();
  55223. this._applyFilterValues();
  55224. this._light._markMeshesAsLightDirty();
  55225. },
  55226. enumerable: true,
  55227. configurable: true
  55228. });
  55229. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  55230. get: function () {
  55231. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  55232. },
  55233. set: function (value) {
  55234. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  55235. return;
  55236. }
  55237. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  55238. },
  55239. enumerable: true,
  55240. configurable: true
  55241. });
  55242. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  55243. get: function () {
  55244. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55245. return this.useExponentialShadowMap;
  55246. },
  55247. set: function (value) {
  55248. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55249. this.useExponentialShadowMap = value;
  55250. },
  55251. enumerable: true,
  55252. configurable: true
  55253. });
  55254. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  55255. get: function () {
  55256. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55257. return this.useBlurExponentialShadowMap;
  55258. },
  55259. set: function (value) {
  55260. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55261. this.useBlurExponentialShadowMap = value;
  55262. },
  55263. enumerable: true,
  55264. configurable: true
  55265. });
  55266. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  55267. get: function () {
  55268. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  55269. },
  55270. set: function (value) {
  55271. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  55272. return;
  55273. }
  55274. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55275. },
  55276. enumerable: true,
  55277. configurable: true
  55278. });
  55279. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  55280. get: function () {
  55281. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  55282. },
  55283. set: function (value) {
  55284. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55285. return;
  55286. }
  55287. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55288. },
  55289. enumerable: true,
  55290. configurable: true
  55291. });
  55292. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  55293. get: function () {
  55294. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55295. },
  55296. set: function (value) {
  55297. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  55298. return;
  55299. }
  55300. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55301. },
  55302. enumerable: true,
  55303. configurable: true
  55304. });
  55305. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  55306. get: function () {
  55307. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55308. },
  55309. set: function (value) {
  55310. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55311. return;
  55312. }
  55313. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55314. },
  55315. enumerable: true,
  55316. configurable: true
  55317. });
  55318. /**
  55319. * Returns the darkness value (float).
  55320. */
  55321. ShadowGenerator.prototype.getDarkness = function () {
  55322. return this._darkness;
  55323. };
  55324. /**
  55325. * Sets the ShadowGenerator darkness value (float <= 1.0).
  55326. * Returns the ShadowGenerator.
  55327. */
  55328. ShadowGenerator.prototype.setDarkness = function (darkness) {
  55329. if (darkness >= 1.0)
  55330. this._darkness = 1.0;
  55331. else if (darkness <= 0.0)
  55332. this._darkness = 0.0;
  55333. else
  55334. this._darkness = darkness;
  55335. return this;
  55336. };
  55337. /**
  55338. * Sets the ability to have transparent shadow (boolean).
  55339. * Returns the ShadowGenerator.
  55340. */
  55341. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  55342. this._transparencyShadow = hasShadow;
  55343. return this;
  55344. };
  55345. /**
  55346. * Returns a RenderTargetTexture object : the shadow map texture.
  55347. */
  55348. ShadowGenerator.prototype.getShadowMap = function () {
  55349. return this._shadowMap;
  55350. };
  55351. /**
  55352. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  55353. */
  55354. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  55355. if (this._shadowMap2) {
  55356. return this._shadowMap2;
  55357. }
  55358. return this._shadowMap;
  55359. };
  55360. /**
  55361. * Helper function to add a mesh and its descendants to the list of shadow casters
  55362. * @param mesh Mesh to add
  55363. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  55364. */
  55365. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  55366. if (includeDescendants === void 0) { includeDescendants = true; }
  55367. if (!this._shadowMap) {
  55368. return this;
  55369. }
  55370. if (!this._shadowMap.renderList) {
  55371. this._shadowMap.renderList = [];
  55372. }
  55373. this._shadowMap.renderList.push(mesh);
  55374. if (includeDescendants) {
  55375. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  55376. }
  55377. return this;
  55378. var _a;
  55379. };
  55380. /**
  55381. * Helper function to remove a mesh and its descendants from the list of shadow casters
  55382. * @param mesh Mesh to remove
  55383. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  55384. */
  55385. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  55386. if (includeDescendants === void 0) { includeDescendants = true; }
  55387. if (!this._shadowMap || !this._shadowMap.renderList) {
  55388. return this;
  55389. }
  55390. var index = this._shadowMap.renderList.indexOf(mesh);
  55391. if (index !== -1) {
  55392. this._shadowMap.renderList.splice(index, 1);
  55393. }
  55394. if (includeDescendants) {
  55395. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  55396. var child = _a[_i];
  55397. this.removeShadowCaster(child);
  55398. }
  55399. }
  55400. return this;
  55401. };
  55402. /**
  55403. * Returns the associated light object.
  55404. */
  55405. ShadowGenerator.prototype.getLight = function () {
  55406. return this._light;
  55407. };
  55408. ShadowGenerator.prototype._initializeGenerator = function () {
  55409. this._light._markMeshesAsLightDirty();
  55410. this._initializeShadowMap();
  55411. };
  55412. ShadowGenerator.prototype._initializeShadowMap = function () {
  55413. var _this = this;
  55414. // Render target
  55415. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  55416. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55417. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55418. this._shadowMap.anisotropicFilteringLevel = 1;
  55419. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55420. this._shadowMap.renderParticles = false;
  55421. this._shadowMap.ignoreCameraViewport = true;
  55422. // Record Face Index before render.
  55423. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  55424. _this._currentFaceIndex = faceIndex;
  55425. });
  55426. // Custom render function.
  55427. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  55428. // Blur if required afer render.
  55429. this._shadowMap.onAfterUnbindObservable.add(function () {
  55430. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  55431. return;
  55432. }
  55433. var shadowMap = _this.getShadowMapForRendering();
  55434. if (shadowMap) {
  55435. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  55436. }
  55437. });
  55438. // Clear according to the chosen filter.
  55439. this._shadowMap.onClearObservable.add(function (engine) {
  55440. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  55441. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  55442. }
  55443. else {
  55444. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55445. }
  55446. });
  55447. };
  55448. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  55449. var _this = this;
  55450. var engine = this._scene.getEngine();
  55451. var targetSize = this._mapSize / this.blurScale;
  55452. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  55453. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  55454. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55455. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55456. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55457. }
  55458. if (this.useKernelBlur) {
  55459. 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);
  55460. this._kernelBlurXPostprocess.width = targetSize;
  55461. this._kernelBlurXPostprocess.height = targetSize;
  55462. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  55463. effect.setTexture("textureSampler", _this._shadowMap);
  55464. });
  55465. 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);
  55466. this._kernelBlurXPostprocess.autoClear = false;
  55467. this._kernelBlurYPostprocess.autoClear = false;
  55468. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55469. this._kernelBlurXPostprocess.packedFloat = true;
  55470. this._kernelBlurYPostprocess.packedFloat = true;
  55471. }
  55472. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  55473. }
  55474. else {
  55475. 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);
  55476. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  55477. effect.setFloat2("screenSize", targetSize, targetSize);
  55478. effect.setTexture("textureSampler", _this._shadowMap);
  55479. });
  55480. this._boxBlurPostprocess.autoClear = false;
  55481. this._blurPostProcesses = [this._boxBlurPostprocess];
  55482. }
  55483. };
  55484. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55485. var index;
  55486. var engine = this._scene.getEngine();
  55487. if (depthOnlySubMeshes.length) {
  55488. engine.setColorWrite(false);
  55489. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55490. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  55491. }
  55492. engine.setColorWrite(true);
  55493. }
  55494. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55495. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  55496. }
  55497. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55498. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  55499. }
  55500. if (this._transparencyShadow) {
  55501. for (index = 0; index < transparentSubMeshes.length; index++) {
  55502. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  55503. }
  55504. }
  55505. };
  55506. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  55507. var _this = this;
  55508. var mesh = subMesh.getRenderingMesh();
  55509. var scene = this._scene;
  55510. var engine = scene.getEngine();
  55511. var material = subMesh.getMaterial();
  55512. if (!material) {
  55513. return;
  55514. }
  55515. // Culling
  55516. engine.setState(material.backFaceCulling);
  55517. // Managing instances
  55518. var batch = mesh._getInstancesRenderList(subMesh._id);
  55519. if (batch.mustReturn) {
  55520. return;
  55521. }
  55522. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  55523. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  55524. engine.enableEffect(this._effect);
  55525. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  55526. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  55527. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  55528. this._effect.setVector3("lightPosition", this.getLight().position);
  55529. if (scene.activeCamera) {
  55530. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  55531. }
  55532. // Alpha test
  55533. if (material && material.needAlphaTesting()) {
  55534. var alphaTexture = material.getAlphaTestTexture();
  55535. if (alphaTexture) {
  55536. this._effect.setTexture("diffuseSampler", alphaTexture);
  55537. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  55538. }
  55539. }
  55540. // Bones
  55541. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55542. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  55543. }
  55544. if (this.forceBackFacesOnly) {
  55545. engine.setState(true, 0, false, true);
  55546. }
  55547. // Draw
  55548. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55549. if (this.forceBackFacesOnly) {
  55550. engine.setState(true, 0, false, false);
  55551. }
  55552. }
  55553. else {
  55554. // Need to reset refresh rate of the shadowMap
  55555. if (this._shadowMap) {
  55556. this._shadowMap.resetRefreshCounter();
  55557. }
  55558. }
  55559. };
  55560. ShadowGenerator.prototype._applyFilterValues = function () {
  55561. if (!this._shadowMap) {
  55562. return;
  55563. }
  55564. if (this.filter === ShadowGenerator.FILTER_NONE) {
  55565. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  55566. }
  55567. else {
  55568. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55569. }
  55570. };
  55571. /**
  55572. * Force shader compilation including textures ready check
  55573. */
  55574. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  55575. var _this = this;
  55576. var localOptions = __assign({ useInstances: false }, options);
  55577. var shadowMap = this.getShadowMap();
  55578. if (!shadowMap) {
  55579. if (onCompiled) {
  55580. onCompiled(this);
  55581. }
  55582. return;
  55583. }
  55584. var renderList = shadowMap.renderList;
  55585. if (!renderList) {
  55586. if (onCompiled) {
  55587. onCompiled(this);
  55588. }
  55589. return;
  55590. }
  55591. var subMeshes = new Array();
  55592. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  55593. var mesh = renderList_1[_i];
  55594. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  55595. }
  55596. if (subMeshes.length === 0) {
  55597. if (onCompiled) {
  55598. onCompiled(this);
  55599. }
  55600. return;
  55601. }
  55602. var currentIndex = 0;
  55603. var checkReady = function () {
  55604. if (!_this._scene || !_this._scene.getEngine()) {
  55605. return;
  55606. }
  55607. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  55608. currentIndex++;
  55609. if (currentIndex >= subMeshes.length) {
  55610. if (onCompiled) {
  55611. onCompiled(_this);
  55612. }
  55613. return;
  55614. }
  55615. }
  55616. setTimeout(checkReady, 16);
  55617. };
  55618. checkReady();
  55619. };
  55620. /**
  55621. * Boolean : true when the ShadowGenerator is finally computed.
  55622. */
  55623. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  55624. var defines = [];
  55625. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55626. defines.push("#define FLOAT");
  55627. }
  55628. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  55629. defines.push("#define ESM");
  55630. }
  55631. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55632. var mesh = subMesh.getMesh();
  55633. var material = subMesh.getMaterial();
  55634. // Alpha test
  55635. if (material && material.needAlphaTesting()) {
  55636. var alphaTexture = material.getAlphaTestTexture();
  55637. if (alphaTexture) {
  55638. defines.push("#define ALPHATEST");
  55639. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55640. attribs.push(BABYLON.VertexBuffer.UVKind);
  55641. defines.push("#define UV1");
  55642. }
  55643. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55644. if (alphaTexture.coordinatesIndex === 1) {
  55645. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55646. defines.push("#define UV2");
  55647. }
  55648. }
  55649. }
  55650. }
  55651. // Bones
  55652. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55653. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55654. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55655. if (mesh.numBoneInfluencers > 4) {
  55656. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55657. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55658. }
  55659. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55660. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55661. }
  55662. else {
  55663. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55664. }
  55665. // Instances
  55666. if (useInstances) {
  55667. defines.push("#define INSTANCES");
  55668. attribs.push("world0");
  55669. attribs.push("world1");
  55670. attribs.push("world2");
  55671. attribs.push("world3");
  55672. }
  55673. // Get correct effect
  55674. var join = defines.join("\n");
  55675. if (this._cachedDefines !== join) {
  55676. this._cachedDefines = join;
  55677. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  55678. }
  55679. if (!this._effect.isReady()) {
  55680. return false;
  55681. }
  55682. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  55683. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  55684. this._initializeBlurRTTAndPostProcesses();
  55685. }
  55686. }
  55687. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  55688. return false;
  55689. }
  55690. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  55691. return false;
  55692. }
  55693. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  55694. return false;
  55695. }
  55696. return true;
  55697. };
  55698. /**
  55699. * This creates the defines related to the standard BJS materials.
  55700. */
  55701. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  55702. var scene = this._scene;
  55703. var light = this._light;
  55704. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  55705. return;
  55706. }
  55707. defines["SHADOW" + lightIndex] = true;
  55708. if (this.usePoissonSampling) {
  55709. defines["SHADOWPCF" + lightIndex] = true;
  55710. }
  55711. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  55712. defines["SHADOWESM" + lightIndex] = true;
  55713. }
  55714. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  55715. defines["SHADOWCLOSEESM" + lightIndex] = true;
  55716. }
  55717. if (light.needCube()) {
  55718. defines["SHADOWCUBE" + lightIndex] = true;
  55719. }
  55720. };
  55721. /**
  55722. * This binds shadow lights related to the standard BJS materials.
  55723. * It implies the unifroms available on the materials are the standard BJS ones.
  55724. */
  55725. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  55726. var light = this._light;
  55727. var scene = this._scene;
  55728. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  55729. return;
  55730. }
  55731. var camera = scene.activeCamera;
  55732. if (!camera) {
  55733. return;
  55734. }
  55735. var shadowMap = this.getShadowMap();
  55736. if (!shadowMap) {
  55737. return;
  55738. }
  55739. if (!light.needCube()) {
  55740. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  55741. }
  55742. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  55743. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  55744. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  55745. };
  55746. // Methods
  55747. /**
  55748. * Returns a Matrix object : the updated transformation matrix.
  55749. */
  55750. ShadowGenerator.prototype.getTransformMatrix = function () {
  55751. var scene = this._scene;
  55752. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  55753. return this._transformMatrix;
  55754. }
  55755. this._currentRenderID = scene.getRenderId();
  55756. this._currentFaceIndexCache = this._currentFaceIndex;
  55757. var lightPosition = this._light.position;
  55758. if (this._light.computeTransformedInformation()) {
  55759. lightPosition = this._light.transformedPosition;
  55760. }
  55761. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  55762. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  55763. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  55764. }
  55765. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  55766. this._cachedPosition = lightPosition.clone();
  55767. this._cachedDirection = this._lightDirection.clone();
  55768. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  55769. var shadowMap = this.getShadowMap();
  55770. if (shadowMap) {
  55771. var renderList = shadowMap.renderList;
  55772. if (renderList) {
  55773. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  55774. }
  55775. }
  55776. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  55777. }
  55778. return this._transformMatrix;
  55779. };
  55780. ShadowGenerator.prototype.recreateShadowMap = function () {
  55781. var shadowMap = this._shadowMap;
  55782. if (!shadowMap) {
  55783. return;
  55784. }
  55785. // Track render list.
  55786. var renderList = shadowMap.renderList;
  55787. // Clean up existing data.
  55788. this._disposeRTTandPostProcesses();
  55789. // Reinitializes.
  55790. this._initializeGenerator();
  55791. // Reaffect the filter to ensure a correct fallback if necessary.
  55792. this.filter = this.filter;
  55793. // Reaffect the filter.
  55794. this._applyFilterValues();
  55795. // Reaffect Render List.
  55796. this._shadowMap.renderList = renderList;
  55797. };
  55798. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  55799. if (this._shadowMap2) {
  55800. this._shadowMap2.dispose();
  55801. this._shadowMap2 = null;
  55802. }
  55803. if (this._boxBlurPostprocess) {
  55804. this._boxBlurPostprocess.dispose();
  55805. this._boxBlurPostprocess = null;
  55806. }
  55807. if (this._kernelBlurXPostprocess) {
  55808. this._kernelBlurXPostprocess.dispose();
  55809. this._kernelBlurXPostprocess = null;
  55810. }
  55811. if (this._kernelBlurYPostprocess) {
  55812. this._kernelBlurYPostprocess.dispose();
  55813. this._kernelBlurYPostprocess = null;
  55814. }
  55815. this._blurPostProcesses = [];
  55816. };
  55817. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  55818. if (this._shadowMap) {
  55819. this._shadowMap.dispose();
  55820. this._shadowMap = null;
  55821. }
  55822. this._disposeBlurPostProcesses();
  55823. };
  55824. /**
  55825. * Disposes the ShadowGenerator.
  55826. * Returns nothing.
  55827. */
  55828. ShadowGenerator.prototype.dispose = function () {
  55829. this._disposeRTTandPostProcesses();
  55830. if (this._light) {
  55831. this._light._shadowGenerator = null;
  55832. this._light._markMeshesAsLightDirty();
  55833. }
  55834. };
  55835. /**
  55836. * Serializes the ShadowGenerator and returns a serializationObject.
  55837. */
  55838. ShadowGenerator.prototype.serialize = function () {
  55839. var serializationObject = {};
  55840. var shadowMap = this.getShadowMap();
  55841. if (!shadowMap) {
  55842. return serializationObject;
  55843. }
  55844. serializationObject.lightId = this._light.id;
  55845. serializationObject.mapSize = shadowMap.getRenderSize();
  55846. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  55847. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  55848. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  55849. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  55850. serializationObject.usePoissonSampling = this.usePoissonSampling;
  55851. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  55852. serializationObject.depthScale = this.depthScale;
  55853. serializationObject.darkness = this.getDarkness();
  55854. serializationObject.blurBoxOffset = this.blurBoxOffset;
  55855. serializationObject.blurKernel = this.blurKernel;
  55856. serializationObject.blurScale = this.blurScale;
  55857. serializationObject.useKernelBlur = this.useKernelBlur;
  55858. serializationObject.transparencyShadow = this._transparencyShadow;
  55859. serializationObject.renderList = [];
  55860. if (shadowMap.renderList) {
  55861. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  55862. var mesh = shadowMap.renderList[meshIndex];
  55863. serializationObject.renderList.push(mesh.id);
  55864. }
  55865. }
  55866. return serializationObject;
  55867. };
  55868. /**
  55869. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  55870. */
  55871. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  55872. //casting to point light, as light is missing the position attr and typescript complains.
  55873. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  55874. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  55875. var shadowMap = shadowGenerator.getShadowMap();
  55876. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  55877. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  55878. meshes.forEach(function (mesh) {
  55879. if (!shadowMap) {
  55880. return;
  55881. }
  55882. if (!shadowMap.renderList) {
  55883. shadowMap.renderList = [];
  55884. }
  55885. shadowMap.renderList.push(mesh);
  55886. });
  55887. }
  55888. if (parsedShadowGenerator.usePoissonSampling) {
  55889. shadowGenerator.usePoissonSampling = true;
  55890. }
  55891. else if (parsedShadowGenerator.useExponentialShadowMap) {
  55892. shadowGenerator.useExponentialShadowMap = true;
  55893. }
  55894. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  55895. shadowGenerator.useBlurExponentialShadowMap = true;
  55896. }
  55897. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  55898. shadowGenerator.useCloseExponentialShadowMap = true;
  55899. }
  55900. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  55901. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  55902. }
  55903. else if (parsedShadowGenerator.useVarianceShadowMap) {
  55904. shadowGenerator.useExponentialShadowMap = true;
  55905. }
  55906. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  55907. shadowGenerator.useBlurExponentialShadowMap = true;
  55908. }
  55909. if (parsedShadowGenerator.depthScale) {
  55910. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  55911. }
  55912. if (parsedShadowGenerator.blurScale) {
  55913. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  55914. }
  55915. if (parsedShadowGenerator.blurBoxOffset) {
  55916. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  55917. }
  55918. if (parsedShadowGenerator.useKernelBlur) {
  55919. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  55920. }
  55921. if (parsedShadowGenerator.blurKernel) {
  55922. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  55923. }
  55924. if (parsedShadowGenerator.bias !== undefined) {
  55925. shadowGenerator.bias = parsedShadowGenerator.bias;
  55926. }
  55927. if (parsedShadowGenerator.darkness) {
  55928. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  55929. }
  55930. if (parsedShadowGenerator.transparencyShadow) {
  55931. shadowGenerator.setTransparencyShadow(true);
  55932. }
  55933. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  55934. return shadowGenerator;
  55935. };
  55936. ShadowGenerator._FILTER_NONE = 0;
  55937. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  55938. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  55939. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  55940. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  55941. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  55942. return ShadowGenerator;
  55943. }());
  55944. BABYLON.ShadowGenerator = ShadowGenerator;
  55945. })(BABYLON || (BABYLON = {}));
  55946. //# sourceMappingURL=babylon.shadowGenerator.js.map
  55947. var BABYLON;
  55948. (function (BABYLON) {
  55949. var DefaultLoadingScreen = /** @class */ (function () {
  55950. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  55951. if (_loadingText === void 0) { _loadingText = ""; }
  55952. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  55953. var _this = this;
  55954. this._renderingCanvas = _renderingCanvas;
  55955. this._loadingText = _loadingText;
  55956. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  55957. // Resize
  55958. this._resizeLoadingUI = function () {
  55959. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  55960. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  55961. if (!_this._loadingDiv) {
  55962. return;
  55963. }
  55964. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  55965. _this._loadingDiv.style.left = canvasRect.left + "px";
  55966. _this._loadingDiv.style.top = canvasRect.top + "px";
  55967. _this._loadingDiv.style.width = canvasRect.width + "px";
  55968. _this._loadingDiv.style.height = canvasRect.height + "px";
  55969. };
  55970. }
  55971. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  55972. if (this._loadingDiv) {
  55973. // Do not add a loading screen if there is already one
  55974. return;
  55975. }
  55976. this._loadingDiv = document.createElement("div");
  55977. this._loadingDiv.id = "babylonjsLoadingDiv";
  55978. this._loadingDiv.style.opacity = "0";
  55979. this._loadingDiv.style.transition = "opacity 1.5s ease";
  55980. this._loadingDiv.style.pointerEvents = "none";
  55981. // Loading text
  55982. this._loadingTextDiv = document.createElement("div");
  55983. this._loadingTextDiv.style.position = "absolute";
  55984. this._loadingTextDiv.style.left = "0";
  55985. this._loadingTextDiv.style.top = "50%";
  55986. this._loadingTextDiv.style.marginTop = "80px";
  55987. this._loadingTextDiv.style.width = "100%";
  55988. this._loadingTextDiv.style.height = "20px";
  55989. this._loadingTextDiv.style.fontFamily = "Arial";
  55990. this._loadingTextDiv.style.fontSize = "14px";
  55991. this._loadingTextDiv.style.color = "white";
  55992. this._loadingTextDiv.style.textAlign = "center";
  55993. this._loadingTextDiv.innerHTML = "Loading";
  55994. this._loadingDiv.appendChild(this._loadingTextDiv);
  55995. //set the predefined text
  55996. this._loadingTextDiv.innerHTML = this._loadingText;
  55997. // Generating keyframes
  55998. var style = document.createElement('style');
  55999. style.type = 'text/css';
  56000. 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 }";
  56001. style.innerHTML = keyFrames;
  56002. document.getElementsByTagName('head')[0].appendChild(style);
  56003. // Loading img
  56004. var imgBack = new Image();
  56005. 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";
  56006. imgBack.style.position = "absolute";
  56007. imgBack.style.left = "50%";
  56008. imgBack.style.top = "50%";
  56009. imgBack.style.marginLeft = "-60px";
  56010. imgBack.style.marginTop = "-60px";
  56011. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  56012. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  56013. imgBack.style.transformOrigin = "50% 50%";
  56014. imgBack.style.webkitTransformOrigin = "50% 50%";
  56015. this._loadingDiv.appendChild(imgBack);
  56016. this._resizeLoadingUI();
  56017. window.addEventListener("resize", this._resizeLoadingUI);
  56018. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56019. document.body.appendChild(this._loadingDiv);
  56020. this._loadingDiv.style.opacity = "1";
  56021. };
  56022. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  56023. var _this = this;
  56024. if (!this._loadingDiv) {
  56025. return;
  56026. }
  56027. var onTransitionEnd = function () {
  56028. if (!_this._loadingDiv) {
  56029. return;
  56030. }
  56031. document.body.removeChild(_this._loadingDiv);
  56032. window.removeEventListener("resize", _this._resizeLoadingUI);
  56033. _this._loadingDiv = null;
  56034. };
  56035. this._loadingDiv.style.opacity = "0";
  56036. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  56037. };
  56038. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  56039. set: function (text) {
  56040. this._loadingText = text;
  56041. if (this._loadingTextDiv) {
  56042. this._loadingTextDiv.innerHTML = this._loadingText;
  56043. }
  56044. },
  56045. enumerable: true,
  56046. configurable: true
  56047. });
  56048. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  56049. get: function () {
  56050. return this._loadingDivBackgroundColor;
  56051. },
  56052. set: function (color) {
  56053. this._loadingDivBackgroundColor = color;
  56054. if (!this._loadingDiv) {
  56055. return;
  56056. }
  56057. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56058. },
  56059. enumerable: true,
  56060. configurable: true
  56061. });
  56062. return DefaultLoadingScreen;
  56063. }());
  56064. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  56065. })(BABYLON || (BABYLON = {}));
  56066. //# sourceMappingURL=babylon.loadingScreen.js.map
  56067. var BABYLON;
  56068. (function (BABYLON) {
  56069. var SceneLoaderProgressEvent = /** @class */ (function () {
  56070. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  56071. this.lengthComputable = lengthComputable;
  56072. this.loaded = loaded;
  56073. this.total = total;
  56074. }
  56075. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  56076. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  56077. };
  56078. return SceneLoaderProgressEvent;
  56079. }());
  56080. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  56081. var SceneLoader = /** @class */ (function () {
  56082. function SceneLoader() {
  56083. }
  56084. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  56085. get: function () {
  56086. return 0;
  56087. },
  56088. enumerable: true,
  56089. configurable: true
  56090. });
  56091. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  56092. get: function () {
  56093. return 1;
  56094. },
  56095. enumerable: true,
  56096. configurable: true
  56097. });
  56098. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  56099. get: function () {
  56100. return 2;
  56101. },
  56102. enumerable: true,
  56103. configurable: true
  56104. });
  56105. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  56106. get: function () {
  56107. return 3;
  56108. },
  56109. enumerable: true,
  56110. configurable: true
  56111. });
  56112. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  56113. get: function () {
  56114. return SceneLoader._ForceFullSceneLoadingForIncremental;
  56115. },
  56116. set: function (value) {
  56117. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  56118. },
  56119. enumerable: true,
  56120. configurable: true
  56121. });
  56122. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  56123. get: function () {
  56124. return SceneLoader._ShowLoadingScreen;
  56125. },
  56126. set: function (value) {
  56127. SceneLoader._ShowLoadingScreen = value;
  56128. },
  56129. enumerable: true,
  56130. configurable: true
  56131. });
  56132. Object.defineProperty(SceneLoader, "loggingLevel", {
  56133. get: function () {
  56134. return SceneLoader._loggingLevel;
  56135. },
  56136. set: function (value) {
  56137. SceneLoader._loggingLevel = value;
  56138. },
  56139. enumerable: true,
  56140. configurable: true
  56141. });
  56142. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  56143. get: function () {
  56144. return SceneLoader._CleanBoneMatrixWeights;
  56145. },
  56146. set: function (value) {
  56147. SceneLoader._CleanBoneMatrixWeights = value;
  56148. },
  56149. enumerable: true,
  56150. configurable: true
  56151. });
  56152. SceneLoader._getDefaultPlugin = function () {
  56153. return SceneLoader._registeredPlugins[".babylon"];
  56154. };
  56155. SceneLoader._getPluginForExtension = function (extension) {
  56156. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  56157. if (registeredPlugin) {
  56158. return registeredPlugin;
  56159. }
  56160. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  56161. return SceneLoader._getDefaultPlugin();
  56162. };
  56163. SceneLoader._getPluginForDirectLoad = function (data) {
  56164. for (var extension in SceneLoader._registeredPlugins) {
  56165. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  56166. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  56167. return SceneLoader._registeredPlugins[extension];
  56168. }
  56169. }
  56170. return SceneLoader._getDefaultPlugin();
  56171. };
  56172. SceneLoader._getPluginForFilename = function (sceneFilename) {
  56173. if (sceneFilename.name) {
  56174. sceneFilename = sceneFilename.name;
  56175. }
  56176. var queryStringPosition = sceneFilename.indexOf("?");
  56177. if (queryStringPosition !== -1) {
  56178. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  56179. }
  56180. var dotPosition = sceneFilename.lastIndexOf(".");
  56181. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  56182. return SceneLoader._getPluginForExtension(extension);
  56183. };
  56184. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  56185. SceneLoader._getDirectLoad = function (sceneFilename) {
  56186. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  56187. return sceneFilename.substr(5);
  56188. }
  56189. return null;
  56190. };
  56191. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  56192. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  56193. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  56194. var plugin;
  56195. if (registeredPlugin.plugin.createPlugin) {
  56196. plugin = registeredPlugin.plugin.createPlugin();
  56197. }
  56198. else {
  56199. plugin = registeredPlugin.plugin;
  56200. }
  56201. var useArrayBuffer = registeredPlugin.isBinary;
  56202. var database;
  56203. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  56204. var dataCallback = function (data, responseURL) {
  56205. if (scene.isDisposed) {
  56206. onError("Scene has been disposed");
  56207. return;
  56208. }
  56209. scene.database = database;
  56210. onSuccess(plugin, data, responseURL);
  56211. };
  56212. var request = null;
  56213. var pluginDisposed = false;
  56214. var onDisposeObservable = plugin.onDisposeObservable;
  56215. if (onDisposeObservable) {
  56216. onDisposeObservable.add(function () {
  56217. pluginDisposed = true;
  56218. if (request) {
  56219. request.abort();
  56220. request = null;
  56221. }
  56222. onDispose();
  56223. });
  56224. }
  56225. var manifestChecked = function () {
  56226. if (pluginDisposed) {
  56227. return;
  56228. }
  56229. var url = rootUrl + sceneFilename;
  56230. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  56231. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  56232. } : undefined, database, useArrayBuffer, function (request, exception) {
  56233. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  56234. });
  56235. };
  56236. if (directLoad) {
  56237. dataCallback(directLoad);
  56238. return plugin;
  56239. }
  56240. if (rootUrl.indexOf("file:") === -1) {
  56241. if (scene.getEngine().enableOfflineSupport) {
  56242. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  56243. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  56244. }
  56245. else {
  56246. manifestChecked();
  56247. }
  56248. }
  56249. else {
  56250. var fileOrString = sceneFilename;
  56251. if (fileOrString.name) {
  56252. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  56253. }
  56254. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  56255. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  56256. }
  56257. else {
  56258. onError("Unable to find file named " + sceneFilename);
  56259. }
  56260. }
  56261. return plugin;
  56262. };
  56263. // Public functions
  56264. SceneLoader.GetPluginForExtension = function (extension) {
  56265. return SceneLoader._getPluginForExtension(extension).plugin;
  56266. };
  56267. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  56268. return !!SceneLoader._registeredPlugins[extension];
  56269. };
  56270. SceneLoader.RegisterPlugin = function (plugin) {
  56271. if (typeof plugin.extensions === "string") {
  56272. var extension = plugin.extensions;
  56273. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56274. plugin: plugin,
  56275. isBinary: false
  56276. };
  56277. }
  56278. else {
  56279. var extensions = plugin.extensions;
  56280. Object.keys(extensions).forEach(function (extension) {
  56281. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56282. plugin: plugin,
  56283. isBinary: extensions[extension].isBinary
  56284. };
  56285. });
  56286. }
  56287. };
  56288. /**
  56289. * Import meshes into a scene
  56290. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  56291. * @param rootUrl a string that defines the root url for scene and resources
  56292. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56293. * @param scene the instance of BABYLON.Scene to append to
  56294. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  56295. * @param onProgress a callback with a progress event for each file being loaded
  56296. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56297. */
  56298. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56299. if (onSuccess === void 0) { onSuccess = null; }
  56300. if (onProgress === void 0) { onProgress = null; }
  56301. if (onError === void 0) { onError = null; }
  56302. if (pluginExtension === void 0) { pluginExtension = null; }
  56303. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56304. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56305. return null;
  56306. }
  56307. var loadingToken = {};
  56308. scene._addPendingData(loadingToken);
  56309. var disposeHandler = function () {
  56310. scene._removePendingData(loadingToken);
  56311. };
  56312. var errorHandler = function (message, exception) {
  56313. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  56314. if (onError) {
  56315. onError(scene, errorMessage, exception);
  56316. }
  56317. else {
  56318. BABYLON.Tools.Error(errorMessage);
  56319. // should the exception be thrown?
  56320. }
  56321. disposeHandler();
  56322. };
  56323. var progressHandler = onProgress ? function (event) {
  56324. try {
  56325. onProgress(event);
  56326. }
  56327. catch (e) {
  56328. errorHandler("Error in onProgress callback", e);
  56329. }
  56330. } : undefined;
  56331. var successHandler = function (meshes, particleSystems, skeletons) {
  56332. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  56333. if (onSuccess) {
  56334. try {
  56335. onSuccess(meshes, particleSystems, skeletons);
  56336. }
  56337. catch (e) {
  56338. errorHandler("Error in onSuccess callback", e);
  56339. }
  56340. }
  56341. scene._removePendingData(loadingToken);
  56342. };
  56343. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56344. if (plugin.rewriteRootURL) {
  56345. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  56346. }
  56347. if (plugin.importMesh) {
  56348. var syncedPlugin = plugin;
  56349. var meshes = new Array();
  56350. var particleSystems = new Array();
  56351. var skeletons = new Array();
  56352. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  56353. return;
  56354. }
  56355. scene.loadingPluginName = plugin.name;
  56356. successHandler(meshes, particleSystems, skeletons);
  56357. }
  56358. else {
  56359. var asyncedPlugin = plugin;
  56360. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  56361. scene.loadingPluginName = plugin.name;
  56362. successHandler(meshes, particleSystems, skeletons);
  56363. }, progressHandler, errorHandler);
  56364. }
  56365. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56366. };
  56367. /**
  56368. * Load a scene
  56369. * @param rootUrl a string that defines the root url for scene and resources
  56370. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56371. * @param engine is the instance of BABYLON.Engine to use to create the scene
  56372. * @param onSuccess a callback with the scene when import succeeds
  56373. * @param onProgress a callback with a progress event for each file being loaded
  56374. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56375. */
  56376. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  56377. if (onSuccess === void 0) { onSuccess = null; }
  56378. if (onProgress === void 0) { onProgress = null; }
  56379. if (onError === void 0) { onError = null; }
  56380. if (pluginExtension === void 0) { pluginExtension = null; }
  56381. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  56382. };
  56383. /**
  56384. * Append a scene
  56385. * @param rootUrl a string that defines the root url for scene and resources
  56386. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56387. * @param scene is the instance of BABYLON.Scene to append to
  56388. * @param onSuccess a callback with the scene when import succeeds
  56389. * @param onProgress a callback with a progress event for each file being loaded
  56390. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56391. */
  56392. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56393. if (onSuccess === void 0) { onSuccess = null; }
  56394. if (onProgress === void 0) { onProgress = null; }
  56395. if (onError === void 0) { onError = null; }
  56396. if (pluginExtension === void 0) { pluginExtension = null; }
  56397. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56398. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56399. return null;
  56400. }
  56401. if (SceneLoader.ShowLoadingScreen) {
  56402. scene.getEngine().displayLoadingUI();
  56403. }
  56404. var loadingToken = {};
  56405. scene._addPendingData(loadingToken);
  56406. var disposeHandler = function () {
  56407. scene._removePendingData(loadingToken);
  56408. scene.getEngine().hideLoadingUI();
  56409. };
  56410. var errorHandler = function (message, exception) {
  56411. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56412. if (onError) {
  56413. onError(scene, errorMessage, exception);
  56414. }
  56415. else {
  56416. BABYLON.Tools.Error(errorMessage);
  56417. // should the exception be thrown?
  56418. }
  56419. disposeHandler();
  56420. };
  56421. var progressHandler = onProgress ? function (event) {
  56422. try {
  56423. onProgress(event);
  56424. }
  56425. catch (e) {
  56426. errorHandler("Error in onProgress callback", e);
  56427. }
  56428. } : undefined;
  56429. var successHandler = function () {
  56430. if (onSuccess) {
  56431. try {
  56432. onSuccess(scene);
  56433. }
  56434. catch (e) {
  56435. errorHandler("Error in onSuccess callback", e);
  56436. }
  56437. }
  56438. scene._removePendingData(loadingToken);
  56439. };
  56440. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56441. if (plugin.load) {
  56442. var syncedPlugin = plugin;
  56443. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  56444. return;
  56445. }
  56446. scene.loadingPluginName = plugin.name;
  56447. successHandler();
  56448. }
  56449. else {
  56450. var asyncedPlugin = plugin;
  56451. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  56452. scene.loadingPluginName = plugin.name;
  56453. successHandler();
  56454. }, progressHandler, errorHandler);
  56455. }
  56456. if (SceneLoader.ShowLoadingScreen) {
  56457. scene.executeWhenReady(function () {
  56458. scene.getEngine().hideLoadingUI();
  56459. });
  56460. }
  56461. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56462. };
  56463. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56464. if (onSuccess === void 0) { onSuccess = null; }
  56465. if (onProgress === void 0) { onProgress = null; }
  56466. if (onError === void 0) { onError = null; }
  56467. if (pluginExtension === void 0) { pluginExtension = null; }
  56468. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56469. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56470. return null;
  56471. }
  56472. var loadingToken = {};
  56473. scene._addPendingData(loadingToken);
  56474. var disposeHandler = function () {
  56475. scene._removePendingData(loadingToken);
  56476. };
  56477. var errorHandler = function (message, exception) {
  56478. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56479. if (onError) {
  56480. onError(scene, errorMessage, exception);
  56481. }
  56482. else {
  56483. BABYLON.Tools.Error(errorMessage);
  56484. // should the exception be thrown?
  56485. }
  56486. disposeHandler();
  56487. };
  56488. var progressHandler = onProgress ? function (event) {
  56489. try {
  56490. onProgress(event);
  56491. }
  56492. catch (e) {
  56493. errorHandler("Error in onProgress callback", e);
  56494. }
  56495. } : undefined;
  56496. var successHandler = function (assets) {
  56497. if (onSuccess) {
  56498. try {
  56499. onSuccess(assets);
  56500. }
  56501. catch (e) {
  56502. errorHandler("Error in onSuccess callback", e);
  56503. }
  56504. }
  56505. scene._removePendingData(loadingToken);
  56506. };
  56507. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56508. if (plugin.loadAssets) {
  56509. var syncedPlugin = plugin;
  56510. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  56511. if (!assetContainer) {
  56512. return;
  56513. }
  56514. scene.loadingPluginName = plugin.name;
  56515. successHandler(assetContainer);
  56516. }
  56517. else if (plugin.loadAssetsAsync) {
  56518. var asyncedPlugin = plugin;
  56519. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  56520. if (assetContainer) {
  56521. scene.loadingPluginName = plugin.name;
  56522. successHandler(assetContainer);
  56523. }
  56524. }, progressHandler, errorHandler);
  56525. }
  56526. else {
  56527. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  56528. }
  56529. if (SceneLoader.ShowLoadingScreen) {
  56530. scene.executeWhenReady(function () {
  56531. scene.getEngine().hideLoadingUI();
  56532. });
  56533. }
  56534. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56535. };
  56536. // Flags
  56537. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  56538. SceneLoader._ShowLoadingScreen = true;
  56539. SceneLoader._CleanBoneMatrixWeights = false;
  56540. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  56541. // Members
  56542. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  56543. SceneLoader._registeredPlugins = {};
  56544. return SceneLoader;
  56545. }());
  56546. BABYLON.SceneLoader = SceneLoader;
  56547. ;
  56548. })(BABYLON || (BABYLON = {}));
  56549. //# sourceMappingURL=babylon.sceneLoader.js.map
  56550. var BABYLON;
  56551. (function (BABYLON) {
  56552. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  56553. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56554. var parsedMaterial = parsedData.materials[index];
  56555. if (parsedMaterial.id === id) {
  56556. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56557. }
  56558. }
  56559. return null;
  56560. };
  56561. var isDescendantOf = function (mesh, names, hierarchyIds) {
  56562. for (var i in names) {
  56563. if (mesh.name === names[i]) {
  56564. hierarchyIds.push(mesh.id);
  56565. return true;
  56566. }
  56567. }
  56568. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  56569. hierarchyIds.push(mesh.id);
  56570. return true;
  56571. }
  56572. return false;
  56573. };
  56574. var logOperation = function (operation, producer) {
  56575. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  56576. };
  56577. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  56578. if (addToScene === void 0) { addToScene = false; }
  56579. var container = new BABYLON.AssetContainer(scene);
  56580. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56581. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56582. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56583. // and avoid problems with multiple concurrent .babylon loads.
  56584. var log = "importScene has failed JSON parse";
  56585. try {
  56586. var parsedData = JSON.parse(data);
  56587. log = "";
  56588. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  56589. var index;
  56590. var cache;
  56591. // Lights
  56592. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  56593. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  56594. var parsedLight = parsedData.lights[index];
  56595. var light = BABYLON.Light.Parse(parsedLight, scene);
  56596. if (light) {
  56597. container.lights.push(light);
  56598. log += (index === 0 ? "\n\tLights:" : "");
  56599. log += "\n\t\t" + light.toString(fullDetails);
  56600. }
  56601. }
  56602. }
  56603. // Animations
  56604. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  56605. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  56606. var parsedAnimation = parsedData.animations[index];
  56607. var animation = BABYLON.Animation.Parse(parsedAnimation);
  56608. scene.animations.push(animation);
  56609. container.animations.push(animation);
  56610. log += (index === 0 ? "\n\tAnimations:" : "");
  56611. log += "\n\t\t" + animation.toString(fullDetails);
  56612. }
  56613. }
  56614. // Materials
  56615. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  56616. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56617. var parsedMaterial = parsedData.materials[index];
  56618. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56619. container.materials.push(mat);
  56620. log += (index === 0 ? "\n\tMaterials:" : "");
  56621. log += "\n\t\t" + mat.toString(fullDetails);
  56622. }
  56623. }
  56624. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  56625. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  56626. var parsedMultiMaterial = parsedData.multiMaterials[index];
  56627. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  56628. container.multiMaterials.push(mmat);
  56629. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  56630. log += "\n\t\t" + mmat.toString(fullDetails);
  56631. }
  56632. }
  56633. // Morph targets
  56634. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  56635. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  56636. var managerData = _a[_i];
  56637. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  56638. }
  56639. }
  56640. // Skeletons
  56641. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  56642. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  56643. var parsedSkeleton = parsedData.skeletons[index];
  56644. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  56645. container.skeletons.push(skeleton);
  56646. log += (index === 0 ? "\n\tSkeletons:" : "");
  56647. log += "\n\t\t" + skeleton.toString(fullDetails);
  56648. }
  56649. }
  56650. // Geometries
  56651. var geometries = parsedData.geometries;
  56652. if (geometries !== undefined && geometries !== null) {
  56653. var addedGeometry = new Array();
  56654. // Boxes
  56655. var boxes = geometries.boxes;
  56656. if (boxes !== undefined && boxes !== null) {
  56657. for (index = 0, cache = boxes.length; index < cache; index++) {
  56658. var parsedBox = boxes[index];
  56659. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  56660. }
  56661. }
  56662. // Spheres
  56663. var spheres = geometries.spheres;
  56664. if (spheres !== undefined && spheres !== null) {
  56665. for (index = 0, cache = spheres.length; index < cache; index++) {
  56666. var parsedSphere = spheres[index];
  56667. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  56668. }
  56669. }
  56670. // Cylinders
  56671. var cylinders = geometries.cylinders;
  56672. if (cylinders !== undefined && cylinders !== null) {
  56673. for (index = 0, cache = cylinders.length; index < cache; index++) {
  56674. var parsedCylinder = cylinders[index];
  56675. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  56676. }
  56677. }
  56678. // Toruses
  56679. var toruses = geometries.toruses;
  56680. if (toruses !== undefined && toruses !== null) {
  56681. for (index = 0, cache = toruses.length; index < cache; index++) {
  56682. var parsedTorus = toruses[index];
  56683. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  56684. }
  56685. }
  56686. // Grounds
  56687. var grounds = geometries.grounds;
  56688. if (grounds !== undefined && grounds !== null) {
  56689. for (index = 0, cache = grounds.length; index < cache; index++) {
  56690. var parsedGround = grounds[index];
  56691. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  56692. }
  56693. }
  56694. // Planes
  56695. var planes = geometries.planes;
  56696. if (planes !== undefined && planes !== null) {
  56697. for (index = 0, cache = planes.length; index < cache; index++) {
  56698. var parsedPlane = planes[index];
  56699. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  56700. }
  56701. }
  56702. // TorusKnots
  56703. var torusKnots = geometries.torusKnots;
  56704. if (torusKnots !== undefined && torusKnots !== null) {
  56705. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  56706. var parsedTorusKnot = torusKnots[index];
  56707. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  56708. }
  56709. }
  56710. // VertexData
  56711. var vertexData = geometries.vertexData;
  56712. if (vertexData !== undefined && vertexData !== null) {
  56713. for (index = 0, cache = vertexData.length; index < cache; index++) {
  56714. var parsedVertexData = vertexData[index];
  56715. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  56716. }
  56717. }
  56718. addedGeometry.forEach(function (g) {
  56719. if (g) {
  56720. container.geometries.push(g);
  56721. }
  56722. });
  56723. }
  56724. // Transform nodes
  56725. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  56726. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  56727. var parsedTransformNode = parsedData.transformNodes[index];
  56728. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  56729. container.transformNodes.push(node);
  56730. }
  56731. }
  56732. // Meshes
  56733. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  56734. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  56735. var parsedMesh = parsedData.meshes[index];
  56736. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  56737. container.meshes.push(mesh);
  56738. log += (index === 0 ? "\n\tMeshes:" : "");
  56739. log += "\n\t\t" + mesh.toString(fullDetails);
  56740. }
  56741. }
  56742. // Cameras
  56743. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  56744. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  56745. var parsedCamera = parsedData.cameras[index];
  56746. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  56747. container.cameras.push(camera);
  56748. log += (index === 0 ? "\n\tCameras:" : "");
  56749. log += "\n\t\t" + camera.toString(fullDetails);
  56750. }
  56751. }
  56752. // Browsing all the graph to connect the dots
  56753. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  56754. var camera = scene.cameras[index];
  56755. if (camera._waitingParentId) {
  56756. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  56757. camera._waitingParentId = null;
  56758. }
  56759. }
  56760. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  56761. var light_1 = scene.lights[index];
  56762. if (light_1 && light_1._waitingParentId) {
  56763. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  56764. light_1._waitingParentId = null;
  56765. }
  56766. }
  56767. // Sounds
  56768. // TODO: add sound
  56769. var loadedSounds = [];
  56770. var loadedSound;
  56771. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  56772. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  56773. var parsedSound = parsedData.sounds[index];
  56774. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56775. if (!parsedSound.url)
  56776. parsedSound.url = parsedSound.name;
  56777. if (!loadedSounds[parsedSound.url]) {
  56778. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  56779. loadedSounds[parsedSound.url] = loadedSound;
  56780. container.sounds.push(loadedSound);
  56781. }
  56782. else {
  56783. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  56784. }
  56785. }
  56786. else {
  56787. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  56788. }
  56789. }
  56790. }
  56791. loadedSounds = [];
  56792. // Connect parents & children and parse actions
  56793. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  56794. var transformNode = scene.transformNodes[index];
  56795. if (transformNode._waitingParentId) {
  56796. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  56797. transformNode._waitingParentId = null;
  56798. }
  56799. }
  56800. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56801. var mesh = scene.meshes[index];
  56802. if (mesh._waitingParentId) {
  56803. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  56804. mesh._waitingParentId = null;
  56805. }
  56806. if (mesh._waitingActions) {
  56807. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  56808. mesh._waitingActions = null;
  56809. }
  56810. }
  56811. // freeze world matrix application
  56812. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56813. var currentMesh = scene.meshes[index];
  56814. if (currentMesh._waitingFreezeWorldMatrix) {
  56815. currentMesh.freezeWorldMatrix();
  56816. currentMesh._waitingFreezeWorldMatrix = null;
  56817. }
  56818. else {
  56819. currentMesh.computeWorldMatrix(true);
  56820. }
  56821. }
  56822. // Particles Systems
  56823. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56824. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56825. var parsedParticleSystem = parsedData.particleSystems[index];
  56826. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56827. container.particleSystems.push(ps);
  56828. }
  56829. }
  56830. // Lens flares
  56831. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  56832. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  56833. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  56834. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  56835. container.lensFlareSystems.push(lf);
  56836. }
  56837. }
  56838. // Shadows
  56839. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  56840. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  56841. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  56842. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  56843. container.shadowGenerators.push(sg);
  56844. }
  56845. }
  56846. // Lights exclusions / inclusions
  56847. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  56848. var light_2 = scene.lights[index];
  56849. // Excluded check
  56850. if (light_2._excludedMeshesIds.length > 0) {
  56851. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  56852. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  56853. if (excludedMesh) {
  56854. light_2.excludedMeshes.push(excludedMesh);
  56855. }
  56856. }
  56857. light_2._excludedMeshesIds = [];
  56858. }
  56859. // Included check
  56860. if (light_2._includedOnlyMeshesIds.length > 0) {
  56861. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  56862. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  56863. if (includedOnlyMesh) {
  56864. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  56865. }
  56866. }
  56867. light_2._includedOnlyMeshesIds = [];
  56868. }
  56869. }
  56870. // Actions (scene)
  56871. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  56872. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  56873. }
  56874. if (!addToScene) {
  56875. container.removeAllFromScene();
  56876. }
  56877. return container;
  56878. }
  56879. catch (err) {
  56880. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  56881. if (onError) {
  56882. onError(msg, err);
  56883. }
  56884. else {
  56885. BABYLON.Tools.Log(msg);
  56886. throw err;
  56887. }
  56888. }
  56889. finally {
  56890. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  56891. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  56892. }
  56893. }
  56894. return null;
  56895. };
  56896. BABYLON.SceneLoader.RegisterPlugin({
  56897. name: "babylon.js",
  56898. extensions: ".babylon",
  56899. canDirectLoad: function (data) {
  56900. if (data.indexOf("babylon") !== -1) {
  56901. return true;
  56902. }
  56903. return false;
  56904. },
  56905. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  56906. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56907. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56908. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56909. // and avoid problems with multiple concurrent .babylon loads.
  56910. var log = "importMesh has failed JSON parse";
  56911. try {
  56912. var parsedData = JSON.parse(data);
  56913. log = "";
  56914. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  56915. if (!meshesNames) {
  56916. meshesNames = null;
  56917. }
  56918. else if (!Array.isArray(meshesNames)) {
  56919. meshesNames = [meshesNames];
  56920. }
  56921. var hierarchyIds = new Array();
  56922. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  56923. var loadedSkeletonsIds = [];
  56924. var loadedMaterialsIds = [];
  56925. var index;
  56926. var cache;
  56927. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  56928. var parsedMesh = parsedData.meshes[index];
  56929. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  56930. if (meshesNames !== null) {
  56931. // Remove found mesh name from list.
  56932. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  56933. }
  56934. //Geometry?
  56935. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  56936. //does the file contain geometries?
  56937. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  56938. //find the correct geometry and add it to the scene
  56939. var found = false;
  56940. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  56941. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  56942. return;
  56943. }
  56944. else {
  56945. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  56946. if (parsedGeometryData.id === parsedMesh.geometryId) {
  56947. switch (geometryType) {
  56948. case "boxes":
  56949. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  56950. break;
  56951. case "spheres":
  56952. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  56953. break;
  56954. case "cylinders":
  56955. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  56956. break;
  56957. case "toruses":
  56958. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  56959. break;
  56960. case "grounds":
  56961. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  56962. break;
  56963. case "planes":
  56964. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  56965. break;
  56966. case "torusKnots":
  56967. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  56968. break;
  56969. case "vertexData":
  56970. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  56971. break;
  56972. }
  56973. found = true;
  56974. }
  56975. });
  56976. }
  56977. });
  56978. if (found === false) {
  56979. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  56980. }
  56981. }
  56982. }
  56983. // Material ?
  56984. if (parsedMesh.materialId) {
  56985. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  56986. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  56987. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  56988. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  56989. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  56990. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  56991. var subMatId = parsedMultiMaterial.materials[matIndex];
  56992. loadedMaterialsIds.push(subMatId);
  56993. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  56994. log += "\n\tMaterial " + mat.toString(fullDetails);
  56995. }
  56996. loadedMaterialsIds.push(parsedMultiMaterial.id);
  56997. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  56998. materialFound = true;
  56999. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  57000. break;
  57001. }
  57002. }
  57003. }
  57004. if (materialFound === false) {
  57005. loadedMaterialsIds.push(parsedMesh.materialId);
  57006. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  57007. if (!mat) {
  57008. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  57009. }
  57010. else {
  57011. log += "\n\tMaterial " + mat.toString(fullDetails);
  57012. }
  57013. }
  57014. }
  57015. // Skeleton ?
  57016. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57017. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  57018. if (skeletonAlreadyLoaded === false) {
  57019. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  57020. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  57021. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  57022. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57023. skeletons.push(skeleton);
  57024. loadedSkeletonsIds.push(parsedSkeleton.id);
  57025. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  57026. }
  57027. }
  57028. }
  57029. }
  57030. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57031. meshes.push(mesh);
  57032. log += "\n\tMesh " + mesh.toString(fullDetails);
  57033. }
  57034. }
  57035. // Connecting parents
  57036. var currentMesh;
  57037. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57038. currentMesh = scene.meshes[index];
  57039. if (currentMesh._waitingParentId) {
  57040. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  57041. currentMesh._waitingParentId = null;
  57042. }
  57043. }
  57044. // freeze and compute world matrix application
  57045. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57046. currentMesh = scene.meshes[index];
  57047. if (currentMesh._waitingFreezeWorldMatrix) {
  57048. currentMesh.freezeWorldMatrix();
  57049. currentMesh._waitingFreezeWorldMatrix = null;
  57050. }
  57051. else {
  57052. currentMesh.computeWorldMatrix(true);
  57053. }
  57054. }
  57055. }
  57056. // Particles
  57057. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57058. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57059. var parsedParticleSystem = parsedData.particleSystems[index];
  57060. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  57061. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  57062. }
  57063. }
  57064. }
  57065. return true;
  57066. }
  57067. catch (err) {
  57068. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  57069. if (onError) {
  57070. onError(msg, err);
  57071. }
  57072. else {
  57073. BABYLON.Tools.Log(msg);
  57074. throw err;
  57075. }
  57076. }
  57077. finally {
  57078. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57079. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57080. }
  57081. }
  57082. return false;
  57083. },
  57084. load: function (scene, data, rootUrl, onError) {
  57085. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57086. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57087. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57088. // and avoid problems with multiple concurrent .babylon loads.
  57089. var log = "importScene has failed JSON parse";
  57090. try {
  57091. var parsedData = JSON.parse(data);
  57092. log = "";
  57093. // Scene
  57094. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  57095. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  57096. }
  57097. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  57098. scene.autoClear = parsedData.autoClear;
  57099. }
  57100. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  57101. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  57102. }
  57103. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  57104. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  57105. }
  57106. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  57107. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  57108. }
  57109. // Fog
  57110. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  57111. scene.fogMode = parsedData.fogMode;
  57112. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  57113. scene.fogStart = parsedData.fogStart;
  57114. scene.fogEnd = parsedData.fogEnd;
  57115. scene.fogDensity = parsedData.fogDensity;
  57116. log += "\tFog mode for scene: ";
  57117. switch (scene.fogMode) {
  57118. // getters not compiling, so using hardcoded
  57119. case 1:
  57120. log += "exp\n";
  57121. break;
  57122. case 2:
  57123. log += "exp2\n";
  57124. break;
  57125. case 3:
  57126. log += "linear\n";
  57127. break;
  57128. }
  57129. }
  57130. //Physics
  57131. if (parsedData.physicsEnabled) {
  57132. var physicsPlugin;
  57133. if (parsedData.physicsEngine === "cannon") {
  57134. physicsPlugin = new BABYLON.CannonJSPlugin();
  57135. }
  57136. else if (parsedData.physicsEngine === "oimo") {
  57137. physicsPlugin = new BABYLON.OimoJSPlugin();
  57138. }
  57139. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  57140. //else - default engine, which is currently oimo
  57141. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  57142. scene.enablePhysics(physicsGravity, physicsPlugin);
  57143. }
  57144. // Metadata
  57145. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  57146. scene.metadata = parsedData.metadata;
  57147. }
  57148. //collisions, if defined. otherwise, default is true
  57149. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  57150. scene.collisionsEnabled = parsedData.collisionsEnabled;
  57151. }
  57152. scene.workerCollisions = !!parsedData.workerCollisions;
  57153. var container = loadAssets(scene, data, rootUrl, onerror, true);
  57154. if (!container) {
  57155. return false;
  57156. }
  57157. if (parsedData.autoAnimate) {
  57158. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  57159. }
  57160. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  57161. scene.setActiveCameraByID(parsedData.activeCameraID);
  57162. }
  57163. // Environment texture
  57164. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  57165. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  57166. if (parsedData.createDefaultSkybox === true) {
  57167. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  57168. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  57169. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  57170. }
  57171. }
  57172. // Finish
  57173. return true;
  57174. }
  57175. catch (err) {
  57176. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  57177. if (onError) {
  57178. onError(msg, err);
  57179. }
  57180. else {
  57181. BABYLON.Tools.Log(msg);
  57182. throw err;
  57183. }
  57184. }
  57185. finally {
  57186. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57187. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57188. }
  57189. }
  57190. return false;
  57191. },
  57192. loadAssets: function (scene, data, rootUrl, onError) {
  57193. var container = loadAssets(scene, data, rootUrl, onerror);
  57194. return container;
  57195. }
  57196. });
  57197. })(BABYLON || (BABYLON = {}));
  57198. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  57199. var BABYLON;
  57200. (function (BABYLON) {
  57201. var FilesInput = /** @class */ (function () {
  57202. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  57203. this.onProcessFileCallback = function () { return true; };
  57204. this._engine = engine;
  57205. this._currentScene = scene;
  57206. this._sceneLoadedCallback = sceneLoadedCallback;
  57207. this._progressCallback = progressCallback;
  57208. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  57209. this._textureLoadingCallback = textureLoadingCallback;
  57210. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  57211. this._onReloadCallback = onReloadCallback;
  57212. this._errorCallback = errorCallback;
  57213. }
  57214. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  57215. var _this = this;
  57216. if (elementToMonitor) {
  57217. this._elementToMonitor = elementToMonitor;
  57218. this._dragEnterHandler = function (e) { _this.drag(e); };
  57219. this._dragOverHandler = function (e) { _this.drag(e); };
  57220. this._dropHandler = function (e) { _this.drop(e); };
  57221. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  57222. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  57223. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  57224. }
  57225. };
  57226. FilesInput.prototype.dispose = function () {
  57227. if (!this._elementToMonitor) {
  57228. return;
  57229. }
  57230. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  57231. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  57232. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  57233. };
  57234. FilesInput.prototype.renderFunction = function () {
  57235. if (this._additionalRenderLoopLogicCallback) {
  57236. this._additionalRenderLoopLogicCallback();
  57237. }
  57238. if (this._currentScene) {
  57239. if (this._textureLoadingCallback) {
  57240. var remaining = this._currentScene.getWaitingItemsCount();
  57241. if (remaining > 0) {
  57242. this._textureLoadingCallback(remaining);
  57243. }
  57244. }
  57245. this._currentScene.render();
  57246. }
  57247. };
  57248. FilesInput.prototype.drag = function (e) {
  57249. e.stopPropagation();
  57250. e.preventDefault();
  57251. };
  57252. FilesInput.prototype.drop = function (eventDrop) {
  57253. eventDrop.stopPropagation();
  57254. eventDrop.preventDefault();
  57255. this.loadFiles(eventDrop);
  57256. };
  57257. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  57258. var _this = this;
  57259. var reader = folder.createReader();
  57260. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  57261. reader.readEntries(function (entries) {
  57262. remaining.count += entries.length;
  57263. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  57264. var entry = entries_1[_i];
  57265. if (entry.isFile) {
  57266. entry.file(function (file) {
  57267. file.correctName = relativePath + file.name;
  57268. files.push(file);
  57269. if (--remaining.count === 0) {
  57270. callback();
  57271. }
  57272. });
  57273. }
  57274. else if (entry.isDirectory) {
  57275. _this._traverseFolder(entry, files, remaining, callback);
  57276. }
  57277. }
  57278. if (--remaining.count) {
  57279. callback();
  57280. }
  57281. });
  57282. };
  57283. FilesInput.prototype._processFiles = function (files) {
  57284. for (var i = 0; i < files.length; i++) {
  57285. var name = files[i].correctName.toLowerCase();
  57286. var extension = name.split('.').pop();
  57287. if (!this.onProcessFileCallback(files[i], name, extension)) {
  57288. continue;
  57289. }
  57290. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  57291. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  57292. this._sceneFileToLoad = files[i];
  57293. }
  57294. else {
  57295. FilesInput.FilesToLoad[name] = files[i];
  57296. }
  57297. }
  57298. };
  57299. FilesInput.prototype.loadFiles = function (event) {
  57300. var _this = this;
  57301. if (this._startingProcessingFilesCallback)
  57302. this._startingProcessingFilesCallback();
  57303. // Handling data transfer via drag'n'drop
  57304. if (event && event.dataTransfer && event.dataTransfer.files) {
  57305. this._filesToLoad = event.dataTransfer.files;
  57306. }
  57307. // Handling files from input files
  57308. if (event && event.target && event.target.files) {
  57309. this._filesToLoad = event.target.files;
  57310. }
  57311. if (this._filesToLoad && this._filesToLoad.length > 0) {
  57312. var files_1 = new Array();
  57313. var folders = [];
  57314. var items = event.dataTransfer ? event.dataTransfer.items : null;
  57315. for (var i = 0; i < this._filesToLoad.length; i++) {
  57316. var fileToLoad = this._filesToLoad[i];
  57317. var name_1 = fileToLoad.name.toLowerCase();
  57318. var entry = void 0;
  57319. fileToLoad.correctName = name_1;
  57320. if (items) {
  57321. var item = items[i];
  57322. if (item.getAsEntry) {
  57323. entry = item.getAsEntry();
  57324. }
  57325. else if (item.webkitGetAsEntry) {
  57326. entry = item.webkitGetAsEntry();
  57327. }
  57328. }
  57329. if (!entry) {
  57330. files_1.push(fileToLoad);
  57331. }
  57332. else {
  57333. if (entry.isDirectory) {
  57334. folders.push(entry);
  57335. }
  57336. else {
  57337. files_1.push(fileToLoad);
  57338. }
  57339. }
  57340. }
  57341. if (folders.length === 0) {
  57342. this._processFiles(files_1);
  57343. this._processReload();
  57344. }
  57345. else {
  57346. var remaining = { count: folders.length };
  57347. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  57348. var folder = folders_1[_i];
  57349. this._traverseFolder(folder, files_1, remaining, function () {
  57350. _this._processFiles(files_1);
  57351. if (remaining.count === 0) {
  57352. _this._processReload();
  57353. }
  57354. });
  57355. }
  57356. }
  57357. }
  57358. };
  57359. FilesInput.prototype._processReload = function () {
  57360. if (this._onReloadCallback) {
  57361. this._onReloadCallback(this._sceneFileToLoad);
  57362. }
  57363. else {
  57364. this.reload();
  57365. }
  57366. };
  57367. FilesInput.prototype.reload = function () {
  57368. var _this = this;
  57369. // If a scene file has been provided
  57370. if (this._sceneFileToLoad) {
  57371. if (this._currentScene) {
  57372. if (BABYLON.Tools.errorsCount > 0) {
  57373. BABYLON.Tools.ClearLogCache();
  57374. }
  57375. this._engine.stopRenderLoop();
  57376. this._currentScene.dispose();
  57377. }
  57378. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  57379. _this._currentScene = newScene;
  57380. if (_this._sceneLoadedCallback) {
  57381. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  57382. }
  57383. // Wait for textures and shaders to be ready
  57384. _this._currentScene.executeWhenReady(function () {
  57385. _this._engine.runRenderLoop(function () {
  57386. _this.renderFunction();
  57387. });
  57388. });
  57389. }, function (progress) {
  57390. if (_this._progressCallback) {
  57391. _this._progressCallback(progress);
  57392. }
  57393. }, function (scene, message) {
  57394. _this._currentScene = scene;
  57395. if (_this._errorCallback) {
  57396. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  57397. }
  57398. });
  57399. }
  57400. else {
  57401. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  57402. }
  57403. };
  57404. FilesInput.FilesToLoad = {};
  57405. return FilesInput;
  57406. }());
  57407. BABYLON.FilesInput = FilesInput;
  57408. })(BABYLON || (BABYLON = {}));
  57409. //# sourceMappingURL=babylon.filesInput.js.map
  57410. var BABYLON;
  57411. (function (BABYLON) {
  57412. /**
  57413. * This class implement a typical dictionary using a string as key and the generic type T as value.
  57414. * The underlying implementation relies on an associative array to ensure the best performances.
  57415. * The value can be anything including 'null' but except 'undefined'
  57416. */
  57417. var StringDictionary = /** @class */ (function () {
  57418. function StringDictionary() {
  57419. this._count = 0;
  57420. this._data = {};
  57421. }
  57422. /**
  57423. * This will clear this dictionary and copy the content from the 'source' one.
  57424. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  57425. * @param source the dictionary to take the content from and copy to this dictionary
  57426. */
  57427. StringDictionary.prototype.copyFrom = function (source) {
  57428. var _this = this;
  57429. this.clear();
  57430. source.forEach(function (t, v) { return _this.add(t, v); });
  57431. };
  57432. /**
  57433. * Get a value based from its key
  57434. * @param key the given key to get the matching value from
  57435. * @return the value if found, otherwise undefined is returned
  57436. */
  57437. StringDictionary.prototype.get = function (key) {
  57438. var val = this._data[key];
  57439. if (val !== undefined) {
  57440. return val;
  57441. }
  57442. return undefined;
  57443. };
  57444. /**
  57445. * Get a value from its key or add it if it doesn't exist.
  57446. * This method will ensure you that a given key/data will be present in the dictionary.
  57447. * @param key the given key to get the matching value from
  57448. * @param factory the factory that will create the value if the key is not present in the dictionary.
  57449. * The factory will only be invoked if there's no data for the given key.
  57450. * @return the value corresponding to the key.
  57451. */
  57452. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  57453. var val = this.get(key);
  57454. if (val !== undefined) {
  57455. return val;
  57456. }
  57457. val = factory(key);
  57458. if (val) {
  57459. this.add(key, val);
  57460. }
  57461. return val;
  57462. };
  57463. /**
  57464. * Get a value from its key if present in the dictionary otherwise add it
  57465. * @param key the key to get the value from
  57466. * @param val if there's no such key/value pair in the dictionary add it with this value
  57467. * @return the value corresponding to the key
  57468. */
  57469. StringDictionary.prototype.getOrAdd = function (key, val) {
  57470. var curVal = this.get(key);
  57471. if (curVal !== undefined) {
  57472. return curVal;
  57473. }
  57474. this.add(key, val);
  57475. return val;
  57476. };
  57477. /**
  57478. * Check if there's a given key in the dictionary
  57479. * @param key the key to check for
  57480. * @return true if the key is present, false otherwise
  57481. */
  57482. StringDictionary.prototype.contains = function (key) {
  57483. return this._data[key] !== undefined;
  57484. };
  57485. /**
  57486. * Add a new key and its corresponding value
  57487. * @param key the key to add
  57488. * @param value the value corresponding to the key
  57489. * @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
  57490. */
  57491. StringDictionary.prototype.add = function (key, value) {
  57492. if (this._data[key] !== undefined) {
  57493. return false;
  57494. }
  57495. this._data[key] = value;
  57496. ++this._count;
  57497. return true;
  57498. };
  57499. StringDictionary.prototype.set = function (key, value) {
  57500. if (this._data[key] === undefined) {
  57501. return false;
  57502. }
  57503. this._data[key] = value;
  57504. return true;
  57505. };
  57506. /**
  57507. * Get the element of the given key and remove it from the dictionary
  57508. * @param key
  57509. */
  57510. StringDictionary.prototype.getAndRemove = function (key) {
  57511. var val = this.get(key);
  57512. if (val !== undefined) {
  57513. delete this._data[key];
  57514. --this._count;
  57515. return val;
  57516. }
  57517. return null;
  57518. };
  57519. /**
  57520. * Remove a key/value from the dictionary.
  57521. * @param key the key to remove
  57522. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  57523. */
  57524. StringDictionary.prototype.remove = function (key) {
  57525. if (this.contains(key)) {
  57526. delete this._data[key];
  57527. --this._count;
  57528. return true;
  57529. }
  57530. return false;
  57531. };
  57532. /**
  57533. * Clear the whole content of the dictionary
  57534. */
  57535. StringDictionary.prototype.clear = function () {
  57536. this._data = {};
  57537. this._count = 0;
  57538. };
  57539. Object.defineProperty(StringDictionary.prototype, "count", {
  57540. get: function () {
  57541. return this._count;
  57542. },
  57543. enumerable: true,
  57544. configurable: true
  57545. });
  57546. /**
  57547. * Execute a callback on each key/val of the dictionary.
  57548. * Note that you can remove any element in this dictionary in the callback implementation
  57549. * @param callback the callback to execute on a given key/value pair
  57550. */
  57551. StringDictionary.prototype.forEach = function (callback) {
  57552. for (var cur in this._data) {
  57553. var val = this._data[cur];
  57554. callback(cur, val);
  57555. }
  57556. };
  57557. /**
  57558. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  57559. * If the callback returns null or undefined the method will iterate to the next key/value pair
  57560. * Note that you can remove any element in this dictionary in the callback implementation
  57561. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  57562. */
  57563. StringDictionary.prototype.first = function (callback) {
  57564. for (var cur in this._data) {
  57565. var val = this._data[cur];
  57566. var res = callback(cur, val);
  57567. if (res) {
  57568. return res;
  57569. }
  57570. }
  57571. return null;
  57572. };
  57573. return StringDictionary;
  57574. }());
  57575. BABYLON.StringDictionary = StringDictionary;
  57576. })(BABYLON || (BABYLON = {}));
  57577. //# sourceMappingURL=babylon.stringDictionary.js.map
  57578. var BABYLON;
  57579. (function (BABYLON) {
  57580. var Tags = /** @class */ (function () {
  57581. function Tags() {
  57582. }
  57583. Tags.EnableFor = function (obj) {
  57584. obj._tags = obj._tags || {};
  57585. obj.hasTags = function () {
  57586. return Tags.HasTags(obj);
  57587. };
  57588. obj.addTags = function (tagsString) {
  57589. return Tags.AddTagsTo(obj, tagsString);
  57590. };
  57591. obj.removeTags = function (tagsString) {
  57592. return Tags.RemoveTagsFrom(obj, tagsString);
  57593. };
  57594. obj.matchesTagsQuery = function (tagsQuery) {
  57595. return Tags.MatchesQuery(obj, tagsQuery);
  57596. };
  57597. };
  57598. Tags.DisableFor = function (obj) {
  57599. delete obj._tags;
  57600. delete obj.hasTags;
  57601. delete obj.addTags;
  57602. delete obj.removeTags;
  57603. delete obj.matchesTagsQuery;
  57604. };
  57605. Tags.HasTags = function (obj) {
  57606. if (!obj._tags) {
  57607. return false;
  57608. }
  57609. return !BABYLON.Tools.IsEmpty(obj._tags);
  57610. };
  57611. Tags.GetTags = function (obj, asString) {
  57612. if (asString === void 0) { asString = true; }
  57613. if (!obj._tags) {
  57614. return null;
  57615. }
  57616. if (asString) {
  57617. var tagsArray = [];
  57618. for (var tag in obj._tags) {
  57619. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  57620. tagsArray.push(tag);
  57621. }
  57622. }
  57623. return tagsArray.join(" ");
  57624. }
  57625. else {
  57626. return obj._tags;
  57627. }
  57628. };
  57629. // the tags 'true' and 'false' are reserved and cannot be used as tags
  57630. // a tag cannot start with '||', '&&', and '!'
  57631. // it cannot contain whitespaces
  57632. Tags.AddTagsTo = function (obj, tagsString) {
  57633. if (!tagsString) {
  57634. return;
  57635. }
  57636. if (typeof tagsString !== "string") {
  57637. return;
  57638. }
  57639. var tags = tagsString.split(" ");
  57640. tags.forEach(function (tag, index, array) {
  57641. Tags._AddTagTo(obj, tag);
  57642. });
  57643. };
  57644. Tags._AddTagTo = function (obj, tag) {
  57645. tag = tag.trim();
  57646. if (tag === "" || tag === "true" || tag === "false") {
  57647. return;
  57648. }
  57649. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  57650. return;
  57651. }
  57652. Tags.EnableFor(obj);
  57653. obj._tags[tag] = true;
  57654. };
  57655. Tags.RemoveTagsFrom = function (obj, tagsString) {
  57656. if (!Tags.HasTags(obj)) {
  57657. return;
  57658. }
  57659. var tags = tagsString.split(" ");
  57660. for (var t in tags) {
  57661. Tags._RemoveTagFrom(obj, tags[t]);
  57662. }
  57663. };
  57664. Tags._RemoveTagFrom = function (obj, tag) {
  57665. delete obj._tags[tag];
  57666. };
  57667. Tags.MatchesQuery = function (obj, tagsQuery) {
  57668. if (tagsQuery === undefined) {
  57669. return true;
  57670. }
  57671. if (tagsQuery === "") {
  57672. return Tags.HasTags(obj);
  57673. }
  57674. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  57675. };
  57676. return Tags;
  57677. }());
  57678. BABYLON.Tags = Tags;
  57679. })(BABYLON || (BABYLON = {}));
  57680. //# sourceMappingURL=babylon.tags.js.map
  57681. var BABYLON;
  57682. (function (BABYLON) {
  57683. var AndOrNotEvaluator = /** @class */ (function () {
  57684. function AndOrNotEvaluator() {
  57685. }
  57686. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  57687. if (!query.match(/\([^\(\)]*\)/g)) {
  57688. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  57689. }
  57690. else {
  57691. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  57692. // remove parenthesis
  57693. r = r.slice(1, r.length - 1);
  57694. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  57695. });
  57696. }
  57697. if (query === "true") {
  57698. return true;
  57699. }
  57700. if (query === "false") {
  57701. return false;
  57702. }
  57703. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  57704. };
  57705. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  57706. evaluateCallback = evaluateCallback || (function (r) {
  57707. return r === "true" ? true : false;
  57708. });
  57709. var result;
  57710. var or = parenthesisContent.split("||");
  57711. for (var i in or) {
  57712. if (or.hasOwnProperty(i)) {
  57713. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  57714. var and = ori.split("&&");
  57715. if (and.length > 1) {
  57716. for (var j = 0; j < and.length; ++j) {
  57717. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  57718. if (andj !== "true" && andj !== "false") {
  57719. if (andj[0] === "!") {
  57720. result = !evaluateCallback(andj.substring(1));
  57721. }
  57722. else {
  57723. result = evaluateCallback(andj);
  57724. }
  57725. }
  57726. else {
  57727. result = andj === "true" ? true : false;
  57728. }
  57729. if (!result) {
  57730. ori = "false";
  57731. break;
  57732. }
  57733. }
  57734. }
  57735. if (result || ori === "true") {
  57736. result = true;
  57737. break;
  57738. }
  57739. // result equals false (or undefined)
  57740. if (ori !== "true" && ori !== "false") {
  57741. if (ori[0] === "!") {
  57742. result = !evaluateCallback(ori.substring(1));
  57743. }
  57744. else {
  57745. result = evaluateCallback(ori);
  57746. }
  57747. }
  57748. else {
  57749. result = ori === "true" ? true : false;
  57750. }
  57751. }
  57752. }
  57753. // the whole parenthesis scope is replaced by 'true' or 'false'
  57754. return result ? "true" : "false";
  57755. };
  57756. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  57757. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  57758. // remove whitespaces
  57759. r = r.replace(/[\s]/g, function () { return ""; });
  57760. return r.length % 2 ? "!" : "";
  57761. });
  57762. booleanString = booleanString.trim();
  57763. if (booleanString === "!true") {
  57764. booleanString = "false";
  57765. }
  57766. else if (booleanString === "!false") {
  57767. booleanString = "true";
  57768. }
  57769. return booleanString;
  57770. };
  57771. return AndOrNotEvaluator;
  57772. }());
  57773. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  57774. })(BABYLON || (BABYLON = {}));
  57775. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  57776. var BABYLON;
  57777. (function (BABYLON) {
  57778. var Database = /** @class */ (function () {
  57779. function Database(urlToScene, callbackManifestChecked) {
  57780. // Handling various flavors of prefixed version of IndexedDB
  57781. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  57782. this.callbackManifestChecked = callbackManifestChecked;
  57783. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  57784. this.db = null;
  57785. this._enableSceneOffline = false;
  57786. this._enableTexturesOffline = false;
  57787. this.manifestVersionFound = 0;
  57788. this.mustUpdateRessources = false;
  57789. this.hasReachedQuota = false;
  57790. if (!Database.IDBStorageEnabled) {
  57791. this.callbackManifestChecked(true);
  57792. }
  57793. else {
  57794. this.checkManifestFile();
  57795. }
  57796. }
  57797. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  57798. get: function () {
  57799. return this._enableSceneOffline;
  57800. },
  57801. enumerable: true,
  57802. configurable: true
  57803. });
  57804. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  57805. get: function () {
  57806. return this._enableTexturesOffline;
  57807. },
  57808. enumerable: true,
  57809. configurable: true
  57810. });
  57811. Database.prototype.checkManifestFile = function () {
  57812. var _this = this;
  57813. var noManifestFile = function () {
  57814. _this._enableSceneOffline = false;
  57815. _this._enableTexturesOffline = false;
  57816. _this.callbackManifestChecked(false);
  57817. };
  57818. var timeStampUsed = false;
  57819. var manifestURL = this.currentSceneUrl + ".manifest";
  57820. var xhr = new XMLHttpRequest();
  57821. if (navigator.onLine) {
  57822. // Adding a timestamp to by-pass browsers' cache
  57823. timeStampUsed = true;
  57824. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  57825. }
  57826. xhr.open("GET", manifestURL, true);
  57827. xhr.addEventListener("load", function () {
  57828. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57829. try {
  57830. var manifestFile = JSON.parse(xhr.response);
  57831. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  57832. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  57833. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  57834. _this.manifestVersionFound = manifestFile.version;
  57835. }
  57836. if (_this.callbackManifestChecked) {
  57837. _this.callbackManifestChecked(true);
  57838. }
  57839. }
  57840. catch (ex) {
  57841. noManifestFile();
  57842. }
  57843. }
  57844. else {
  57845. noManifestFile();
  57846. }
  57847. }, false);
  57848. xhr.addEventListener("error", function (event) {
  57849. if (timeStampUsed) {
  57850. timeStampUsed = false;
  57851. // Let's retry without the timeStamp
  57852. // It could fail when coupled with HTML5 Offline API
  57853. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  57854. xhr.open("GET", retryManifestURL, true);
  57855. xhr.send();
  57856. }
  57857. else {
  57858. noManifestFile();
  57859. }
  57860. }, false);
  57861. try {
  57862. xhr.send();
  57863. }
  57864. catch (ex) {
  57865. BABYLON.Tools.Error("Error on XHR send request.");
  57866. this.callbackManifestChecked(false);
  57867. }
  57868. };
  57869. Database.prototype.openAsync = function (successCallback, errorCallback) {
  57870. var _this = this;
  57871. var handleError = function () {
  57872. _this.isSupported = false;
  57873. if (errorCallback)
  57874. errorCallback();
  57875. };
  57876. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  57877. // Your browser doesn't support IndexedDB
  57878. this.isSupported = false;
  57879. if (errorCallback)
  57880. errorCallback();
  57881. }
  57882. else {
  57883. // If the DB hasn't been opened or created yet
  57884. if (!this.db) {
  57885. this.hasReachedQuota = false;
  57886. this.isSupported = true;
  57887. var request = this.idbFactory.open("babylonjs", 1);
  57888. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  57889. request.onerror = function (event) {
  57890. handleError();
  57891. };
  57892. // executes when a version change transaction cannot complete due to other active transactions
  57893. request.onblocked = function (event) {
  57894. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  57895. handleError();
  57896. };
  57897. // DB has been opened successfully
  57898. request.onsuccess = function (event) {
  57899. _this.db = request.result;
  57900. successCallback();
  57901. };
  57902. // Initialization of the DB. Creating Scenes & Textures stores
  57903. request.onupgradeneeded = function (event) {
  57904. _this.db = (event.target).result;
  57905. if (_this.db) {
  57906. try {
  57907. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  57908. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  57909. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  57910. }
  57911. catch (ex) {
  57912. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  57913. handleError();
  57914. }
  57915. }
  57916. };
  57917. }
  57918. else {
  57919. if (successCallback)
  57920. successCallback();
  57921. }
  57922. }
  57923. };
  57924. Database.prototype.loadImageFromDB = function (url, image) {
  57925. var _this = this;
  57926. var completeURL = Database.ReturnFullUrlLocation(url);
  57927. var saveAndLoadImage = function () {
  57928. if (!_this.hasReachedQuota && _this.db !== null) {
  57929. // the texture is not yet in the DB, let's try to save it
  57930. _this._saveImageIntoDBAsync(completeURL, image);
  57931. }
  57932. else {
  57933. image.src = url;
  57934. }
  57935. };
  57936. if (!this.mustUpdateRessources) {
  57937. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  57938. }
  57939. else {
  57940. saveAndLoadImage();
  57941. }
  57942. };
  57943. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  57944. if (this.isSupported && this.db !== null) {
  57945. var texture;
  57946. var transaction = this.db.transaction(["textures"]);
  57947. transaction.onabort = function (event) {
  57948. image.src = url;
  57949. };
  57950. transaction.oncomplete = function (event) {
  57951. var blobTextureURL;
  57952. if (texture) {
  57953. var URL = window.URL || window.webkitURL;
  57954. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  57955. image.onerror = function () {
  57956. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  57957. image.src = url;
  57958. };
  57959. image.src = blobTextureURL;
  57960. }
  57961. else {
  57962. notInDBCallback();
  57963. }
  57964. };
  57965. var getRequest = transaction.objectStore("textures").get(url);
  57966. getRequest.onsuccess = function (event) {
  57967. texture = (event.target).result;
  57968. };
  57969. getRequest.onerror = function (event) {
  57970. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  57971. image.src = url;
  57972. };
  57973. }
  57974. else {
  57975. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  57976. image.src = url;
  57977. }
  57978. };
  57979. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  57980. var _this = this;
  57981. if (this.isSupported) {
  57982. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  57983. var generateBlobUrl = function () {
  57984. var blobTextureURL;
  57985. if (blob) {
  57986. var URL = window.URL || window.webkitURL;
  57987. try {
  57988. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  57989. }
  57990. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  57991. catch (ex) {
  57992. blobTextureURL = URL.createObjectURL(blob);
  57993. }
  57994. }
  57995. if (blobTextureURL) {
  57996. image.src = blobTextureURL;
  57997. }
  57998. };
  57999. if (Database.IsUASupportingBlobStorage) {
  58000. var xhr = new XMLHttpRequest(), blob;
  58001. xhr.open("GET", url, true);
  58002. xhr.responseType = "blob";
  58003. xhr.addEventListener("load", function () {
  58004. if (xhr.status === 200 && _this.db) {
  58005. // Blob as response (XHR2)
  58006. blob = xhr.response;
  58007. var transaction = _this.db.transaction(["textures"], "readwrite");
  58008. // the transaction could abort because of a QuotaExceededError error
  58009. transaction.onabort = function (event) {
  58010. try {
  58011. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58012. var srcElement = (event.srcElement || event.target);
  58013. var error = srcElement.error;
  58014. if (error && error.name === "QuotaExceededError") {
  58015. _this.hasReachedQuota = true;
  58016. }
  58017. }
  58018. catch (ex) { }
  58019. generateBlobUrl();
  58020. };
  58021. transaction.oncomplete = function (event) {
  58022. generateBlobUrl();
  58023. };
  58024. var newTexture = { textureUrl: url, data: blob };
  58025. try {
  58026. // Put the blob into the dabase
  58027. var addRequest = transaction.objectStore("textures").put(newTexture);
  58028. addRequest.onsuccess = function (event) {
  58029. };
  58030. addRequest.onerror = function (event) {
  58031. generateBlobUrl();
  58032. };
  58033. }
  58034. catch (ex) {
  58035. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  58036. if (ex.code === 25) {
  58037. Database.IsUASupportingBlobStorage = false;
  58038. }
  58039. image.src = url;
  58040. }
  58041. }
  58042. else {
  58043. image.src = url;
  58044. }
  58045. }, false);
  58046. xhr.addEventListener("error", function (event) {
  58047. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  58048. image.src = url;
  58049. }, false);
  58050. xhr.send();
  58051. }
  58052. else {
  58053. image.src = url;
  58054. }
  58055. }
  58056. else {
  58057. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58058. image.src = url;
  58059. }
  58060. };
  58061. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  58062. var _this = this;
  58063. var updateVersion = function () {
  58064. // the version is not yet in the DB or we need to update it
  58065. _this._saveVersionIntoDBAsync(url, versionLoaded);
  58066. };
  58067. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  58068. };
  58069. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  58070. var _this = this;
  58071. if (this.isSupported && this.db) {
  58072. var version;
  58073. try {
  58074. var transaction = this.db.transaction(["versions"]);
  58075. transaction.oncomplete = function (event) {
  58076. if (version) {
  58077. // If the version in the JSON file is > than the version in DB
  58078. if (_this.manifestVersionFound > version.data) {
  58079. _this.mustUpdateRessources = true;
  58080. updateInDBCallback();
  58081. }
  58082. else {
  58083. callback(version.data);
  58084. }
  58085. }
  58086. else {
  58087. _this.mustUpdateRessources = true;
  58088. updateInDBCallback();
  58089. }
  58090. };
  58091. transaction.onabort = function (event) {
  58092. callback(-1);
  58093. };
  58094. var getRequest = transaction.objectStore("versions").get(url);
  58095. getRequest.onsuccess = function (event) {
  58096. version = (event.target).result;
  58097. };
  58098. getRequest.onerror = function (event) {
  58099. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  58100. callback(-1);
  58101. };
  58102. }
  58103. catch (ex) {
  58104. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  58105. callback(-1);
  58106. }
  58107. }
  58108. else {
  58109. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58110. callback(-1);
  58111. }
  58112. };
  58113. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  58114. var _this = this;
  58115. if (this.isSupported && !this.hasReachedQuota && this.db) {
  58116. try {
  58117. // Open a transaction to the database
  58118. var transaction = this.db.transaction(["versions"], "readwrite");
  58119. // the transaction could abort because of a QuotaExceededError error
  58120. transaction.onabort = function (event) {
  58121. try {
  58122. var error = event.srcElement['error'];
  58123. if (error && error.name === "QuotaExceededError") {
  58124. _this.hasReachedQuota = true;
  58125. }
  58126. }
  58127. catch (ex) { }
  58128. callback(-1);
  58129. };
  58130. transaction.oncomplete = function (event) {
  58131. callback(_this.manifestVersionFound);
  58132. };
  58133. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  58134. // Put the scene into the database
  58135. var addRequest = transaction.objectStore("versions").put(newVersion);
  58136. addRequest.onsuccess = function (event) {
  58137. };
  58138. addRequest.onerror = function (event) {
  58139. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  58140. };
  58141. }
  58142. catch (ex) {
  58143. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  58144. callback(-1);
  58145. }
  58146. }
  58147. else {
  58148. callback(-1);
  58149. }
  58150. };
  58151. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  58152. var _this = this;
  58153. var completeUrl = Database.ReturnFullUrlLocation(url);
  58154. var saveAndLoadFile = function () {
  58155. // the scene is not yet in the DB, let's try to save it
  58156. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  58157. };
  58158. this._checkVersionFromDB(completeUrl, function (version) {
  58159. if (version !== -1) {
  58160. if (!_this.mustUpdateRessources) {
  58161. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  58162. }
  58163. else {
  58164. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  58165. }
  58166. }
  58167. else {
  58168. if (errorCallback) {
  58169. errorCallback();
  58170. }
  58171. }
  58172. });
  58173. };
  58174. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  58175. if (this.isSupported && this.db) {
  58176. var targetStore;
  58177. if (url.indexOf(".babylon") !== -1) {
  58178. targetStore = "scenes";
  58179. }
  58180. else {
  58181. targetStore = "textures";
  58182. }
  58183. var file;
  58184. var transaction = this.db.transaction([targetStore]);
  58185. transaction.oncomplete = function (event) {
  58186. if (file) {
  58187. callback(file.data);
  58188. }
  58189. else {
  58190. notInDBCallback();
  58191. }
  58192. };
  58193. transaction.onabort = function (event) {
  58194. notInDBCallback();
  58195. };
  58196. var getRequest = transaction.objectStore(targetStore).get(url);
  58197. getRequest.onsuccess = function (event) {
  58198. file = (event.target).result;
  58199. };
  58200. getRequest.onerror = function (event) {
  58201. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  58202. notInDBCallback();
  58203. };
  58204. }
  58205. else {
  58206. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58207. callback();
  58208. }
  58209. };
  58210. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  58211. var _this = this;
  58212. if (this.isSupported) {
  58213. var targetStore;
  58214. if (url.indexOf(".babylon") !== -1) {
  58215. targetStore = "scenes";
  58216. }
  58217. else {
  58218. targetStore = "textures";
  58219. }
  58220. // Create XHR
  58221. var xhr = new XMLHttpRequest();
  58222. var fileData;
  58223. xhr.open("GET", url, true);
  58224. if (useArrayBuffer) {
  58225. xhr.responseType = "arraybuffer";
  58226. }
  58227. if (progressCallback) {
  58228. xhr.onprogress = progressCallback;
  58229. }
  58230. xhr.addEventListener("load", function () {
  58231. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  58232. // Blob as response (XHR2)
  58233. //fileData = xhr.responseText;
  58234. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  58235. if (!_this.hasReachedQuota && _this.db) {
  58236. // Open a transaction to the database
  58237. var transaction = _this.db.transaction([targetStore], "readwrite");
  58238. // the transaction could abort because of a QuotaExceededError error
  58239. transaction.onabort = function (event) {
  58240. try {
  58241. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58242. var error = event.srcElement['error'];
  58243. if (error && error.name === "QuotaExceededError") {
  58244. _this.hasReachedQuota = true;
  58245. }
  58246. }
  58247. catch (ex) { }
  58248. callback(fileData);
  58249. };
  58250. transaction.oncomplete = function (event) {
  58251. callback(fileData);
  58252. };
  58253. var newFile;
  58254. if (targetStore === "scenes") {
  58255. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  58256. }
  58257. else {
  58258. newFile = { textureUrl: url, data: fileData };
  58259. }
  58260. try {
  58261. // Put the scene into the database
  58262. var addRequest = transaction.objectStore(targetStore).put(newFile);
  58263. addRequest.onsuccess = function (event) {
  58264. };
  58265. addRequest.onerror = function (event) {
  58266. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  58267. };
  58268. }
  58269. catch (ex) {
  58270. callback(fileData);
  58271. }
  58272. }
  58273. else {
  58274. callback(fileData);
  58275. }
  58276. }
  58277. else {
  58278. callback();
  58279. }
  58280. }, false);
  58281. xhr.addEventListener("error", function (event) {
  58282. BABYLON.Tools.Error("error on XHR request.");
  58283. callback();
  58284. }, false);
  58285. xhr.send();
  58286. }
  58287. else {
  58288. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58289. callback();
  58290. }
  58291. };
  58292. Database.IsUASupportingBlobStorage = true;
  58293. Database.IDBStorageEnabled = true;
  58294. Database.parseURL = function (url) {
  58295. var a = document.createElement('a');
  58296. a.href = url;
  58297. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  58298. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  58299. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  58300. return absLocation;
  58301. };
  58302. Database.ReturnFullUrlLocation = function (url) {
  58303. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  58304. return (Database.parseURL(window.location.href) + url);
  58305. }
  58306. else {
  58307. return url;
  58308. }
  58309. };
  58310. return Database;
  58311. }());
  58312. BABYLON.Database = Database;
  58313. })(BABYLON || (BABYLON = {}));
  58314. //# sourceMappingURL=babylon.database.js.map
  58315. var BABYLON;
  58316. (function (BABYLON) {
  58317. var FresnelParameters = /** @class */ (function () {
  58318. function FresnelParameters() {
  58319. this._isEnabled = true;
  58320. this.leftColor = BABYLON.Color3.White();
  58321. this.rightColor = BABYLON.Color3.Black();
  58322. this.bias = 0;
  58323. this.power = 1;
  58324. }
  58325. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  58326. get: function () {
  58327. return this._isEnabled;
  58328. },
  58329. set: function (value) {
  58330. if (this._isEnabled === value) {
  58331. return;
  58332. }
  58333. this._isEnabled = value;
  58334. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  58335. },
  58336. enumerable: true,
  58337. configurable: true
  58338. });
  58339. FresnelParameters.prototype.clone = function () {
  58340. var newFresnelParameters = new FresnelParameters();
  58341. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  58342. return newFresnelParameters;
  58343. };
  58344. FresnelParameters.prototype.serialize = function () {
  58345. var serializationObject = {};
  58346. serializationObject.isEnabled = this.isEnabled;
  58347. serializationObject.leftColor = this.leftColor;
  58348. serializationObject.rightColor = this.rightColor;
  58349. serializationObject.bias = this.bias;
  58350. serializationObject.power = this.power;
  58351. return serializationObject;
  58352. };
  58353. FresnelParameters.Parse = function (parsedFresnelParameters) {
  58354. var fresnelParameters = new FresnelParameters();
  58355. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  58356. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  58357. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  58358. fresnelParameters.bias = parsedFresnelParameters.bias;
  58359. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  58360. return fresnelParameters;
  58361. };
  58362. return FresnelParameters;
  58363. }());
  58364. BABYLON.FresnelParameters = FresnelParameters;
  58365. })(BABYLON || (BABYLON = {}));
  58366. //# sourceMappingURL=babylon.fresnelParameters.js.map
  58367. var BABYLON;
  58368. (function (BABYLON) {
  58369. var MultiMaterial = /** @class */ (function (_super) {
  58370. __extends(MultiMaterial, _super);
  58371. function MultiMaterial(name, scene) {
  58372. var _this = _super.call(this, name, scene, true) || this;
  58373. scene.multiMaterials.push(_this);
  58374. _this.subMaterials = new Array();
  58375. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  58376. return _this;
  58377. }
  58378. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  58379. get: function () {
  58380. return this._subMaterials;
  58381. },
  58382. set: function (value) {
  58383. this._subMaterials = value;
  58384. this._hookArray(value);
  58385. },
  58386. enumerable: true,
  58387. configurable: true
  58388. });
  58389. MultiMaterial.prototype._hookArray = function (array) {
  58390. var _this = this;
  58391. var oldPush = array.push;
  58392. array.push = function () {
  58393. var items = [];
  58394. for (var _i = 0; _i < arguments.length; _i++) {
  58395. items[_i] = arguments[_i];
  58396. }
  58397. var result = oldPush.apply(array, items);
  58398. _this._markAllSubMeshesAsTexturesDirty();
  58399. return result;
  58400. };
  58401. var oldSplice = array.splice;
  58402. array.splice = function (index, deleteCount) {
  58403. var deleted = oldSplice.apply(array, [index, deleteCount]);
  58404. _this._markAllSubMeshesAsTexturesDirty();
  58405. return deleted;
  58406. };
  58407. };
  58408. // Properties
  58409. MultiMaterial.prototype.getSubMaterial = function (index) {
  58410. if (index < 0 || index >= this.subMaterials.length) {
  58411. return this.getScene().defaultMaterial;
  58412. }
  58413. return this.subMaterials[index];
  58414. };
  58415. MultiMaterial.prototype.getActiveTextures = function () {
  58416. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  58417. if (subMaterial) {
  58418. return subMaterial.getActiveTextures();
  58419. }
  58420. else {
  58421. return [];
  58422. }
  58423. }));
  58424. var _a;
  58425. };
  58426. // Methods
  58427. MultiMaterial.prototype.getClassName = function () {
  58428. return "MultiMaterial";
  58429. };
  58430. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  58431. for (var index = 0; index < this.subMaterials.length; index++) {
  58432. var subMaterial = this.subMaterials[index];
  58433. if (subMaterial) {
  58434. if (subMaterial.storeEffectOnSubMeshes) {
  58435. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  58436. return false;
  58437. }
  58438. continue;
  58439. }
  58440. if (!subMaterial.isReady(mesh)) {
  58441. return false;
  58442. }
  58443. }
  58444. }
  58445. return true;
  58446. };
  58447. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  58448. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  58449. for (var index = 0; index < this.subMaterials.length; index++) {
  58450. var subMaterial = null;
  58451. var current = this.subMaterials[index];
  58452. if (cloneChildren && current) {
  58453. subMaterial = current.clone(name + "-" + current.name);
  58454. }
  58455. else {
  58456. subMaterial = this.subMaterials[index];
  58457. }
  58458. newMultiMaterial.subMaterials.push(subMaterial);
  58459. }
  58460. return newMultiMaterial;
  58461. };
  58462. MultiMaterial.prototype.serialize = function () {
  58463. var serializationObject = {};
  58464. serializationObject.name = this.name;
  58465. serializationObject.id = this.id;
  58466. if (BABYLON.Tags) {
  58467. serializationObject.tags = BABYLON.Tags.GetTags(this);
  58468. }
  58469. serializationObject.materials = [];
  58470. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  58471. var subMat = this.subMaterials[matIndex];
  58472. if (subMat) {
  58473. serializationObject.materials.push(subMat.id);
  58474. }
  58475. else {
  58476. serializationObject.materials.push(null);
  58477. }
  58478. }
  58479. return serializationObject;
  58480. };
  58481. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58482. var scene = this.getScene();
  58483. if (!scene) {
  58484. return;
  58485. }
  58486. var index = scene.multiMaterials.indexOf(this);
  58487. if (index >= 0) {
  58488. scene.multiMaterials.splice(index, 1);
  58489. }
  58490. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58491. };
  58492. return MultiMaterial;
  58493. }(BABYLON.Material));
  58494. BABYLON.MultiMaterial = MultiMaterial;
  58495. })(BABYLON || (BABYLON = {}));
  58496. //# sourceMappingURL=babylon.multiMaterial.js.map
  58497. var BABYLON;
  58498. (function (BABYLON) {
  58499. var FreeCameraTouchInput = /** @class */ (function () {
  58500. function FreeCameraTouchInput() {
  58501. this._offsetX = null;
  58502. this._offsetY = null;
  58503. this._pointerPressed = new Array();
  58504. this.touchAngularSensibility = 200000.0;
  58505. this.touchMoveSensibility = 250.0;
  58506. }
  58507. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  58508. var _this = this;
  58509. var previousPosition = null;
  58510. if (this._pointerInput === undefined) {
  58511. this._onLostFocus = function (evt) {
  58512. _this._offsetX = null;
  58513. _this._offsetY = null;
  58514. };
  58515. this._pointerInput = function (p, s) {
  58516. var evt = p.event;
  58517. if (evt.pointerType === "mouse") {
  58518. return;
  58519. }
  58520. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  58521. if (!noPreventDefault) {
  58522. evt.preventDefault();
  58523. }
  58524. _this._pointerPressed.push(evt.pointerId);
  58525. if (_this._pointerPressed.length !== 1) {
  58526. return;
  58527. }
  58528. previousPosition = {
  58529. x: evt.clientX,
  58530. y: evt.clientY
  58531. };
  58532. }
  58533. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  58534. if (!noPreventDefault) {
  58535. evt.preventDefault();
  58536. }
  58537. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58538. if (index === -1) {
  58539. return;
  58540. }
  58541. _this._pointerPressed.splice(index, 1);
  58542. if (index != 0) {
  58543. return;
  58544. }
  58545. previousPosition = null;
  58546. _this._offsetX = null;
  58547. _this._offsetY = null;
  58548. }
  58549. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  58550. if (!noPreventDefault) {
  58551. evt.preventDefault();
  58552. }
  58553. if (!previousPosition) {
  58554. return;
  58555. }
  58556. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58557. if (index != 0) {
  58558. return;
  58559. }
  58560. _this._offsetX = evt.clientX - previousPosition.x;
  58561. _this._offsetY = -(evt.clientY - previousPosition.y);
  58562. }
  58563. };
  58564. }
  58565. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  58566. if (this._onLostFocus) {
  58567. element.addEventListener("blur", this._onLostFocus);
  58568. }
  58569. };
  58570. FreeCameraTouchInput.prototype.detachControl = function (element) {
  58571. if (this._pointerInput && element) {
  58572. if (this._observer) {
  58573. this.camera.getScene().onPointerObservable.remove(this._observer);
  58574. this._observer = null;
  58575. }
  58576. if (this._onLostFocus) {
  58577. element.removeEventListener("blur", this._onLostFocus);
  58578. this._onLostFocus = null;
  58579. }
  58580. this._pointerPressed = [];
  58581. this._offsetX = null;
  58582. this._offsetY = null;
  58583. }
  58584. };
  58585. FreeCameraTouchInput.prototype.checkInputs = function () {
  58586. if (this._offsetX && this._offsetY) {
  58587. var camera = this.camera;
  58588. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  58589. if (this._pointerPressed.length > 1) {
  58590. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  58591. }
  58592. else {
  58593. var speed = camera._computeLocalCameraSpeed();
  58594. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  58595. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  58596. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  58597. }
  58598. }
  58599. };
  58600. FreeCameraTouchInput.prototype.getClassName = function () {
  58601. return "FreeCameraTouchInput";
  58602. };
  58603. FreeCameraTouchInput.prototype.getSimpleName = function () {
  58604. return "touch";
  58605. };
  58606. __decorate([
  58607. BABYLON.serialize()
  58608. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  58609. __decorate([
  58610. BABYLON.serialize()
  58611. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  58612. return FreeCameraTouchInput;
  58613. }());
  58614. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  58615. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  58616. })(BABYLON || (BABYLON = {}));
  58617. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  58618. var BABYLON;
  58619. (function (BABYLON) {
  58620. // We're mainly based on the logic defined into the FreeCamera code
  58621. var TouchCamera = /** @class */ (function (_super) {
  58622. __extends(TouchCamera, _super);
  58623. //-- end properties for backward compatibility for inputs
  58624. function TouchCamera(name, position, scene) {
  58625. var _this = _super.call(this, name, position, scene) || this;
  58626. _this.inputs.addTouch();
  58627. _this._setupInputs();
  58628. return _this;
  58629. }
  58630. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  58631. //-- Begin properties for backward compatibility for inputs
  58632. get: function () {
  58633. var touch = this.inputs.attached["touch"];
  58634. if (touch)
  58635. return touch.touchAngularSensibility;
  58636. return 0;
  58637. },
  58638. set: function (value) {
  58639. var touch = this.inputs.attached["touch"];
  58640. if (touch)
  58641. touch.touchAngularSensibility = value;
  58642. },
  58643. enumerable: true,
  58644. configurable: true
  58645. });
  58646. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  58647. get: function () {
  58648. var touch = this.inputs.attached["touch"];
  58649. if (touch)
  58650. return touch.touchMoveSensibility;
  58651. return 0;
  58652. },
  58653. set: function (value) {
  58654. var touch = this.inputs.attached["touch"];
  58655. if (touch)
  58656. touch.touchMoveSensibility = value;
  58657. },
  58658. enumerable: true,
  58659. configurable: true
  58660. });
  58661. TouchCamera.prototype.getClassName = function () {
  58662. return "TouchCamera";
  58663. };
  58664. TouchCamera.prototype._setupInputs = function () {
  58665. var mouse = this.inputs.attached["mouse"];
  58666. if (mouse) {
  58667. mouse.touchEnabled = false;
  58668. }
  58669. };
  58670. return TouchCamera;
  58671. }(BABYLON.FreeCamera));
  58672. BABYLON.TouchCamera = TouchCamera;
  58673. })(BABYLON || (BABYLON = {}));
  58674. //# sourceMappingURL=babylon.touchCamera.js.map
  58675. var BABYLON;
  58676. (function (BABYLON) {
  58677. var ProceduralTexture = /** @class */ (function (_super) {
  58678. __extends(ProceduralTexture, _super);
  58679. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  58680. if (fallbackTexture === void 0) { fallbackTexture = null; }
  58681. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58682. if (isCube === void 0) { isCube = false; }
  58683. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58684. _this.isCube = isCube;
  58685. _this.isEnabled = true;
  58686. _this._currentRefreshId = -1;
  58687. _this._refreshRate = 1;
  58688. _this._vertexBuffers = {};
  58689. _this._uniforms = new Array();
  58690. _this._samplers = new Array();
  58691. _this._textures = {};
  58692. _this._floats = {};
  58693. _this._floatsArrays = {};
  58694. _this._colors3 = {};
  58695. _this._colors4 = {};
  58696. _this._vectors2 = {};
  58697. _this._vectors3 = {};
  58698. _this._matrices = {};
  58699. _this._fallbackTextureUsed = false;
  58700. scene._proceduralTextures.push(_this);
  58701. _this._engine = scene.getEngine();
  58702. _this.name = name;
  58703. _this.isRenderTarget = true;
  58704. _this._size = size;
  58705. _this._generateMipMaps = generateMipMaps;
  58706. _this.setFragment(fragment);
  58707. _this._fallbackTexture = fallbackTexture;
  58708. if (isCube) {
  58709. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  58710. _this.setFloat("face", 0);
  58711. }
  58712. else {
  58713. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  58714. }
  58715. // VBO
  58716. var vertices = [];
  58717. vertices.push(1, 1);
  58718. vertices.push(-1, 1);
  58719. vertices.push(-1, -1);
  58720. vertices.push(1, -1);
  58721. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  58722. _this._createIndexBuffer();
  58723. return _this;
  58724. }
  58725. ProceduralTexture.prototype._createIndexBuffer = function () {
  58726. var engine = this._engine;
  58727. // Indices
  58728. var indices = [];
  58729. indices.push(0);
  58730. indices.push(1);
  58731. indices.push(2);
  58732. indices.push(0);
  58733. indices.push(2);
  58734. indices.push(3);
  58735. this._indexBuffer = engine.createIndexBuffer(indices);
  58736. };
  58737. ProceduralTexture.prototype._rebuild = function () {
  58738. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58739. if (vb) {
  58740. vb._rebuild();
  58741. }
  58742. this._createIndexBuffer();
  58743. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58744. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58745. }
  58746. };
  58747. ProceduralTexture.prototype.reset = function () {
  58748. if (this._effect === undefined) {
  58749. return;
  58750. }
  58751. var engine = this._engine;
  58752. engine._releaseEffect(this._effect);
  58753. };
  58754. ProceduralTexture.prototype.isReady = function () {
  58755. var _this = this;
  58756. var engine = this._engine;
  58757. var shaders;
  58758. if (!this._fragment) {
  58759. return false;
  58760. }
  58761. if (this._fallbackTextureUsed) {
  58762. return true;
  58763. }
  58764. if (this._fragment.fragmentElement !== undefined) {
  58765. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  58766. }
  58767. else {
  58768. shaders = { vertex: "procedural", fragment: this._fragment };
  58769. }
  58770. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  58771. _this.releaseInternalTexture();
  58772. if (_this._fallbackTexture) {
  58773. _this._texture = _this._fallbackTexture._texture;
  58774. if (_this._texture) {
  58775. _this._texture.incrementReferences();
  58776. }
  58777. }
  58778. _this._fallbackTextureUsed = true;
  58779. });
  58780. return this._effect.isReady();
  58781. };
  58782. ProceduralTexture.prototype.resetRefreshCounter = function () {
  58783. this._currentRefreshId = -1;
  58784. };
  58785. ProceduralTexture.prototype.setFragment = function (fragment) {
  58786. this._fragment = fragment;
  58787. };
  58788. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  58789. get: function () {
  58790. return this._refreshRate;
  58791. },
  58792. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58793. set: function (value) {
  58794. this._refreshRate = value;
  58795. this.resetRefreshCounter();
  58796. },
  58797. enumerable: true,
  58798. configurable: true
  58799. });
  58800. ProceduralTexture.prototype._shouldRender = function () {
  58801. if (!this.isEnabled || !this.isReady() || !this._texture) {
  58802. return false;
  58803. }
  58804. if (this._fallbackTextureUsed) {
  58805. return false;
  58806. }
  58807. if (this._currentRefreshId === -1) {
  58808. this._currentRefreshId = 1;
  58809. return true;
  58810. }
  58811. if (this.refreshRate === this._currentRefreshId) {
  58812. this._currentRefreshId = 1;
  58813. return true;
  58814. }
  58815. this._currentRefreshId++;
  58816. return false;
  58817. };
  58818. ProceduralTexture.prototype.getRenderSize = function () {
  58819. return this._size;
  58820. };
  58821. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  58822. if (this._fallbackTextureUsed) {
  58823. return;
  58824. }
  58825. this.releaseInternalTexture();
  58826. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  58827. };
  58828. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  58829. if (this._uniforms.indexOf(uniformName) === -1) {
  58830. this._uniforms.push(uniformName);
  58831. }
  58832. };
  58833. ProceduralTexture.prototype.setTexture = function (name, texture) {
  58834. if (this._samplers.indexOf(name) === -1) {
  58835. this._samplers.push(name);
  58836. }
  58837. this._textures[name] = texture;
  58838. return this;
  58839. };
  58840. ProceduralTexture.prototype.setFloat = function (name, value) {
  58841. this._checkUniform(name);
  58842. this._floats[name] = value;
  58843. return this;
  58844. };
  58845. ProceduralTexture.prototype.setFloats = function (name, value) {
  58846. this._checkUniform(name);
  58847. this._floatsArrays[name] = value;
  58848. return this;
  58849. };
  58850. ProceduralTexture.prototype.setColor3 = function (name, value) {
  58851. this._checkUniform(name);
  58852. this._colors3[name] = value;
  58853. return this;
  58854. };
  58855. ProceduralTexture.prototype.setColor4 = function (name, value) {
  58856. this._checkUniform(name);
  58857. this._colors4[name] = value;
  58858. return this;
  58859. };
  58860. ProceduralTexture.prototype.setVector2 = function (name, value) {
  58861. this._checkUniform(name);
  58862. this._vectors2[name] = value;
  58863. return this;
  58864. };
  58865. ProceduralTexture.prototype.setVector3 = function (name, value) {
  58866. this._checkUniform(name);
  58867. this._vectors3[name] = value;
  58868. return this;
  58869. };
  58870. ProceduralTexture.prototype.setMatrix = function (name, value) {
  58871. this._checkUniform(name);
  58872. this._matrices[name] = value;
  58873. return this;
  58874. };
  58875. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  58876. var scene = this.getScene();
  58877. if (!scene) {
  58878. return;
  58879. }
  58880. var engine = this._engine;
  58881. // Render
  58882. engine.enableEffect(this._effect);
  58883. engine.setState(false);
  58884. // Texture
  58885. for (var name in this._textures) {
  58886. this._effect.setTexture(name, this._textures[name]);
  58887. }
  58888. // Float
  58889. for (name in this._floats) {
  58890. this._effect.setFloat(name, this._floats[name]);
  58891. }
  58892. // Floats
  58893. for (name in this._floatsArrays) {
  58894. this._effect.setArray(name, this._floatsArrays[name]);
  58895. }
  58896. // Color3
  58897. for (name in this._colors3) {
  58898. this._effect.setColor3(name, this._colors3[name]);
  58899. }
  58900. // Color4
  58901. for (name in this._colors4) {
  58902. var color = this._colors4[name];
  58903. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58904. }
  58905. // Vector2
  58906. for (name in this._vectors2) {
  58907. this._effect.setVector2(name, this._vectors2[name]);
  58908. }
  58909. // Vector3
  58910. for (name in this._vectors3) {
  58911. this._effect.setVector3(name, this._vectors3[name]);
  58912. }
  58913. // Matrix
  58914. for (name in this._matrices) {
  58915. this._effect.setMatrix(name, this._matrices[name]);
  58916. }
  58917. if (!this._texture) {
  58918. return;
  58919. }
  58920. if (this.isCube) {
  58921. for (var face = 0; face < 6; face++) {
  58922. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  58923. // VBOs
  58924. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58925. this._effect.setFloat("face", face);
  58926. // Clear
  58927. engine.clear(scene.clearColor, true, true, true);
  58928. // Draw order
  58929. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  58930. // Mipmaps
  58931. if (face === 5) {
  58932. engine.generateMipMapsForCubemap(this._texture);
  58933. }
  58934. }
  58935. }
  58936. else {
  58937. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  58938. // VBOs
  58939. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58940. // Clear
  58941. engine.clear(scene.clearColor, true, true, true);
  58942. // Draw order
  58943. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  58944. }
  58945. // Unbind
  58946. engine.unBindFramebuffer(this._texture, this.isCube);
  58947. if (this.onGenerated) {
  58948. this.onGenerated();
  58949. }
  58950. };
  58951. ProceduralTexture.prototype.clone = function () {
  58952. var textureSize = this.getSize();
  58953. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  58954. // Base texture
  58955. newTexture.hasAlpha = this.hasAlpha;
  58956. newTexture.level = this.level;
  58957. // RenderTarget Texture
  58958. newTexture.coordinatesMode = this.coordinatesMode;
  58959. return newTexture;
  58960. };
  58961. ProceduralTexture.prototype.dispose = function () {
  58962. var scene = this.getScene();
  58963. if (!scene) {
  58964. return;
  58965. }
  58966. var index = scene._proceduralTextures.indexOf(this);
  58967. if (index >= 0) {
  58968. scene._proceduralTextures.splice(index, 1);
  58969. }
  58970. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58971. if (vertexBuffer) {
  58972. vertexBuffer.dispose();
  58973. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  58974. }
  58975. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  58976. this._indexBuffer = null;
  58977. }
  58978. _super.prototype.dispose.call(this);
  58979. };
  58980. return ProceduralTexture;
  58981. }(BABYLON.Texture));
  58982. BABYLON.ProceduralTexture = ProceduralTexture;
  58983. })(BABYLON || (BABYLON = {}));
  58984. //# sourceMappingURL=babylon.proceduralTexture.js.map
  58985. var BABYLON;
  58986. (function (BABYLON) {
  58987. var CustomProceduralTexture = /** @class */ (function (_super) {
  58988. __extends(CustomProceduralTexture, _super);
  58989. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  58990. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  58991. _this._animate = true;
  58992. _this._time = 0;
  58993. _this._texturePath = texturePath;
  58994. //Try to load json
  58995. _this.loadJson(texturePath);
  58996. _this.refreshRate = 1;
  58997. return _this;
  58998. }
  58999. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  59000. var _this = this;
  59001. var noConfigFile = function () {
  59002. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  59003. try {
  59004. _this.setFragment(_this._texturePath);
  59005. }
  59006. catch (ex) {
  59007. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  59008. }
  59009. };
  59010. var configFileUrl = jsonUrl + "/config.json";
  59011. var xhr = new XMLHttpRequest();
  59012. xhr.open("GET", configFileUrl, true);
  59013. xhr.addEventListener("load", function () {
  59014. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  59015. try {
  59016. _this._config = JSON.parse(xhr.response);
  59017. _this.updateShaderUniforms();
  59018. _this.updateTextures();
  59019. _this.setFragment(_this._texturePath + "/custom");
  59020. _this._animate = _this._config.animate;
  59021. _this.refreshRate = _this._config.refreshrate;
  59022. }
  59023. catch (ex) {
  59024. noConfigFile();
  59025. }
  59026. }
  59027. else {
  59028. noConfigFile();
  59029. }
  59030. }, false);
  59031. xhr.addEventListener("error", function () {
  59032. noConfigFile();
  59033. }, false);
  59034. try {
  59035. xhr.send();
  59036. }
  59037. catch (ex) {
  59038. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  59039. }
  59040. };
  59041. CustomProceduralTexture.prototype.isReady = function () {
  59042. if (!_super.prototype.isReady.call(this)) {
  59043. return false;
  59044. }
  59045. for (var name in this._textures) {
  59046. var texture = this._textures[name];
  59047. if (!texture.isReady()) {
  59048. return false;
  59049. }
  59050. }
  59051. return true;
  59052. };
  59053. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59054. var scene = this.getScene();
  59055. if (this._animate && scene) {
  59056. this._time += scene.getAnimationRatio() * 0.03;
  59057. this.updateShaderUniforms();
  59058. }
  59059. _super.prototype.render.call(this, useCameraPostProcess);
  59060. };
  59061. CustomProceduralTexture.prototype.updateTextures = function () {
  59062. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  59063. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  59064. }
  59065. };
  59066. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  59067. if (this._config) {
  59068. for (var j = 0; j < this._config.uniforms.length; j++) {
  59069. var uniform = this._config.uniforms[j];
  59070. switch (uniform.type) {
  59071. case "float":
  59072. this.setFloat(uniform.name, uniform.value);
  59073. break;
  59074. case "color3":
  59075. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  59076. break;
  59077. case "color4":
  59078. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  59079. break;
  59080. case "vector2":
  59081. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  59082. break;
  59083. case "vector3":
  59084. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  59085. break;
  59086. }
  59087. }
  59088. }
  59089. this.setFloat("time", this._time);
  59090. };
  59091. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  59092. get: function () {
  59093. return this._animate;
  59094. },
  59095. set: function (value) {
  59096. this._animate = value;
  59097. },
  59098. enumerable: true,
  59099. configurable: true
  59100. });
  59101. return CustomProceduralTexture;
  59102. }(BABYLON.ProceduralTexture));
  59103. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  59104. })(BABYLON || (BABYLON = {}));
  59105. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  59106. var BABYLON;
  59107. (function (BABYLON) {
  59108. var FreeCameraGamepadInput = /** @class */ (function () {
  59109. function FreeCameraGamepadInput() {
  59110. this.gamepadAngularSensibility = 200;
  59111. this.gamepadMoveSensibility = 40;
  59112. // private members
  59113. this._cameraTransform = BABYLON.Matrix.Identity();
  59114. this._deltaTransform = BABYLON.Vector3.Zero();
  59115. this._vector3 = BABYLON.Vector3.Zero();
  59116. this._vector2 = BABYLON.Vector2.Zero();
  59117. }
  59118. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59119. var _this = this;
  59120. var manager = this.camera.getScene().gamepadManager;
  59121. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59122. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59123. // prioritize XBOX gamepads.
  59124. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59125. _this.gamepad = gamepad;
  59126. }
  59127. }
  59128. });
  59129. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59130. if (_this.gamepad === gamepad) {
  59131. _this.gamepad = null;
  59132. }
  59133. });
  59134. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59135. };
  59136. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  59137. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59138. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59139. this.gamepad = null;
  59140. };
  59141. FreeCameraGamepadInput.prototype.checkInputs = function () {
  59142. if (this.gamepad && this.gamepad.leftStick) {
  59143. var camera = this.camera;
  59144. var LSValues = this.gamepad.leftStick;
  59145. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  59146. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59147. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  59148. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  59149. var RSValues = this.gamepad.rightStick;
  59150. if (RSValues) {
  59151. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  59152. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  59153. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  59154. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  59155. }
  59156. else {
  59157. RSValues = { x: 0, y: 0 };
  59158. }
  59159. if (!camera.rotationQuaternion) {
  59160. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  59161. }
  59162. else {
  59163. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  59164. }
  59165. var speed = camera._computeLocalCameraSpeed() * 50.0;
  59166. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  59167. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  59168. camera.cameraDirection.addInPlace(this._deltaTransform);
  59169. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  59170. camera.cameraRotation.addInPlace(this._vector2);
  59171. }
  59172. };
  59173. FreeCameraGamepadInput.prototype.getClassName = function () {
  59174. return "FreeCameraGamepadInput";
  59175. };
  59176. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  59177. return "gamepad";
  59178. };
  59179. __decorate([
  59180. BABYLON.serialize()
  59181. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  59182. __decorate([
  59183. BABYLON.serialize()
  59184. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59185. return FreeCameraGamepadInput;
  59186. }());
  59187. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  59188. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  59189. })(BABYLON || (BABYLON = {}));
  59190. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  59191. var BABYLON;
  59192. (function (BABYLON) {
  59193. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  59194. function ArcRotateCameraGamepadInput() {
  59195. this.gamepadRotationSensibility = 80;
  59196. this.gamepadMoveSensibility = 40;
  59197. }
  59198. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59199. var _this = this;
  59200. var manager = this.camera.getScene().gamepadManager;
  59201. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59202. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59203. // prioritize XBOX gamepads.
  59204. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59205. _this.gamepad = gamepad;
  59206. }
  59207. }
  59208. });
  59209. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59210. if (_this.gamepad === gamepad) {
  59211. _this.gamepad = null;
  59212. }
  59213. });
  59214. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59215. };
  59216. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  59217. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59218. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59219. this.gamepad = null;
  59220. };
  59221. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  59222. if (this.gamepad) {
  59223. var camera = this.camera;
  59224. var RSValues = this.gamepad.rightStick;
  59225. if (RSValues) {
  59226. if (RSValues.x != 0) {
  59227. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  59228. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  59229. camera.inertialAlphaOffset += normalizedRX;
  59230. }
  59231. }
  59232. if (RSValues.y != 0) {
  59233. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  59234. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  59235. camera.inertialBetaOffset += normalizedRY;
  59236. }
  59237. }
  59238. }
  59239. var LSValues = this.gamepad.leftStick;
  59240. if (LSValues && LSValues.y != 0) {
  59241. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59242. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  59243. this.camera.inertialRadiusOffset -= normalizedLY;
  59244. }
  59245. }
  59246. }
  59247. };
  59248. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  59249. return "ArcRotateCameraGamepadInput";
  59250. };
  59251. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  59252. return "gamepad";
  59253. };
  59254. __decorate([
  59255. BABYLON.serialize()
  59256. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  59257. __decorate([
  59258. BABYLON.serialize()
  59259. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59260. return ArcRotateCameraGamepadInput;
  59261. }());
  59262. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  59263. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  59264. })(BABYLON || (BABYLON = {}));
  59265. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  59266. var BABYLON;
  59267. (function (BABYLON) {
  59268. var GamepadManager = /** @class */ (function () {
  59269. function GamepadManager(_scene) {
  59270. var _this = this;
  59271. this._scene = _scene;
  59272. this._babylonGamepads = [];
  59273. this._oneGamepadConnected = false;
  59274. this._isMonitoring = false;
  59275. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  59276. if (!BABYLON.Tools.IsWindowObjectExist()) {
  59277. this._gamepadEventSupported = false;
  59278. }
  59279. else {
  59280. this._gamepadEventSupported = 'GamepadEvent' in window;
  59281. this._gamepadSupport = (navigator.getGamepads ||
  59282. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  59283. }
  59284. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  59285. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  59286. for (var i in _this._babylonGamepads) {
  59287. var gamepad = _this._babylonGamepads[i];
  59288. if (gamepad && gamepad._isConnected) {
  59289. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  59290. }
  59291. }
  59292. });
  59293. this._onGamepadConnectedEvent = function (evt) {
  59294. var gamepad = evt.gamepad;
  59295. if (gamepad.index in _this._babylonGamepads) {
  59296. if (_this._babylonGamepads[gamepad.index].isConnected) {
  59297. return;
  59298. }
  59299. }
  59300. var newGamepad;
  59301. if (_this._babylonGamepads[gamepad.index]) {
  59302. newGamepad = _this._babylonGamepads[gamepad.index];
  59303. newGamepad.browserGamepad = gamepad;
  59304. newGamepad._isConnected = true;
  59305. }
  59306. else {
  59307. newGamepad = _this._addNewGamepad(gamepad);
  59308. }
  59309. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59310. _this._startMonitoringGamepads();
  59311. };
  59312. this._onGamepadDisconnectedEvent = function (evt) {
  59313. var gamepad = evt.gamepad;
  59314. // Remove the gamepad from the list of gamepads to monitor.
  59315. for (var i in _this._babylonGamepads) {
  59316. if (_this._babylonGamepads[i].index === gamepad.index) {
  59317. var disconnectedGamepad = _this._babylonGamepads[i];
  59318. disconnectedGamepad._isConnected = false;
  59319. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  59320. break;
  59321. }
  59322. }
  59323. };
  59324. if (this._gamepadSupport) {
  59325. //first add already-connected gamepads
  59326. this._updateGamepadObjects();
  59327. if (this._babylonGamepads.length) {
  59328. this._startMonitoringGamepads();
  59329. }
  59330. // Checking if the gamepad connected event is supported (like in Firefox)
  59331. if (this._gamepadEventSupported) {
  59332. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  59333. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  59334. }
  59335. else {
  59336. this._startMonitoringGamepads();
  59337. }
  59338. }
  59339. }
  59340. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  59341. get: function () {
  59342. return this._babylonGamepads;
  59343. },
  59344. enumerable: true,
  59345. configurable: true
  59346. });
  59347. GamepadManager.prototype.getGamepadByType = function (type) {
  59348. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  59349. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  59350. var gamepad = _a[_i];
  59351. if (gamepad && gamepad.type === type) {
  59352. return gamepad;
  59353. }
  59354. }
  59355. return null;
  59356. };
  59357. GamepadManager.prototype.dispose = function () {
  59358. if (this._gamepadEventSupported) {
  59359. if (this._onGamepadConnectedEvent) {
  59360. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  59361. }
  59362. if (this._onGamepadDisconnectedEvent) {
  59363. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  59364. }
  59365. this._onGamepadConnectedEvent = null;
  59366. this._onGamepadDisconnectedEvent = null;
  59367. }
  59368. this._babylonGamepads.forEach(function (gamepad) {
  59369. gamepad.dispose();
  59370. });
  59371. this.onGamepadConnectedObservable.clear();
  59372. this.onGamepadDisconnectedObservable.clear();
  59373. this._oneGamepadConnected = false;
  59374. this._stopMonitoringGamepads();
  59375. this._babylonGamepads = [];
  59376. };
  59377. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  59378. if (!this._oneGamepadConnected) {
  59379. this._oneGamepadConnected = true;
  59380. }
  59381. var newGamepad;
  59382. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  59383. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  59384. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  59385. }
  59386. else if (gamepad.pose) {
  59387. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  59388. }
  59389. else {
  59390. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  59391. }
  59392. this._babylonGamepads[newGamepad.index] = newGamepad;
  59393. return newGamepad;
  59394. };
  59395. GamepadManager.prototype._startMonitoringGamepads = function () {
  59396. if (!this._isMonitoring) {
  59397. this._isMonitoring = true;
  59398. //back-comp
  59399. if (!this._scene) {
  59400. this._checkGamepadsStatus();
  59401. }
  59402. }
  59403. };
  59404. GamepadManager.prototype._stopMonitoringGamepads = function () {
  59405. this._isMonitoring = false;
  59406. };
  59407. GamepadManager.prototype._checkGamepadsStatus = function () {
  59408. var _this = this;
  59409. // Hack to be compatible Chrome
  59410. this._updateGamepadObjects();
  59411. for (var i in this._babylonGamepads) {
  59412. var gamepad = this._babylonGamepads[i];
  59413. if (!gamepad || !gamepad.isConnected) {
  59414. continue;
  59415. }
  59416. gamepad.update();
  59417. }
  59418. if (this._isMonitoring && !this._scene) {
  59419. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  59420. }
  59421. };
  59422. // This function is called only on Chrome, which does not properly support
  59423. // connection/disconnection events and forces you to recopy again the gamepad object
  59424. GamepadManager.prototype._updateGamepadObjects = function () {
  59425. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  59426. for (var i = 0; i < gamepads.length; i++) {
  59427. if (gamepads[i]) {
  59428. if (!this._babylonGamepads[gamepads[i].index]) {
  59429. var newGamepad = this._addNewGamepad(gamepads[i]);
  59430. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59431. }
  59432. else {
  59433. // Forced to copy again this object for Chrome for unknown reason
  59434. this._babylonGamepads[i].browserGamepad = gamepads[i];
  59435. if (!this._babylonGamepads[i].isConnected) {
  59436. this._babylonGamepads[i]._isConnected = true;
  59437. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  59438. }
  59439. }
  59440. }
  59441. }
  59442. };
  59443. return GamepadManager;
  59444. }());
  59445. BABYLON.GamepadManager = GamepadManager;
  59446. })(BABYLON || (BABYLON = {}));
  59447. //# sourceMappingURL=babylon.gamepadManager.js.map
  59448. var BABYLON;
  59449. (function (BABYLON) {
  59450. var StickValues = /** @class */ (function () {
  59451. function StickValues(x, y) {
  59452. this.x = x;
  59453. this.y = y;
  59454. }
  59455. return StickValues;
  59456. }());
  59457. BABYLON.StickValues = StickValues;
  59458. var Gamepad = /** @class */ (function () {
  59459. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  59460. if (leftStickX === void 0) { leftStickX = 0; }
  59461. if (leftStickY === void 0) { leftStickY = 1; }
  59462. if (rightStickX === void 0) { rightStickX = 2; }
  59463. if (rightStickY === void 0) { rightStickY = 3; }
  59464. this.id = id;
  59465. this.index = index;
  59466. this.browserGamepad = browserGamepad;
  59467. this._isConnected = true;
  59468. this._invertLeftStickY = false;
  59469. this.type = Gamepad.GAMEPAD;
  59470. this._leftStickAxisX = leftStickX;
  59471. this._leftStickAxisY = leftStickY;
  59472. this._rightStickAxisX = rightStickX;
  59473. this._rightStickAxisY = rightStickY;
  59474. if (this.browserGamepad.axes.length >= 2) {
  59475. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59476. }
  59477. if (this.browserGamepad.axes.length >= 4) {
  59478. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59479. }
  59480. }
  59481. Object.defineProperty(Gamepad.prototype, "isConnected", {
  59482. get: function () {
  59483. return this._isConnected;
  59484. },
  59485. enumerable: true,
  59486. configurable: true
  59487. });
  59488. Gamepad.prototype.onleftstickchanged = function (callback) {
  59489. this._onleftstickchanged = callback;
  59490. };
  59491. Gamepad.prototype.onrightstickchanged = function (callback) {
  59492. this._onrightstickchanged = callback;
  59493. };
  59494. Object.defineProperty(Gamepad.prototype, "leftStick", {
  59495. get: function () {
  59496. return this._leftStick;
  59497. },
  59498. set: function (newValues) {
  59499. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  59500. this._onleftstickchanged(newValues);
  59501. }
  59502. this._leftStick = newValues;
  59503. },
  59504. enumerable: true,
  59505. configurable: true
  59506. });
  59507. Object.defineProperty(Gamepad.prototype, "rightStick", {
  59508. get: function () {
  59509. return this._rightStick;
  59510. },
  59511. set: function (newValues) {
  59512. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  59513. this._onrightstickchanged(newValues);
  59514. }
  59515. this._rightStick = newValues;
  59516. },
  59517. enumerable: true,
  59518. configurable: true
  59519. });
  59520. Gamepad.prototype.update = function () {
  59521. if (this._leftStick) {
  59522. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59523. if (this._invertLeftStickY) {
  59524. this.leftStick.y *= -1;
  59525. }
  59526. }
  59527. if (this._rightStick) {
  59528. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59529. }
  59530. };
  59531. Gamepad.prototype.dispose = function () {
  59532. };
  59533. Gamepad.GAMEPAD = 0;
  59534. Gamepad.GENERIC = 1;
  59535. Gamepad.XBOX = 2;
  59536. Gamepad.POSE_ENABLED = 3;
  59537. return Gamepad;
  59538. }());
  59539. BABYLON.Gamepad = Gamepad;
  59540. var GenericPad = /** @class */ (function (_super) {
  59541. __extends(GenericPad, _super);
  59542. function GenericPad(id, index, browserGamepad) {
  59543. var _this = _super.call(this, id, index, browserGamepad) || this;
  59544. _this.onButtonDownObservable = new BABYLON.Observable();
  59545. _this.onButtonUpObservable = new BABYLON.Observable();
  59546. _this.type = Gamepad.GENERIC;
  59547. _this._buttons = new Array(browserGamepad.buttons.length);
  59548. return _this;
  59549. }
  59550. GenericPad.prototype.onbuttondown = function (callback) {
  59551. this._onbuttondown = callback;
  59552. };
  59553. GenericPad.prototype.onbuttonup = function (callback) {
  59554. this._onbuttonup = callback;
  59555. };
  59556. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  59557. if (newValue !== currentValue) {
  59558. if (newValue === 1) {
  59559. if (this._onbuttondown) {
  59560. this._onbuttondown(buttonIndex);
  59561. }
  59562. this.onButtonDownObservable.notifyObservers(buttonIndex);
  59563. }
  59564. if (newValue === 0) {
  59565. if (this._onbuttonup) {
  59566. this._onbuttonup(buttonIndex);
  59567. }
  59568. this.onButtonUpObservable.notifyObservers(buttonIndex);
  59569. }
  59570. }
  59571. return newValue;
  59572. };
  59573. GenericPad.prototype.update = function () {
  59574. _super.prototype.update.call(this);
  59575. for (var index = 0; index < this._buttons.length; index++) {
  59576. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  59577. }
  59578. };
  59579. GenericPad.prototype.dispose = function () {
  59580. _super.prototype.dispose.call(this);
  59581. this.onButtonDownObservable.clear();
  59582. this.onButtonUpObservable.clear();
  59583. };
  59584. return GenericPad;
  59585. }(Gamepad));
  59586. BABYLON.GenericPad = GenericPad;
  59587. })(BABYLON || (BABYLON = {}));
  59588. //# sourceMappingURL=babylon.gamepad.js.map
  59589. var BABYLON;
  59590. (function (BABYLON) {
  59591. var Xbox360Button;
  59592. (function (Xbox360Button) {
  59593. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  59594. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  59595. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  59596. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  59597. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  59598. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  59599. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  59600. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  59601. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  59602. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  59603. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  59604. var Xbox360Dpad;
  59605. (function (Xbox360Dpad) {
  59606. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  59607. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  59608. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  59609. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  59610. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  59611. var Xbox360Pad = /** @class */ (function (_super) {
  59612. __extends(Xbox360Pad, _super);
  59613. function Xbox360Pad(id, index, gamepad, xboxOne) {
  59614. if (xboxOne === void 0) { xboxOne = false; }
  59615. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  59616. _this._leftTrigger = 0;
  59617. _this._rightTrigger = 0;
  59618. _this.onButtonDownObservable = new BABYLON.Observable();
  59619. _this.onButtonUpObservable = new BABYLON.Observable();
  59620. _this.onPadDownObservable = new BABYLON.Observable();
  59621. _this.onPadUpObservable = new BABYLON.Observable();
  59622. _this._buttonA = 0;
  59623. _this._buttonB = 0;
  59624. _this._buttonX = 0;
  59625. _this._buttonY = 0;
  59626. _this._buttonBack = 0;
  59627. _this._buttonStart = 0;
  59628. _this._buttonLB = 0;
  59629. _this._buttonRB = 0;
  59630. _this._buttonLeftStick = 0;
  59631. _this._buttonRightStick = 0;
  59632. _this._dPadUp = 0;
  59633. _this._dPadDown = 0;
  59634. _this._dPadLeft = 0;
  59635. _this._dPadRight = 0;
  59636. _this._isXboxOnePad = false;
  59637. _this.type = BABYLON.Gamepad.XBOX;
  59638. _this._isXboxOnePad = xboxOne;
  59639. return _this;
  59640. }
  59641. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  59642. this._onlefttriggerchanged = callback;
  59643. };
  59644. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  59645. this._onrighttriggerchanged = callback;
  59646. };
  59647. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  59648. get: function () {
  59649. return this._leftTrigger;
  59650. },
  59651. set: function (newValue) {
  59652. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  59653. this._onlefttriggerchanged(newValue);
  59654. }
  59655. this._leftTrigger = newValue;
  59656. },
  59657. enumerable: true,
  59658. configurable: true
  59659. });
  59660. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  59661. get: function () {
  59662. return this._rightTrigger;
  59663. },
  59664. set: function (newValue) {
  59665. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  59666. this._onrighttriggerchanged(newValue);
  59667. }
  59668. this._rightTrigger = newValue;
  59669. },
  59670. enumerable: true,
  59671. configurable: true
  59672. });
  59673. Xbox360Pad.prototype.onbuttondown = function (callback) {
  59674. this._onbuttondown = callback;
  59675. };
  59676. Xbox360Pad.prototype.onbuttonup = function (callback) {
  59677. this._onbuttonup = callback;
  59678. };
  59679. Xbox360Pad.prototype.ondpaddown = function (callback) {
  59680. this._ondpaddown = callback;
  59681. };
  59682. Xbox360Pad.prototype.ondpadup = function (callback) {
  59683. this._ondpadup = callback;
  59684. };
  59685. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  59686. if (newValue !== currentValue) {
  59687. if (newValue === 1) {
  59688. if (this._onbuttondown) {
  59689. this._onbuttondown(buttonType);
  59690. }
  59691. this.onButtonDownObservable.notifyObservers(buttonType);
  59692. }
  59693. if (newValue === 0) {
  59694. if (this._onbuttonup) {
  59695. this._onbuttonup(buttonType);
  59696. }
  59697. this.onButtonUpObservable.notifyObservers(buttonType);
  59698. }
  59699. }
  59700. return newValue;
  59701. };
  59702. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  59703. if (newValue !== currentValue) {
  59704. if (newValue === 1) {
  59705. if (this._ondpaddown) {
  59706. this._ondpaddown(buttonType);
  59707. }
  59708. this.onPadDownObservable.notifyObservers(buttonType);
  59709. }
  59710. if (newValue === 0) {
  59711. if (this._ondpadup) {
  59712. this._ondpadup(buttonType);
  59713. }
  59714. this.onPadUpObservable.notifyObservers(buttonType);
  59715. }
  59716. }
  59717. return newValue;
  59718. };
  59719. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  59720. get: function () {
  59721. return this._buttonA;
  59722. },
  59723. set: function (value) {
  59724. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  59725. },
  59726. enumerable: true,
  59727. configurable: true
  59728. });
  59729. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  59730. get: function () {
  59731. return this._buttonB;
  59732. },
  59733. set: function (value) {
  59734. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  59735. },
  59736. enumerable: true,
  59737. configurable: true
  59738. });
  59739. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  59740. get: function () {
  59741. return this._buttonX;
  59742. },
  59743. set: function (value) {
  59744. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  59745. },
  59746. enumerable: true,
  59747. configurable: true
  59748. });
  59749. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  59750. get: function () {
  59751. return this._buttonY;
  59752. },
  59753. set: function (value) {
  59754. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  59755. },
  59756. enumerable: true,
  59757. configurable: true
  59758. });
  59759. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  59760. get: function () {
  59761. return this._buttonStart;
  59762. },
  59763. set: function (value) {
  59764. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  59765. },
  59766. enumerable: true,
  59767. configurable: true
  59768. });
  59769. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  59770. get: function () {
  59771. return this._buttonBack;
  59772. },
  59773. set: function (value) {
  59774. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  59775. },
  59776. enumerable: true,
  59777. configurable: true
  59778. });
  59779. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  59780. get: function () {
  59781. return this._buttonLB;
  59782. },
  59783. set: function (value) {
  59784. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  59785. },
  59786. enumerable: true,
  59787. configurable: true
  59788. });
  59789. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  59790. get: function () {
  59791. return this._buttonRB;
  59792. },
  59793. set: function (value) {
  59794. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  59795. },
  59796. enumerable: true,
  59797. configurable: true
  59798. });
  59799. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  59800. get: function () {
  59801. return this._buttonLeftStick;
  59802. },
  59803. set: function (value) {
  59804. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  59805. },
  59806. enumerable: true,
  59807. configurable: true
  59808. });
  59809. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  59810. get: function () {
  59811. return this._buttonRightStick;
  59812. },
  59813. set: function (value) {
  59814. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  59815. },
  59816. enumerable: true,
  59817. configurable: true
  59818. });
  59819. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  59820. get: function () {
  59821. return this._dPadUp;
  59822. },
  59823. set: function (value) {
  59824. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  59825. },
  59826. enumerable: true,
  59827. configurable: true
  59828. });
  59829. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  59830. get: function () {
  59831. return this._dPadDown;
  59832. },
  59833. set: function (value) {
  59834. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  59835. },
  59836. enumerable: true,
  59837. configurable: true
  59838. });
  59839. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  59840. get: function () {
  59841. return this._dPadLeft;
  59842. },
  59843. set: function (value) {
  59844. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  59845. },
  59846. enumerable: true,
  59847. configurable: true
  59848. });
  59849. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  59850. get: function () {
  59851. return this._dPadRight;
  59852. },
  59853. set: function (value) {
  59854. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  59855. },
  59856. enumerable: true,
  59857. configurable: true
  59858. });
  59859. Xbox360Pad.prototype.update = function () {
  59860. _super.prototype.update.call(this);
  59861. if (this._isXboxOnePad) {
  59862. this.buttonA = this.browserGamepad.buttons[0].value;
  59863. this.buttonB = this.browserGamepad.buttons[1].value;
  59864. this.buttonX = this.browserGamepad.buttons[2].value;
  59865. this.buttonY = this.browserGamepad.buttons[3].value;
  59866. this.buttonLB = this.browserGamepad.buttons[4].value;
  59867. this.buttonRB = this.browserGamepad.buttons[5].value;
  59868. this.leftTrigger = this.browserGamepad.axes[2];
  59869. this.rightTrigger = this.browserGamepad.axes[5];
  59870. this.buttonBack = this.browserGamepad.buttons[9].value;
  59871. this.buttonStart = this.browserGamepad.buttons[8].value;
  59872. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  59873. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  59874. this.dPadUp = this.browserGamepad.buttons[11].value;
  59875. this.dPadDown = this.browserGamepad.buttons[12].value;
  59876. this.dPadLeft = this.browserGamepad.buttons[13].value;
  59877. this.dPadRight = this.browserGamepad.buttons[14].value;
  59878. }
  59879. else {
  59880. this.buttonA = this.browserGamepad.buttons[0].value;
  59881. this.buttonB = this.browserGamepad.buttons[1].value;
  59882. this.buttonX = this.browserGamepad.buttons[2].value;
  59883. this.buttonY = this.browserGamepad.buttons[3].value;
  59884. this.buttonLB = this.browserGamepad.buttons[4].value;
  59885. this.buttonRB = this.browserGamepad.buttons[5].value;
  59886. this.leftTrigger = this.browserGamepad.buttons[6].value;
  59887. this.rightTrigger = this.browserGamepad.buttons[7].value;
  59888. this.buttonBack = this.browserGamepad.buttons[8].value;
  59889. this.buttonStart = this.browserGamepad.buttons[9].value;
  59890. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  59891. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  59892. this.dPadUp = this.browserGamepad.buttons[12].value;
  59893. this.dPadDown = this.browserGamepad.buttons[13].value;
  59894. this.dPadLeft = this.browserGamepad.buttons[14].value;
  59895. this.dPadRight = this.browserGamepad.buttons[15].value;
  59896. }
  59897. };
  59898. Xbox360Pad.prototype.dispose = function () {
  59899. _super.prototype.dispose.call(this);
  59900. this.onButtonDownObservable.clear();
  59901. this.onButtonUpObservable.clear();
  59902. this.onPadDownObservable.clear();
  59903. this.onPadUpObservable.clear();
  59904. };
  59905. return Xbox360Pad;
  59906. }(BABYLON.Gamepad));
  59907. BABYLON.Xbox360Pad = Xbox360Pad;
  59908. })(BABYLON || (BABYLON = {}));
  59909. //# sourceMappingURL=babylon.xboxGamepad.js.map
  59910. var BABYLON;
  59911. (function (BABYLON) {
  59912. var PoseEnabledControllerType;
  59913. (function (PoseEnabledControllerType) {
  59914. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  59915. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  59916. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  59917. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  59918. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  59919. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  59920. var PoseEnabledControllerHelper = /** @class */ (function () {
  59921. function PoseEnabledControllerHelper() {
  59922. }
  59923. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  59924. // Oculus Touch
  59925. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  59926. return new BABYLON.OculusTouchController(vrGamepad);
  59927. }
  59928. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  59929. return new BABYLON.WindowsMotionController(vrGamepad);
  59930. }
  59931. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  59932. return new BABYLON.ViveController(vrGamepad);
  59933. }
  59934. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  59935. return new BABYLON.GearVRController(vrGamepad);
  59936. }
  59937. else {
  59938. return new BABYLON.GenericController(vrGamepad);
  59939. }
  59940. };
  59941. return PoseEnabledControllerHelper;
  59942. }());
  59943. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  59944. var PoseEnabledController = /** @class */ (function (_super) {
  59945. __extends(PoseEnabledController, _super);
  59946. function PoseEnabledController(browserGamepad) {
  59947. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  59948. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  59949. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  59950. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  59951. // Represents device position and rotation in babylon space
  59952. _this.devicePosition = BABYLON.Vector3.Zero();
  59953. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  59954. _this.deviceScaleFactor = 1;
  59955. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  59956. _this._deviceToWorld = BABYLON.Matrix.Identity();
  59957. _this._workingMatrix = BABYLON.Matrix.Identity();
  59958. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  59959. _this.controllerType = PoseEnabledControllerType.GENERIC;
  59960. _this.position = BABYLON.Vector3.Zero();
  59961. _this.rotationQuaternion = new BABYLON.Quaternion();
  59962. _this._calculatedPosition = BABYLON.Vector3.Zero();
  59963. _this._calculatedRotation = new BABYLON.Quaternion();
  59964. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  59965. return _this;
  59966. }
  59967. PoseEnabledController.prototype.update = function () {
  59968. _super.prototype.update.call(this);
  59969. var pose = this.browserGamepad.pose;
  59970. this.updateFromDevice(pose);
  59971. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  59972. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  59973. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  59974. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  59975. if (this._mesh) {
  59976. this._mesh.position.copyFrom(this.devicePosition);
  59977. if (this._mesh.rotationQuaternion) {
  59978. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  59979. }
  59980. }
  59981. };
  59982. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  59983. if (poseData) {
  59984. this.rawPose = poseData;
  59985. if (poseData.position) {
  59986. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  59987. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  59988. this._deviceRoomPosition.z *= -1;
  59989. }
  59990. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  59991. this._calculatedPosition.addInPlace(this.position);
  59992. }
  59993. var pose = this.rawPose;
  59994. if (poseData.orientation && pose.orientation) {
  59995. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  59996. if (this._mesh) {
  59997. if (this._mesh.getScene().useRightHandedSystem) {
  59998. this._deviceRoomRotationQuaternion.z *= -1;
  59999. this._deviceRoomRotationQuaternion.w *= -1;
  60000. }
  60001. else {
  60002. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  60003. }
  60004. }
  60005. // if the camera is set, rotate to the camera's rotation
  60006. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  60007. }
  60008. }
  60009. };
  60010. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  60011. if (this._mesh) {
  60012. this._mesh.parent = null;
  60013. }
  60014. this._mesh = mesh;
  60015. if (this._poseControlledCamera) {
  60016. this._mesh.parent = this._poseControlledCamera;
  60017. }
  60018. if (!this._mesh.rotationQuaternion) {
  60019. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  60020. }
  60021. };
  60022. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  60023. this._poseControlledCamera = camera;
  60024. if (this._mesh) {
  60025. this._mesh.parent = this._poseControlledCamera;
  60026. }
  60027. };
  60028. PoseEnabledController.prototype.dispose = function () {
  60029. if (this._mesh) {
  60030. this._mesh.dispose();
  60031. }
  60032. this._mesh = null;
  60033. _super.prototype.dispose.call(this);
  60034. };
  60035. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  60036. get: function () {
  60037. return this._mesh;
  60038. },
  60039. enumerable: true,
  60040. configurable: true
  60041. });
  60042. PoseEnabledController.prototype.getForwardRay = function (length) {
  60043. if (length === void 0) { length = 100; }
  60044. if (!this.mesh) {
  60045. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  60046. }
  60047. var m = this.mesh.getWorldMatrix();
  60048. var origin = m.getTranslation();
  60049. var forward = new BABYLON.Vector3(0, 0, -1);
  60050. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  60051. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  60052. return new BABYLON.Ray(origin, direction, length);
  60053. };
  60054. return PoseEnabledController;
  60055. }(BABYLON.Gamepad));
  60056. BABYLON.PoseEnabledController = PoseEnabledController;
  60057. })(BABYLON || (BABYLON = {}));
  60058. //# sourceMappingURL=babylon.poseEnabledController.js.map
  60059. var BABYLON;
  60060. (function (BABYLON) {
  60061. var WebVRController = /** @class */ (function (_super) {
  60062. __extends(WebVRController, _super);
  60063. function WebVRController(vrGamepad) {
  60064. var _this = _super.call(this, vrGamepad) || this;
  60065. // Observables
  60066. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  60067. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  60068. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  60069. _this.onPadStateChangedObservable = new BABYLON.Observable();
  60070. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  60071. _this.pad = { x: 0, y: 0 };
  60072. // avoid GC, store state in a tmp object
  60073. _this._changes = {
  60074. pressChanged: false,
  60075. touchChanged: false,
  60076. valueChanged: false,
  60077. changed: false
  60078. };
  60079. _this._buttons = new Array(vrGamepad.buttons.length);
  60080. _this.hand = vrGamepad.hand;
  60081. return _this;
  60082. }
  60083. WebVRController.prototype.onButtonStateChange = function (callback) {
  60084. this._onButtonStateChange = callback;
  60085. };
  60086. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  60087. get: function () {
  60088. return this._defaultModel;
  60089. },
  60090. enumerable: true,
  60091. configurable: true
  60092. });
  60093. WebVRController.prototype.update = function () {
  60094. _super.prototype.update.call(this);
  60095. for (var index = 0; index < this._buttons.length; index++) {
  60096. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  60097. }
  60098. ;
  60099. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  60100. this.pad.x = this.leftStick.x;
  60101. this.pad.y = this.leftStick.y;
  60102. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  60103. }
  60104. };
  60105. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  60106. if (!newState) {
  60107. newState = {
  60108. pressed: false,
  60109. touched: false,
  60110. value: 0
  60111. };
  60112. }
  60113. if (!currentState) {
  60114. this._buttons[buttonIndex] = {
  60115. pressed: newState.pressed,
  60116. touched: newState.touched,
  60117. value: newState.value
  60118. };
  60119. return;
  60120. }
  60121. this._checkChanges(newState, currentState);
  60122. if (this._changes.changed) {
  60123. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  60124. this.handleButtonChange(buttonIndex, newState, this._changes);
  60125. }
  60126. this._buttons[buttonIndex].pressed = newState.pressed;
  60127. this._buttons[buttonIndex].touched = newState.touched;
  60128. // oculus triggers are never 0, thou not touched.
  60129. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  60130. };
  60131. WebVRController.prototype._checkChanges = function (newState, currentState) {
  60132. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  60133. this._changes.touchChanged = newState.touched !== currentState.touched;
  60134. this._changes.valueChanged = newState.value !== currentState.value;
  60135. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  60136. return this._changes;
  60137. };
  60138. WebVRController.prototype.dispose = function () {
  60139. _super.prototype.dispose.call(this);
  60140. this.onTriggerStateChangedObservable.clear();
  60141. this.onMainButtonStateChangedObservable.clear();
  60142. this.onSecondaryButtonStateChangedObservable.clear();
  60143. this.onPadStateChangedObservable.clear();
  60144. this.onPadValuesChangedObservable.clear();
  60145. };
  60146. return WebVRController;
  60147. }(BABYLON.PoseEnabledController));
  60148. BABYLON.WebVRController = WebVRController;
  60149. })(BABYLON || (BABYLON = {}));
  60150. //# sourceMappingURL=babylon.webVRController.js.map
  60151. var BABYLON;
  60152. (function (BABYLON) {
  60153. var OculusTouchController = /** @class */ (function (_super) {
  60154. __extends(OculusTouchController, _super);
  60155. function OculusTouchController(vrGamepad) {
  60156. var _this = _super.call(this, vrGamepad) || this;
  60157. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  60158. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  60159. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  60160. return _this;
  60161. }
  60162. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60163. var _this = this;
  60164. var meshName;
  60165. // Hand
  60166. if (this.hand === 'left') {
  60167. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  60168. }
  60169. else {
  60170. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  60171. }
  60172. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  60173. /*
  60174. Parent Mesh name: oculus_touch_left
  60175. - body
  60176. - trigger
  60177. - thumbstick
  60178. - grip
  60179. - button_y
  60180. - button_x
  60181. - button_enter
  60182. */
  60183. _this._defaultModel = newMeshes[1];
  60184. _this.attachToMesh(_this._defaultModel);
  60185. if (meshLoaded) {
  60186. meshLoaded(_this._defaultModel);
  60187. }
  60188. });
  60189. };
  60190. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  60191. // helper getters for left and right hand.
  60192. get: function () {
  60193. if (this.hand === 'right') {
  60194. return this.onMainButtonStateChangedObservable;
  60195. }
  60196. else {
  60197. throw new Error('No A button on left hand');
  60198. }
  60199. },
  60200. enumerable: true,
  60201. configurable: true
  60202. });
  60203. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  60204. get: function () {
  60205. if (this.hand === 'right') {
  60206. return this.onSecondaryButtonStateChangedObservable;
  60207. }
  60208. else {
  60209. throw new Error('No B button on left hand');
  60210. }
  60211. },
  60212. enumerable: true,
  60213. configurable: true
  60214. });
  60215. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  60216. get: function () {
  60217. if (this.hand === 'left') {
  60218. return this.onMainButtonStateChangedObservable;
  60219. }
  60220. else {
  60221. throw new Error('No X button on right hand');
  60222. }
  60223. },
  60224. enumerable: true,
  60225. configurable: true
  60226. });
  60227. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  60228. get: function () {
  60229. if (this.hand === 'left') {
  60230. return this.onSecondaryButtonStateChangedObservable;
  60231. }
  60232. else {
  60233. throw new Error('No Y button on right hand');
  60234. }
  60235. },
  60236. enumerable: true,
  60237. configurable: true
  60238. });
  60239. /*
  60240. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  60241. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  60242. 2) secondary trigger (same)
  60243. 3) A (right) X (left), touch, pressed = value
  60244. 4) B / Y
  60245. 5) thumb rest
  60246. */
  60247. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60248. var notifyObject = state; //{ state: state, changes: changes };
  60249. var triggerDirection = this.hand === 'right' ? -1 : 1;
  60250. switch (buttonIdx) {
  60251. case 0:
  60252. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60253. return;
  60254. case 1:// index trigger
  60255. if (this._defaultModel) {
  60256. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  60257. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  60258. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  60259. }
  60260. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60261. return;
  60262. case 2:// secondary trigger
  60263. if (this._defaultModel) {
  60264. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  60265. }
  60266. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  60267. return;
  60268. case 3:
  60269. if (this._defaultModel) {
  60270. if (notifyObject.pressed) {
  60271. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  60272. }
  60273. else {
  60274. (this._defaultModel.getChildren()[1]).position.y = 0;
  60275. }
  60276. }
  60277. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60278. return;
  60279. case 4:
  60280. if (this._defaultModel) {
  60281. if (notifyObject.pressed) {
  60282. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60283. }
  60284. else {
  60285. (this._defaultModel.getChildren()[2]).position.y = 0;
  60286. }
  60287. }
  60288. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60289. return;
  60290. case 5:
  60291. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  60292. return;
  60293. }
  60294. };
  60295. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  60296. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  60297. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  60298. return OculusTouchController;
  60299. }(BABYLON.WebVRController));
  60300. BABYLON.OculusTouchController = OculusTouchController;
  60301. })(BABYLON || (BABYLON = {}));
  60302. //# sourceMappingURL=babylon.oculusTouchController.js.map
  60303. var BABYLON;
  60304. (function (BABYLON) {
  60305. var ViveController = /** @class */ (function (_super) {
  60306. __extends(ViveController, _super);
  60307. function ViveController(vrGamepad) {
  60308. var _this = _super.call(this, vrGamepad) || this;
  60309. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  60310. _this._invertLeftStickY = true;
  60311. return _this;
  60312. }
  60313. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60314. var _this = this;
  60315. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  60316. /*
  60317. Parent Mesh name: ViveWand
  60318. - body
  60319. - r_gripper
  60320. - l_gripper
  60321. - menu_button
  60322. - system_button
  60323. - trackpad
  60324. - trigger
  60325. - LED
  60326. */
  60327. _this._defaultModel = newMeshes[1];
  60328. _this.attachToMesh(_this._defaultModel);
  60329. if (meshLoaded) {
  60330. meshLoaded(_this._defaultModel);
  60331. }
  60332. });
  60333. };
  60334. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  60335. get: function () {
  60336. return this.onMainButtonStateChangedObservable;
  60337. },
  60338. enumerable: true,
  60339. configurable: true
  60340. });
  60341. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  60342. get: function () {
  60343. return this.onMainButtonStateChangedObservable;
  60344. },
  60345. enumerable: true,
  60346. configurable: true
  60347. });
  60348. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  60349. get: function () {
  60350. return this.onSecondaryButtonStateChangedObservable;
  60351. },
  60352. enumerable: true,
  60353. configurable: true
  60354. });
  60355. /**
  60356. * Vive mapping:
  60357. * 0: touchpad
  60358. * 1: trigger
  60359. * 2: left AND right buttons
  60360. * 3: menu button
  60361. */
  60362. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60363. var notifyObject = state; //{ state: state, changes: changes };
  60364. switch (buttonIdx) {
  60365. case 0:
  60366. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60367. return;
  60368. case 1:// index trigger
  60369. if (this._defaultModel) {
  60370. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  60371. }
  60372. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60373. return;
  60374. case 2:// left AND right button
  60375. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60376. return;
  60377. case 3:
  60378. if (this._defaultModel) {
  60379. if (notifyObject.pressed) {
  60380. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60381. }
  60382. else {
  60383. (this._defaultModel.getChildren()[2]).position.y = 0;
  60384. }
  60385. }
  60386. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60387. return;
  60388. }
  60389. };
  60390. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  60391. ViveController.MODEL_FILENAME = 'wand.babylon';
  60392. return ViveController;
  60393. }(BABYLON.WebVRController));
  60394. BABYLON.ViveController = ViveController;
  60395. })(BABYLON || (BABYLON = {}));
  60396. //# sourceMappingURL=babylon.viveController.js.map
  60397. var BABYLON;
  60398. (function (BABYLON) {
  60399. var GenericController = /** @class */ (function (_super) {
  60400. __extends(GenericController, _super);
  60401. function GenericController(vrGamepad) {
  60402. return _super.call(this, vrGamepad) || this;
  60403. }
  60404. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60405. var _this = this;
  60406. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  60407. _this._defaultModel = newMeshes[1];
  60408. _this.attachToMesh(_this._defaultModel);
  60409. if (meshLoaded) {
  60410. meshLoaded(_this._defaultModel);
  60411. }
  60412. });
  60413. };
  60414. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60415. console.log("Button id: " + buttonIdx + "state: ");
  60416. console.dir(state);
  60417. };
  60418. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60419. GenericController.MODEL_FILENAME = 'generic.babylon';
  60420. return GenericController;
  60421. }(BABYLON.WebVRController));
  60422. BABYLON.GenericController = GenericController;
  60423. })(BABYLON || (BABYLON = {}));
  60424. //# sourceMappingURL=babylon.genericController.js.map
  60425. var BABYLON;
  60426. (function (BABYLON) {
  60427. var LoadedMeshInfo = /** @class */ (function () {
  60428. function LoadedMeshInfo() {
  60429. this.buttonMeshes = {};
  60430. this.axisMeshes = {};
  60431. }
  60432. return LoadedMeshInfo;
  60433. }());
  60434. var WindowsMotionController = /** @class */ (function (_super) {
  60435. __extends(WindowsMotionController, _super);
  60436. function WindowsMotionController(vrGamepad) {
  60437. var _this = _super.call(this, vrGamepad) || this;
  60438. _this._mapping = {
  60439. // Semantic button names
  60440. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  60441. // A mapping of the button name to glTF model node name
  60442. // that should be transformed by button value.
  60443. buttonMeshNames: {
  60444. 'trigger': 'SELECT',
  60445. 'menu': 'MENU',
  60446. 'grip': 'GRASP',
  60447. 'thumbstick': 'THUMBSTICK_PRESS',
  60448. 'trackpad': 'TOUCHPAD_PRESS'
  60449. },
  60450. // This mapping is used to translate from the Motion Controller to Babylon semantics
  60451. buttonObservableNames: {
  60452. 'trigger': 'onTriggerStateChangedObservable',
  60453. 'menu': 'onSecondaryButtonStateChangedObservable',
  60454. 'grip': 'onMainButtonStateChangedObservable',
  60455. 'thumbstick': 'onPadStateChangedObservable',
  60456. 'trackpad': 'onTrackpadChangedObservable'
  60457. },
  60458. // A mapping of the axis name to glTF model node name
  60459. // that should be transformed by axis value.
  60460. // This array mirrors the browserGamepad.axes array, such that
  60461. // the mesh corresponding to axis 0 is in this array index 0.
  60462. axisMeshNames: [
  60463. 'THUMBSTICK_X',
  60464. 'THUMBSTICK_Y',
  60465. 'TOUCHPAD_TOUCH_X',
  60466. 'TOUCHPAD_TOUCH_Y'
  60467. ],
  60468. pointingPoseMeshName: 'POINTING_POSE'
  60469. };
  60470. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  60471. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  60472. _this.trackpad = { x: 0, y: 0 };
  60473. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  60474. _this._loadedMeshInfo = null;
  60475. return _this;
  60476. }
  60477. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  60478. get: function () {
  60479. return this.onTriggerStateChangedObservable;
  60480. },
  60481. enumerable: true,
  60482. configurable: true
  60483. });
  60484. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  60485. get: function () {
  60486. return this.onSecondaryButtonStateChangedObservable;
  60487. },
  60488. enumerable: true,
  60489. configurable: true
  60490. });
  60491. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  60492. get: function () {
  60493. return this.onMainButtonStateChangedObservable;
  60494. },
  60495. enumerable: true,
  60496. configurable: true
  60497. });
  60498. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  60499. get: function () {
  60500. return this.onPadStateChangedObservable;
  60501. },
  60502. enumerable: true,
  60503. configurable: true
  60504. });
  60505. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  60506. get: function () {
  60507. return this.onTrackpadChangedObservable;
  60508. },
  60509. enumerable: true,
  60510. configurable: true
  60511. });
  60512. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  60513. get: function () {
  60514. return this.onTrackpadValuesChangedObservable;
  60515. },
  60516. enumerable: true,
  60517. configurable: true
  60518. });
  60519. /**
  60520. * Called once per frame by the engine.
  60521. */
  60522. WindowsMotionController.prototype.update = function () {
  60523. _super.prototype.update.call(this);
  60524. // Only need to animate axes if there is a loaded mesh
  60525. if (this._loadedMeshInfo) {
  60526. if (this.browserGamepad.axes) {
  60527. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  60528. this.trackpad.x = this.browserGamepad["axes"][2];
  60529. this.trackpad.y = this.browserGamepad["axes"][3];
  60530. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  60531. }
  60532. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  60533. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  60534. }
  60535. }
  60536. }
  60537. };
  60538. /**
  60539. * Called once for each button that changed state since the last frame
  60540. * @param buttonIdx Which button index changed
  60541. * @param state New state of the button
  60542. * @param changes Which properties on the state changed since last frame
  60543. */
  60544. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60545. var buttonName = this._mapping.buttons[buttonIdx];
  60546. if (!buttonName) {
  60547. return;
  60548. }
  60549. // Only emit events for buttons that we know how to map from index to name
  60550. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  60551. if (observable) {
  60552. observable.notifyObservers(state);
  60553. }
  60554. this.lerpButtonTransform(buttonName, state.value);
  60555. };
  60556. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  60557. // If there is no loaded mesh, there is nothing to transform.
  60558. if (!this._loadedMeshInfo) {
  60559. return;
  60560. }
  60561. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  60562. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60563. return;
  60564. }
  60565. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  60566. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  60567. };
  60568. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  60569. if (!this._loadedMeshInfo) {
  60570. return;
  60571. }
  60572. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  60573. if (!meshInfo) {
  60574. return;
  60575. }
  60576. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60577. return;
  60578. }
  60579. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  60580. var lerpValue = axisValue * 0.5 + 0.5;
  60581. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  60582. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  60583. };
  60584. /**
  60585. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  60586. * @param scene scene in which to add meshes
  60587. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  60588. */
  60589. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  60590. var _this = this;
  60591. if (forceDefault === void 0) { forceDefault = false; }
  60592. var path;
  60593. var filename;
  60594. // Checking if GLB loader is present
  60595. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  60596. // Determine the device specific folder based on the ID suffix
  60597. var device = 'default';
  60598. if (this.id && !forceDefault) {
  60599. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  60600. device = ((match && match[0]) || device);
  60601. }
  60602. // Hand
  60603. if (this.hand === 'left') {
  60604. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  60605. }
  60606. else {
  60607. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  60608. }
  60609. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  60610. }
  60611. else {
  60612. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  60613. path = BABYLON.GenericController.MODEL_BASE_URL;
  60614. filename = BABYLON.GenericController.MODEL_FILENAME;
  60615. }
  60616. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  60617. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  60618. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  60619. if (!_this._loadedMeshInfo) {
  60620. return;
  60621. }
  60622. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  60623. _this.attachToMesh(_this._defaultModel);
  60624. if (meshLoaded) {
  60625. meshLoaded(_this._defaultModel);
  60626. }
  60627. }, null, function (scene, message) {
  60628. BABYLON.Tools.Log(message);
  60629. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  60630. if (!forceDefault) {
  60631. _this.initControllerMesh(scene, meshLoaded, true);
  60632. }
  60633. });
  60634. };
  60635. /**
  60636. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  60637. * can be transformed by button presses and axes values, based on this._mapping.
  60638. *
  60639. * @param scene scene in which the meshes exist
  60640. * @param meshes list of meshes that make up the controller model to process
  60641. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  60642. */
  60643. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  60644. var loadedMeshInfo = null;
  60645. // Create a new mesh to contain the glTF hierarchy
  60646. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  60647. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  60648. var childMesh = null;
  60649. for (var i = 0; i < meshes.length; i++) {
  60650. var mesh = meshes[i];
  60651. if (!mesh.parent) {
  60652. // Exclude controller meshes from picking results
  60653. mesh.isPickable = false;
  60654. // Handle root node, attach to the new parentMesh
  60655. childMesh = mesh;
  60656. break;
  60657. }
  60658. }
  60659. if (childMesh) {
  60660. childMesh.setParent(parentMesh);
  60661. // Create our mesh info. Note that this method will always return non-null.
  60662. loadedMeshInfo = this.createMeshInfo(parentMesh);
  60663. }
  60664. else {
  60665. BABYLON.Tools.Warn('Could not find root node in model file.');
  60666. }
  60667. return loadedMeshInfo;
  60668. };
  60669. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  60670. var loadedMeshInfo = new LoadedMeshInfo();
  60671. var i;
  60672. loadedMeshInfo.rootNode = rootNode;
  60673. // Reset the caches
  60674. loadedMeshInfo.buttonMeshes = {};
  60675. loadedMeshInfo.axisMeshes = {};
  60676. // Button Meshes
  60677. for (i = 0; i < this._mapping.buttons.length; i++) {
  60678. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  60679. if (!buttonMeshName) {
  60680. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  60681. continue;
  60682. }
  60683. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  60684. if (!buttonMesh) {
  60685. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  60686. continue;
  60687. }
  60688. var buttonMeshInfo = {
  60689. index: i,
  60690. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  60691. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  60692. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  60693. };
  60694. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  60695. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  60696. }
  60697. else {
  60698. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  60699. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  60700. '(VALUE: ' + !!buttonMeshInfo.value +
  60701. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  60702. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  60703. ')');
  60704. }
  60705. }
  60706. // Axis Meshes
  60707. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  60708. var axisMeshName = this._mapping.axisMeshNames[i];
  60709. if (!axisMeshName) {
  60710. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  60711. continue;
  60712. }
  60713. var axisMesh = getChildByName(rootNode, axisMeshName);
  60714. if (!axisMesh) {
  60715. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  60716. continue;
  60717. }
  60718. var axisMeshInfo = {
  60719. index: i,
  60720. value: getImmediateChildByName(axisMesh, 'VALUE'),
  60721. min: getImmediateChildByName(axisMesh, 'MIN'),
  60722. max: getImmediateChildByName(axisMesh, 'MAX')
  60723. };
  60724. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  60725. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  60726. }
  60727. else {
  60728. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  60729. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  60730. '(VALUE: ' + !!axisMeshInfo.value +
  60731. ', MIN: ' + !!axisMeshInfo.min +
  60732. ', MAX:' + !!axisMeshInfo.max +
  60733. ')');
  60734. }
  60735. }
  60736. // Pointing Ray
  60737. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  60738. if (!loadedMeshInfo.pointingPoseNode) {
  60739. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  60740. }
  60741. return loadedMeshInfo;
  60742. // Look through all children recursively. This will return null if no mesh exists with the given name.
  60743. function getChildByName(node, name) {
  60744. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  60745. }
  60746. // Look through only immediate children. This will return null if no mesh exists with the given name.
  60747. function getImmediateChildByName(node, name) {
  60748. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  60749. }
  60750. };
  60751. WindowsMotionController.prototype.getForwardRay = function (length) {
  60752. if (length === void 0) { length = 100; }
  60753. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  60754. return _super.prototype.getForwardRay.call(this, length);
  60755. }
  60756. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  60757. var origin = m.getTranslation();
  60758. var forward = new BABYLON.Vector3(0, 0, -1);
  60759. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  60760. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  60761. return new BABYLON.Ray(origin, direction, length);
  60762. };
  60763. WindowsMotionController.prototype.dispose = function () {
  60764. _super.prototype.dispose.call(this);
  60765. this.onTrackpadChangedObservable.clear();
  60766. };
  60767. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  60768. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  60769. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  60770. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  60771. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  60772. return WindowsMotionController;
  60773. }(BABYLON.WebVRController));
  60774. BABYLON.WindowsMotionController = WindowsMotionController;
  60775. })(BABYLON || (BABYLON = {}));
  60776. //# sourceMappingURL=babylon.windowsMotionController.js.map
  60777. var BABYLON;
  60778. (function (BABYLON) {
  60779. var GearVRController = /** @class */ (function (_super) {
  60780. __extends(GearVRController, _super);
  60781. function GearVRController(vrGamepad) {
  60782. var _this = _super.call(this, vrGamepad) || this;
  60783. _this._buttonIndexToObservableNameMap = [
  60784. 'onTrackpadChangedObservable',
  60785. 'onTriggerStateChangedObservable' // Trigger
  60786. ];
  60787. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  60788. return _this;
  60789. }
  60790. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60791. var _this = this;
  60792. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  60793. _this._defaultModel = newMeshes[1];
  60794. _this.attachToMesh(_this._defaultModel);
  60795. if (meshLoaded) {
  60796. meshLoaded(_this._defaultModel);
  60797. }
  60798. });
  60799. };
  60800. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60801. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  60802. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  60803. // Only emit events for buttons that we know how to map from index to observable
  60804. var observable = this[observableName];
  60805. if (observable) {
  60806. observable.notifyObservers(state);
  60807. }
  60808. }
  60809. };
  60810. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60811. GearVRController.MODEL_FILENAME = 'generic.babylon';
  60812. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  60813. return GearVRController;
  60814. }(BABYLON.WebVRController));
  60815. BABYLON.GearVRController = GearVRController;
  60816. })(BABYLON || (BABYLON = {}));
  60817. //# sourceMappingURL=babylon.gearVRController.js.map
  60818. var BABYLON;
  60819. (function (BABYLON) {
  60820. var FollowCamera = /** @class */ (function (_super) {
  60821. __extends(FollowCamera, _super);
  60822. function FollowCamera(name, position, scene, lockedTarget) {
  60823. if (lockedTarget === void 0) { lockedTarget = null; }
  60824. var _this = _super.call(this, name, position, scene) || this;
  60825. _this.radius = 12;
  60826. _this.rotationOffset = 0;
  60827. _this.heightOffset = 4;
  60828. _this.cameraAcceleration = 0.05;
  60829. _this.maxCameraSpeed = 20;
  60830. _this.lockedTarget = lockedTarget;
  60831. return _this;
  60832. }
  60833. FollowCamera.prototype.getRadians = function (degrees) {
  60834. return degrees * Math.PI / 180;
  60835. };
  60836. FollowCamera.prototype.follow = function (cameraTarget) {
  60837. if (!cameraTarget)
  60838. return;
  60839. var yRotation;
  60840. if (cameraTarget.rotationQuaternion) {
  60841. var rotMatrix = new BABYLON.Matrix();
  60842. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  60843. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  60844. }
  60845. else {
  60846. yRotation = cameraTarget.rotation.y;
  60847. }
  60848. var radians = this.getRadians(this.rotationOffset) + yRotation;
  60849. var targetPosition = cameraTarget.getAbsolutePosition();
  60850. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  60851. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  60852. var dx = targetX - this.position.x;
  60853. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  60854. var dz = (targetZ) - this.position.z;
  60855. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  60856. var vy = dy * this.cameraAcceleration;
  60857. var vz = dz * this.cameraAcceleration * 2;
  60858. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  60859. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60860. }
  60861. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  60862. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60863. }
  60864. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  60865. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60866. }
  60867. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  60868. this.setTarget(targetPosition);
  60869. };
  60870. FollowCamera.prototype._checkInputs = function () {
  60871. _super.prototype._checkInputs.call(this);
  60872. if (this.lockedTarget) {
  60873. this.follow(this.lockedTarget);
  60874. }
  60875. };
  60876. FollowCamera.prototype.getClassName = function () {
  60877. return "FollowCamera";
  60878. };
  60879. __decorate([
  60880. BABYLON.serialize()
  60881. ], FollowCamera.prototype, "radius", void 0);
  60882. __decorate([
  60883. BABYLON.serialize()
  60884. ], FollowCamera.prototype, "rotationOffset", void 0);
  60885. __decorate([
  60886. BABYLON.serialize()
  60887. ], FollowCamera.prototype, "heightOffset", void 0);
  60888. __decorate([
  60889. BABYLON.serialize()
  60890. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  60891. __decorate([
  60892. BABYLON.serialize()
  60893. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  60894. __decorate([
  60895. BABYLON.serializeAsMeshReference("lockedTargetId")
  60896. ], FollowCamera.prototype, "lockedTarget", void 0);
  60897. return FollowCamera;
  60898. }(BABYLON.TargetCamera));
  60899. BABYLON.FollowCamera = FollowCamera;
  60900. var ArcFollowCamera = /** @class */ (function (_super) {
  60901. __extends(ArcFollowCamera, _super);
  60902. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  60903. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  60904. _this.alpha = alpha;
  60905. _this.beta = beta;
  60906. _this.radius = radius;
  60907. _this.target = target;
  60908. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  60909. _this.follow();
  60910. return _this;
  60911. }
  60912. ArcFollowCamera.prototype.follow = function () {
  60913. if (!this.target) {
  60914. return;
  60915. }
  60916. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  60917. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  60918. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  60919. var targetPosition = this.target.getAbsolutePosition();
  60920. this.position = targetPosition.add(this._cartesianCoordinates);
  60921. this.setTarget(targetPosition);
  60922. };
  60923. ArcFollowCamera.prototype._checkInputs = function () {
  60924. _super.prototype._checkInputs.call(this);
  60925. this.follow();
  60926. };
  60927. ArcFollowCamera.prototype.getClassName = function () {
  60928. return "ArcFollowCamera";
  60929. };
  60930. return ArcFollowCamera;
  60931. }(BABYLON.TargetCamera));
  60932. BABYLON.ArcFollowCamera = ArcFollowCamera;
  60933. })(BABYLON || (BABYLON = {}));
  60934. //# sourceMappingURL=babylon.followCamera.js.map
  60935. var BABYLON;
  60936. (function (BABYLON) {
  60937. // We're mainly based on the logic defined into the FreeCamera code
  60938. var UniversalCamera = /** @class */ (function (_super) {
  60939. __extends(UniversalCamera, _super);
  60940. //-- end properties for backward compatibility for inputs
  60941. function UniversalCamera(name, position, scene) {
  60942. var _this = _super.call(this, name, position, scene) || this;
  60943. _this.inputs.addGamepad();
  60944. return _this;
  60945. }
  60946. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  60947. //-- Begin properties for backward compatibility for inputs
  60948. get: function () {
  60949. var gamepad = this.inputs.attached["gamepad"];
  60950. if (gamepad)
  60951. return gamepad.gamepadAngularSensibility;
  60952. return 0;
  60953. },
  60954. set: function (value) {
  60955. var gamepad = this.inputs.attached["gamepad"];
  60956. if (gamepad)
  60957. gamepad.gamepadAngularSensibility = value;
  60958. },
  60959. enumerable: true,
  60960. configurable: true
  60961. });
  60962. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  60963. get: function () {
  60964. var gamepad = this.inputs.attached["gamepad"];
  60965. if (gamepad)
  60966. return gamepad.gamepadMoveSensibility;
  60967. return 0;
  60968. },
  60969. set: function (value) {
  60970. var gamepad = this.inputs.attached["gamepad"];
  60971. if (gamepad)
  60972. gamepad.gamepadMoveSensibility = value;
  60973. },
  60974. enumerable: true,
  60975. configurable: true
  60976. });
  60977. UniversalCamera.prototype.getClassName = function () {
  60978. return "UniversalCamera";
  60979. };
  60980. return UniversalCamera;
  60981. }(BABYLON.TouchCamera));
  60982. BABYLON.UniversalCamera = UniversalCamera;
  60983. })(BABYLON || (BABYLON = {}));
  60984. //# sourceMappingURL=babylon.universalCamera.js.map
  60985. var BABYLON;
  60986. (function (BABYLON) {
  60987. // We're mainly based on the logic defined into the FreeCamera code
  60988. var GamepadCamera = /** @class */ (function (_super) {
  60989. __extends(GamepadCamera, _super);
  60990. //-- end properties for backward compatibility for inputs
  60991. function GamepadCamera(name, position, scene) {
  60992. return _super.call(this, name, position, scene) || this;
  60993. }
  60994. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  60995. //-- Begin properties for backward compatibility for inputs
  60996. get: function () {
  60997. var gamepad = this.inputs.attached["gamepad"];
  60998. if (gamepad)
  60999. return gamepad.gamepadAngularSensibility;
  61000. return 0;
  61001. },
  61002. set: function (value) {
  61003. var gamepad = this.inputs.attached["gamepad"];
  61004. if (gamepad)
  61005. gamepad.gamepadAngularSensibility = value;
  61006. },
  61007. enumerable: true,
  61008. configurable: true
  61009. });
  61010. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  61011. get: function () {
  61012. var gamepad = this.inputs.attached["gamepad"];
  61013. if (gamepad)
  61014. return gamepad.gamepadMoveSensibility;
  61015. return 0;
  61016. },
  61017. set: function (value) {
  61018. var gamepad = this.inputs.attached["gamepad"];
  61019. if (gamepad)
  61020. gamepad.gamepadMoveSensibility = value;
  61021. },
  61022. enumerable: true,
  61023. configurable: true
  61024. });
  61025. GamepadCamera.prototype.getClassName = function () {
  61026. return "GamepadCamera";
  61027. };
  61028. return GamepadCamera;
  61029. }(BABYLON.UniversalCamera));
  61030. BABYLON.GamepadCamera = GamepadCamera;
  61031. })(BABYLON || (BABYLON = {}));
  61032. //# sourceMappingURL=babylon.gamepadCamera.js.map
  61033. var BABYLON;
  61034. (function (BABYLON) {
  61035. var PostProcessRenderPipelineManager = /** @class */ (function () {
  61036. function PostProcessRenderPipelineManager() {
  61037. this._renderPipelines = {};
  61038. }
  61039. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  61040. this._renderPipelines[renderPipeline._name] = renderPipeline;
  61041. };
  61042. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  61043. if (unique === void 0) { unique = false; }
  61044. var renderPipeline = this._renderPipelines[renderPipelineName];
  61045. if (!renderPipeline) {
  61046. return;
  61047. }
  61048. renderPipeline._attachCameras(cameras, unique);
  61049. };
  61050. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  61051. var renderPipeline = this._renderPipelines[renderPipelineName];
  61052. if (!renderPipeline) {
  61053. return;
  61054. }
  61055. renderPipeline._detachCameras(cameras);
  61056. };
  61057. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61058. var renderPipeline = this._renderPipelines[renderPipelineName];
  61059. if (!renderPipeline) {
  61060. return;
  61061. }
  61062. renderPipeline._enableEffect(renderEffectName, cameras);
  61063. };
  61064. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61065. var renderPipeline = this._renderPipelines[renderPipelineName];
  61066. if (!renderPipeline) {
  61067. return;
  61068. }
  61069. renderPipeline._disableEffect(renderEffectName, cameras);
  61070. };
  61071. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  61072. var renderPipeline = this._renderPipelines[renderPipelineName];
  61073. if (!renderPipeline) {
  61074. return;
  61075. }
  61076. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  61077. };
  61078. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  61079. var renderPipeline = this._renderPipelines[renderPipelineName];
  61080. if (!renderPipeline) {
  61081. return;
  61082. }
  61083. renderPipeline._disableDisplayOnlyPass(cameras);
  61084. };
  61085. PostProcessRenderPipelineManager.prototype.update = function () {
  61086. for (var renderPipelineName in this._renderPipelines) {
  61087. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61088. var pipeline = this._renderPipelines[renderPipelineName];
  61089. if (!pipeline.isSupported) {
  61090. pipeline.dispose();
  61091. delete this._renderPipelines[renderPipelineName];
  61092. }
  61093. else {
  61094. pipeline._update();
  61095. }
  61096. }
  61097. }
  61098. };
  61099. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  61100. for (var renderPipelineName in this._renderPipelines) {
  61101. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61102. var pipeline = this._renderPipelines[renderPipelineName];
  61103. pipeline._rebuild();
  61104. }
  61105. }
  61106. };
  61107. PostProcessRenderPipelineManager.prototype.dispose = function () {
  61108. for (var renderPipelineName in this._renderPipelines) {
  61109. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61110. var pipeline = this._renderPipelines[renderPipelineName];
  61111. pipeline.dispose();
  61112. }
  61113. }
  61114. };
  61115. return PostProcessRenderPipelineManager;
  61116. }());
  61117. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  61118. })(BABYLON || (BABYLON = {}));
  61119. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  61120. var BABYLON;
  61121. (function (BABYLON) {
  61122. var PostProcessRenderPass = /** @class */ (function () {
  61123. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  61124. this._refCount = 0;
  61125. this._name = name;
  61126. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  61127. this.setRenderList(renderList);
  61128. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  61129. this._renderTexture.onAfterRenderObservable.add(afterRender);
  61130. this._scene = scene;
  61131. this._renderList = renderList;
  61132. }
  61133. // private
  61134. PostProcessRenderPass.prototype._incRefCount = function () {
  61135. if (this._refCount === 0) {
  61136. this._scene.customRenderTargets.push(this._renderTexture);
  61137. }
  61138. return ++this._refCount;
  61139. };
  61140. PostProcessRenderPass.prototype._decRefCount = function () {
  61141. this._refCount--;
  61142. if (this._refCount <= 0) {
  61143. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  61144. }
  61145. return this._refCount;
  61146. };
  61147. PostProcessRenderPass.prototype._update = function () {
  61148. this.setRenderList(this._renderList);
  61149. };
  61150. // public
  61151. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  61152. this._renderTexture.renderList = renderList;
  61153. };
  61154. PostProcessRenderPass.prototype.getRenderTexture = function () {
  61155. return this._renderTexture;
  61156. };
  61157. return PostProcessRenderPass;
  61158. }());
  61159. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  61160. })(BABYLON || (BABYLON = {}));
  61161. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  61162. var BABYLON;
  61163. (function (BABYLON) {
  61164. var PostProcessRenderEffect = /** @class */ (function () {
  61165. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  61166. this._name = name;
  61167. this._singleInstance = singleInstance || true;
  61168. this._getPostProcess = getPostProcess;
  61169. this._cameras = {};
  61170. this._indicesForCamera = {};
  61171. this._postProcesses = {};
  61172. this._renderPasses = {};
  61173. this._renderEffectAsPasses = {};
  61174. }
  61175. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  61176. get: function () {
  61177. for (var index in this._postProcesses) {
  61178. if (!this._postProcesses[index].isSupported) {
  61179. return false;
  61180. }
  61181. }
  61182. return true;
  61183. },
  61184. enumerable: true,
  61185. configurable: true
  61186. });
  61187. PostProcessRenderEffect.prototype._update = function () {
  61188. for (var renderPassName in this._renderPasses) {
  61189. this._renderPasses[renderPassName]._update();
  61190. }
  61191. };
  61192. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  61193. this._renderPasses[renderPass._name] = renderPass;
  61194. this._linkParameters();
  61195. };
  61196. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  61197. delete this._renderPasses[renderPass._name];
  61198. this._linkParameters();
  61199. };
  61200. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  61201. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  61202. this._linkParameters();
  61203. };
  61204. PostProcessRenderEffect.prototype.getPass = function (passName) {
  61205. for (var renderPassName in this._renderPasses) {
  61206. if (renderPassName === passName) {
  61207. return this._renderPasses[passName];
  61208. }
  61209. }
  61210. return null;
  61211. };
  61212. PostProcessRenderEffect.prototype.emptyPasses = function () {
  61213. this._renderPasses = {};
  61214. this._linkParameters();
  61215. };
  61216. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  61217. var cameraKey;
  61218. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61219. if (!cams) {
  61220. return;
  61221. }
  61222. for (var i = 0; i < cams.length; i++) {
  61223. var camera = cams[i];
  61224. var cameraName = camera.name;
  61225. if (this._singleInstance) {
  61226. cameraKey = 0;
  61227. }
  61228. else {
  61229. cameraKey = cameraName;
  61230. }
  61231. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  61232. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  61233. if (!this._indicesForCamera[cameraName]) {
  61234. this._indicesForCamera[cameraName] = [];
  61235. }
  61236. this._indicesForCamera[cameraName].push(index);
  61237. if (!this._cameras[cameraName]) {
  61238. this._cameras[cameraName] = camera;
  61239. }
  61240. for (var passName in this._renderPasses) {
  61241. this._renderPasses[passName]._incRefCount();
  61242. }
  61243. }
  61244. this._linkParameters();
  61245. };
  61246. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  61247. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61248. if (!cams) {
  61249. return;
  61250. }
  61251. for (var i = 0; i < cams.length; i++) {
  61252. var camera = cams[i];
  61253. var cameraName = camera.name;
  61254. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61255. if (this._cameras[cameraName]) {
  61256. //this._indicesForCamera.splice(index, 1);
  61257. this._cameras[cameraName] = null;
  61258. }
  61259. for (var passName in this._renderPasses) {
  61260. this._renderPasses[passName]._decRefCount();
  61261. }
  61262. }
  61263. };
  61264. PostProcessRenderEffect.prototype._enable = function (cameras) {
  61265. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61266. if (!cams) {
  61267. return;
  61268. }
  61269. for (var i = 0; i < cams.length; i++) {
  61270. var camera = cams[i];
  61271. var cameraName = camera.name;
  61272. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  61273. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  61274. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  61275. }
  61276. }
  61277. for (var passName in this._renderPasses) {
  61278. this._renderPasses[passName]._incRefCount();
  61279. }
  61280. }
  61281. };
  61282. PostProcessRenderEffect.prototype._disable = function (cameras) {
  61283. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61284. if (!cams) {
  61285. return;
  61286. }
  61287. for (var i = 0; i < cams.length; i++) {
  61288. var camera = cams[i];
  61289. var cameraName = camera.Name;
  61290. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61291. for (var passName in this._renderPasses) {
  61292. this._renderPasses[passName]._decRefCount();
  61293. }
  61294. }
  61295. };
  61296. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  61297. if (this._singleInstance) {
  61298. return this._postProcesses[0];
  61299. }
  61300. else {
  61301. if (!camera) {
  61302. return null;
  61303. }
  61304. return this._postProcesses[camera.name];
  61305. }
  61306. };
  61307. PostProcessRenderEffect.prototype._linkParameters = function () {
  61308. var _this = this;
  61309. for (var index in this._postProcesses) {
  61310. if (this.applyParameters) {
  61311. this.applyParameters(this._postProcesses[index]);
  61312. }
  61313. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  61314. _this._linkTextures(effect);
  61315. });
  61316. }
  61317. };
  61318. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  61319. for (var renderPassName in this._renderPasses) {
  61320. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  61321. }
  61322. for (var renderEffectName in this._renderEffectAsPasses) {
  61323. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  61324. }
  61325. };
  61326. return PostProcessRenderEffect;
  61327. }());
  61328. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  61329. })(BABYLON || (BABYLON = {}));
  61330. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  61331. var BABYLON;
  61332. (function (BABYLON) {
  61333. var PostProcessRenderPipeline = /** @class */ (function () {
  61334. function PostProcessRenderPipeline(engine, name) {
  61335. this._engine = engine;
  61336. this._name = name;
  61337. this._renderEffects = {};
  61338. this._renderEffectsForIsolatedPass = new Array();
  61339. this._cameras = [];
  61340. }
  61341. PostProcessRenderPipeline.prototype.getClassName = function () {
  61342. return "PostProcessRenderPipeline";
  61343. };
  61344. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  61345. get: function () {
  61346. for (var renderEffectName in this._renderEffects) {
  61347. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61348. if (!this._renderEffects[renderEffectName].isSupported) {
  61349. return false;
  61350. }
  61351. }
  61352. }
  61353. return true;
  61354. },
  61355. enumerable: true,
  61356. configurable: true
  61357. });
  61358. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  61359. this._renderEffects[renderEffect._name] = renderEffect;
  61360. };
  61361. // private
  61362. PostProcessRenderPipeline.prototype._rebuild = function () {
  61363. };
  61364. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  61365. var renderEffects = this._renderEffects[renderEffectName];
  61366. if (!renderEffects) {
  61367. return;
  61368. }
  61369. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61370. };
  61371. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  61372. var renderEffects = this._renderEffects[renderEffectName];
  61373. if (!renderEffects) {
  61374. return;
  61375. }
  61376. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61377. };
  61378. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  61379. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61380. if (!cams) {
  61381. return;
  61382. }
  61383. var indicesToDelete = [];
  61384. var i;
  61385. for (i = 0; i < cams.length; i++) {
  61386. var camera = cams[i];
  61387. var cameraName = camera.name;
  61388. if (this._cameras.indexOf(camera) === -1) {
  61389. this._cameras[cameraName] = camera;
  61390. }
  61391. else if (unique) {
  61392. indicesToDelete.push(i);
  61393. }
  61394. }
  61395. for (i = 0; i < indicesToDelete.length; i++) {
  61396. cameras.splice(indicesToDelete[i], 1);
  61397. }
  61398. for (var renderEffectName in this._renderEffects) {
  61399. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61400. this._renderEffects[renderEffectName]._attachCameras(cams);
  61401. }
  61402. }
  61403. };
  61404. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  61405. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61406. if (!cams) {
  61407. return;
  61408. }
  61409. for (var renderEffectName in this._renderEffects) {
  61410. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61411. this._renderEffects[renderEffectName]._detachCameras(cams);
  61412. }
  61413. }
  61414. for (var i = 0; i < cams.length; i++) {
  61415. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  61416. }
  61417. };
  61418. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  61419. var _this = this;
  61420. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61421. if (!cams) {
  61422. return;
  61423. }
  61424. var pass = null;
  61425. var renderEffectName;
  61426. for (renderEffectName in this._renderEffects) {
  61427. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61428. pass = this._renderEffects[renderEffectName].getPass(passName);
  61429. if (pass != null) {
  61430. break;
  61431. }
  61432. }
  61433. }
  61434. if (pass === null) {
  61435. return;
  61436. }
  61437. for (renderEffectName in this._renderEffects) {
  61438. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61439. this._renderEffects[renderEffectName]._disable(cams);
  61440. }
  61441. }
  61442. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  61443. for (var i = 0; i < cams.length; i++) {
  61444. var camera = cams[i];
  61445. var cameraName = camera.name;
  61446. 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); });
  61447. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  61448. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  61449. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  61450. }
  61451. };
  61452. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  61453. var _this = this;
  61454. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61455. if (!cams) {
  61456. return;
  61457. }
  61458. for (var i = 0; i < cams.length; i++) {
  61459. var camera = cams[i];
  61460. var cameraName = camera.name;
  61461. 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); });
  61462. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  61463. }
  61464. for (var renderEffectName in this._renderEffects) {
  61465. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61466. this._renderEffects[renderEffectName]._enable(cams);
  61467. }
  61468. }
  61469. };
  61470. PostProcessRenderPipeline.prototype._update = function () {
  61471. for (var renderEffectName in this._renderEffects) {
  61472. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61473. this._renderEffects[renderEffectName]._update();
  61474. }
  61475. }
  61476. for (var i = 0; i < this._cameras.length; i++) {
  61477. var cameraName = this._cameras[i].name;
  61478. if (this._renderEffectsForIsolatedPass[cameraName]) {
  61479. this._renderEffectsForIsolatedPass[cameraName]._update();
  61480. }
  61481. }
  61482. };
  61483. PostProcessRenderPipeline.prototype._reset = function () {
  61484. this._renderEffects = {};
  61485. this._renderEffectsForIsolatedPass = new Array();
  61486. };
  61487. PostProcessRenderPipeline.prototype.dispose = function () {
  61488. // Must be implemented by children
  61489. };
  61490. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  61491. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  61492. __decorate([
  61493. BABYLON.serialize()
  61494. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  61495. return PostProcessRenderPipeline;
  61496. }());
  61497. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  61498. })(BABYLON || (BABYLON = {}));
  61499. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  61500. var BABYLON;
  61501. (function (BABYLON) {
  61502. var DepthRenderer = /** @class */ (function () {
  61503. function DepthRenderer(scene, type) {
  61504. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  61505. var _this = this;
  61506. this._scene = scene;
  61507. var engine = scene.getEngine();
  61508. // Render target
  61509. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  61510. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61511. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61512. this._depthMap.refreshRate = 1;
  61513. this._depthMap.renderParticles = false;
  61514. this._depthMap.renderList = null;
  61515. // set default depth value to 1.0 (far away)
  61516. this._depthMap.onClearObservable.add(function (engine) {
  61517. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  61518. });
  61519. // Custom render function
  61520. var renderSubMesh = function (subMesh) {
  61521. var mesh = subMesh.getRenderingMesh();
  61522. var scene = _this._scene;
  61523. var engine = scene.getEngine();
  61524. var material = subMesh.getMaterial();
  61525. if (!material) {
  61526. return;
  61527. }
  61528. // Culling and reverse (right handed system)
  61529. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61530. // Managing instances
  61531. var batch = mesh._getInstancesRenderList(subMesh._id);
  61532. if (batch.mustReturn) {
  61533. return;
  61534. }
  61535. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61536. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  61537. engine.enableEffect(_this._effect);
  61538. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61539. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61540. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  61541. // Alpha test
  61542. if (material && material.needAlphaTesting()) {
  61543. var alphaTexture = material.getAlphaTestTexture();
  61544. if (alphaTexture) {
  61545. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61546. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61547. }
  61548. }
  61549. // Bones
  61550. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61551. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61552. }
  61553. // Draw
  61554. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61555. }
  61556. };
  61557. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61558. var index;
  61559. if (depthOnlySubMeshes.length) {
  61560. engine.setColorWrite(false);
  61561. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61562. renderSubMesh(depthOnlySubMeshes.data[index]);
  61563. }
  61564. engine.setColorWrite(true);
  61565. }
  61566. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61567. renderSubMesh(opaqueSubMeshes.data[index]);
  61568. }
  61569. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61570. renderSubMesh(alphaTestSubMeshes.data[index]);
  61571. }
  61572. };
  61573. }
  61574. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  61575. var material = subMesh.getMaterial();
  61576. if (material.disableDepthWrite) {
  61577. return false;
  61578. }
  61579. var defines = [];
  61580. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61581. var mesh = subMesh.getMesh();
  61582. // Alpha test
  61583. if (material && material.needAlphaTesting()) {
  61584. defines.push("#define ALPHATEST");
  61585. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61586. attribs.push(BABYLON.VertexBuffer.UVKind);
  61587. defines.push("#define UV1");
  61588. }
  61589. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61590. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61591. defines.push("#define UV2");
  61592. }
  61593. }
  61594. // Bones
  61595. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61596. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61597. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61598. if (mesh.numBoneInfluencers > 4) {
  61599. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61600. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61601. }
  61602. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61603. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61604. }
  61605. else {
  61606. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61607. }
  61608. // Instances
  61609. if (useInstances) {
  61610. defines.push("#define INSTANCES");
  61611. attribs.push("world0");
  61612. attribs.push("world1");
  61613. attribs.push("world2");
  61614. attribs.push("world3");
  61615. }
  61616. // Get correct effect
  61617. var join = defines.join("\n");
  61618. if (this._cachedDefines !== join) {
  61619. this._cachedDefines = join;
  61620. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  61621. }
  61622. return this._effect.isReady();
  61623. };
  61624. DepthRenderer.prototype.getDepthMap = function () {
  61625. return this._depthMap;
  61626. };
  61627. // Methods
  61628. DepthRenderer.prototype.dispose = function () {
  61629. this._depthMap.dispose();
  61630. };
  61631. return DepthRenderer;
  61632. }());
  61633. BABYLON.DepthRenderer = DepthRenderer;
  61634. })(BABYLON || (BABYLON = {}));
  61635. //# sourceMappingURL=babylon.depthRenderer.js.map
  61636. var BABYLON;
  61637. (function (BABYLON) {
  61638. var SSAORenderingPipeline = /** @class */ (function (_super) {
  61639. __extends(SSAORenderingPipeline, _super);
  61640. /**
  61641. * @constructor
  61642. * @param {string} name - The rendering pipeline name
  61643. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61644. * @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 }
  61645. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61646. */
  61647. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  61648. var _this = _super.call(this, scene.getEngine(), name) || this;
  61649. // Members
  61650. /**
  61651. * The PassPostProcess id in the pipeline that contains the original scene color
  61652. * @type {string}
  61653. */
  61654. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  61655. /**
  61656. * The SSAO PostProcess id in the pipeline
  61657. * @type {string}
  61658. */
  61659. _this.SSAORenderEffect = "SSAORenderEffect";
  61660. /**
  61661. * The horizontal blur PostProcess id in the pipeline
  61662. * @type {string}
  61663. */
  61664. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  61665. /**
  61666. * The vertical blur PostProcess id in the pipeline
  61667. * @type {string}
  61668. */
  61669. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  61670. /**
  61671. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  61672. * @type {string}
  61673. */
  61674. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  61675. /**
  61676. * The output strength of the SSAO post-process. Default value is 1.0.
  61677. * @type {number}
  61678. */
  61679. _this.totalStrength = 1.0;
  61680. /**
  61681. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  61682. * @type {number}
  61683. */
  61684. _this.radius = 0.0001;
  61685. /**
  61686. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  61687. * Must not be equal to fallOff and superior to fallOff.
  61688. * Default value is 0.975
  61689. * @type {number}
  61690. */
  61691. _this.area = 0.0075;
  61692. /**
  61693. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  61694. * Must not be equal to area and inferior to area.
  61695. * Default value is 0.0
  61696. * @type {number}
  61697. */
  61698. _this.fallOff = 0.000001;
  61699. /**
  61700. * The base color of the SSAO post-process
  61701. * The final result is "base + ssao" between [0, 1]
  61702. * @type {number}
  61703. */
  61704. _this.base = 0.5;
  61705. _this._firstUpdate = true;
  61706. _this._scene = scene;
  61707. // Set up assets
  61708. _this._createRandomTexture();
  61709. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  61710. var ssaoRatio = ratio.ssaoRatio || ratio;
  61711. var combineRatio = ratio.combineRatio || ratio;
  61712. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  61713. _this._createSSAOPostProcess(ssaoRatio);
  61714. _this._createBlurPostProcess(ssaoRatio);
  61715. _this._createSSAOCombinePostProcess(combineRatio);
  61716. // Set up pipeline
  61717. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  61718. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  61719. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  61720. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  61721. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  61722. // Finish
  61723. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61724. if (cameras)
  61725. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  61726. return _this;
  61727. }
  61728. // Public Methods
  61729. /**
  61730. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  61731. */
  61732. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  61733. if (disableDepthRender === void 0) { disableDepthRender = false; }
  61734. for (var i = 0; i < this._scene.cameras.length; i++) {
  61735. var camera = this._scene.cameras[i];
  61736. this._originalColorPostProcess.dispose(camera);
  61737. this._ssaoPostProcess.dispose(camera);
  61738. this._blurHPostProcess.dispose(camera);
  61739. this._blurVPostProcess.dispose(camera);
  61740. this._ssaoCombinePostProcess.dispose(camera);
  61741. }
  61742. this._randomTexture.dispose();
  61743. if (disableDepthRender)
  61744. this._scene.disableDepthRenderer();
  61745. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  61746. _super.prototype.dispose.call(this);
  61747. };
  61748. // Private Methods
  61749. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  61750. var _this = this;
  61751. var size = 16;
  61752. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61753. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61754. this._blurHPostProcess.onActivateObservable.add(function () {
  61755. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  61756. _this._blurHPostProcess.kernel = size * dw;
  61757. });
  61758. this._blurVPostProcess.onActivateObservable.add(function () {
  61759. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  61760. _this._blurVPostProcess.kernel = size * dw;
  61761. });
  61762. };
  61763. SSAORenderingPipeline.prototype._rebuild = function () {
  61764. this._firstUpdate = true;
  61765. _super.prototype._rebuild.call(this);
  61766. };
  61767. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  61768. var _this = this;
  61769. var numSamples = 16;
  61770. var sampleSphere = [
  61771. 0.5381, 0.1856, -0.4319,
  61772. 0.1379, 0.2486, 0.4430,
  61773. 0.3371, 0.5679, -0.0057,
  61774. -0.6999, -0.0451, -0.0019,
  61775. 0.0689, -0.1598, -0.8547,
  61776. 0.0560, 0.0069, -0.1843,
  61777. -0.0146, 0.1402, 0.0762,
  61778. 0.0100, -0.1924, -0.0344,
  61779. -0.3577, -0.5301, -0.4358,
  61780. -0.3169, 0.1063, 0.0158,
  61781. 0.0103, -0.5869, 0.0046,
  61782. -0.0897, -0.4940, 0.3287,
  61783. 0.7119, -0.0154, -0.0918,
  61784. -0.0533, 0.0596, -0.5411,
  61785. 0.0352, -0.0631, 0.5460,
  61786. -0.4776, 0.2847, -0.0271
  61787. ];
  61788. var samplesFactor = 1.0 / numSamples;
  61789. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  61790. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  61791. "area", "fallOff", "base", "range", "viewport"
  61792. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  61793. this._ssaoPostProcess.onApply = function (effect) {
  61794. if (_this._firstUpdate) {
  61795. effect.setArray3("sampleSphere", sampleSphere);
  61796. effect.setFloat("samplesFactor", samplesFactor);
  61797. effect.setFloat("randTextureTiles", 4.0);
  61798. }
  61799. effect.setFloat("totalStrength", _this.totalStrength);
  61800. effect.setFloat("radius", _this.radius);
  61801. effect.setFloat("area", _this.area);
  61802. effect.setFloat("fallOff", _this.fallOff);
  61803. effect.setFloat("base", _this.base);
  61804. effect.setTexture("textureSampler", _this._depthTexture);
  61805. effect.setTexture("randomSampler", _this._randomTexture);
  61806. };
  61807. };
  61808. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  61809. var _this = this;
  61810. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  61811. this._ssaoCombinePostProcess.onApply = function (effect) {
  61812. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  61813. };
  61814. };
  61815. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  61816. var size = 512;
  61817. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61818. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61819. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61820. var context = this._randomTexture.getContext();
  61821. var rand = function (min, max) {
  61822. return Math.random() * (max - min) + min;
  61823. };
  61824. var randVector = BABYLON.Vector3.Zero();
  61825. for (var x = 0; x < size; x++) {
  61826. for (var y = 0; y < size; y++) {
  61827. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  61828. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  61829. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  61830. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  61831. context.fillRect(x, y, 1, 1);
  61832. }
  61833. }
  61834. this._randomTexture.update(false);
  61835. };
  61836. __decorate([
  61837. BABYLON.serialize()
  61838. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  61839. __decorate([
  61840. BABYLON.serialize()
  61841. ], SSAORenderingPipeline.prototype, "radius", void 0);
  61842. __decorate([
  61843. BABYLON.serialize()
  61844. ], SSAORenderingPipeline.prototype, "area", void 0);
  61845. __decorate([
  61846. BABYLON.serialize()
  61847. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  61848. __decorate([
  61849. BABYLON.serialize()
  61850. ], SSAORenderingPipeline.prototype, "base", void 0);
  61851. return SSAORenderingPipeline;
  61852. }(BABYLON.PostProcessRenderPipeline));
  61853. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  61854. })(BABYLON || (BABYLON = {}));
  61855. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  61856. var BABYLON;
  61857. (function (BABYLON) {
  61858. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  61859. __extends(SSAO2RenderingPipeline, _super);
  61860. /**
  61861. * @constructor
  61862. * @param {string} name - The rendering pipeline name
  61863. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61864. * @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 }
  61865. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61866. */
  61867. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  61868. var _this = _super.call(this, scene.getEngine(), name) || this;
  61869. // Members
  61870. /**
  61871. * The PassPostProcess id in the pipeline that contains the original scene color
  61872. * @type {string}
  61873. */
  61874. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  61875. /**
  61876. * The SSAO PostProcess id in the pipeline
  61877. * @type {string}
  61878. */
  61879. _this.SSAORenderEffect = "SSAORenderEffect";
  61880. /**
  61881. * The horizontal blur PostProcess id in the pipeline
  61882. * @type {string}
  61883. */
  61884. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  61885. /**
  61886. * The vertical blur PostProcess id in the pipeline
  61887. * @type {string}
  61888. */
  61889. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  61890. /**
  61891. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  61892. * @type {string}
  61893. */
  61894. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  61895. /**
  61896. * The output strength of the SSAO post-process. Default value is 1.0.
  61897. * @type {number}
  61898. */
  61899. _this.totalStrength = 1.0;
  61900. /**
  61901. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  61902. * @type {number}
  61903. */
  61904. _this.maxZ = 100.0;
  61905. /**
  61906. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  61907. * @type {number}
  61908. */
  61909. _this.minZAspect = 0.2;
  61910. /**
  61911. * Number of samples used for the SSAO calculations. Default value is 8
  61912. * @type {number}
  61913. */
  61914. _this._samples = 8;
  61915. /**
  61916. * Are we using bilateral blur ?
  61917. * @type {boolean}
  61918. */
  61919. _this._expensiveBlur = true;
  61920. /**
  61921. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  61922. * @type {number}
  61923. */
  61924. _this.radius = 2.0;
  61925. /**
  61926. * The base color of the SSAO post-process
  61927. * The final result is "base + ssao" between [0, 1]
  61928. * @type {number}
  61929. */
  61930. _this.base = 0.1;
  61931. _this._firstUpdate = true;
  61932. _this._scene = scene;
  61933. if (!_this.isSupported) {
  61934. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  61935. return _this;
  61936. }
  61937. var ssaoRatio = ratio.ssaoRatio || ratio;
  61938. var blurRatio = ratio.blurRatio || ratio;
  61939. // Set up assets
  61940. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  61941. _this._createRandomTexture();
  61942. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  61943. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  61944. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  61945. _this._createSSAOPostProcess(1.0);
  61946. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  61947. _this._createSSAOCombinePostProcess(blurRatio);
  61948. // Set up pipeline
  61949. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  61950. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  61951. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  61952. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  61953. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  61954. // Finish
  61955. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61956. if (cameras)
  61957. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  61958. return _this;
  61959. }
  61960. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  61961. get: function () {
  61962. return this._samples;
  61963. },
  61964. set: function (n) {
  61965. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  61966. this._samples = n;
  61967. this._sampleSphere = this._generateHemisphere();
  61968. this._firstUpdate = true;
  61969. },
  61970. enumerable: true,
  61971. configurable: true
  61972. });
  61973. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  61974. get: function () {
  61975. return this._expensiveBlur;
  61976. },
  61977. set: function (b) {
  61978. 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"]);
  61979. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  61980. this._expensiveBlur = b;
  61981. this._firstUpdate = true;
  61982. },
  61983. enumerable: true,
  61984. configurable: true
  61985. });
  61986. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  61987. /**
  61988. * Support test.
  61989. * @type {boolean}
  61990. */
  61991. get: function () {
  61992. var engine = BABYLON.Engine.LastCreatedEngine;
  61993. if (!engine) {
  61994. return false;
  61995. }
  61996. return engine.getCaps().drawBuffersExtension;
  61997. },
  61998. enumerable: true,
  61999. configurable: true
  62000. });
  62001. // Public Methods
  62002. /**
  62003. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62004. */
  62005. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  62006. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  62007. for (var i = 0; i < this._scene.cameras.length; i++) {
  62008. var camera = this._scene.cameras[i];
  62009. this._originalColorPostProcess.dispose(camera);
  62010. this._ssaoPostProcess.dispose(camera);
  62011. this._blurHPostProcess.dispose(camera);
  62012. this._blurVPostProcess.dispose(camera);
  62013. this._ssaoCombinePostProcess.dispose(camera);
  62014. }
  62015. this._randomTexture.dispose();
  62016. if (disableGeometryBufferRenderer)
  62017. this._scene.disableGeometryBufferRenderer();
  62018. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62019. _super.prototype.dispose.call(this);
  62020. };
  62021. // Private Methods
  62022. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  62023. var _this = this;
  62024. this._samplerOffsets = [];
  62025. var expensive = this.expensiveBlur;
  62026. for (var i = -8; i < 8; i++) {
  62027. this._samplerOffsets.push(i * 2 + 0.5);
  62028. }
  62029. 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");
  62030. this._blurHPostProcess.onApply = function (effect) {
  62031. if (!_this._scene.activeCamera) {
  62032. return;
  62033. }
  62034. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  62035. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62036. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62037. effect.setFloat("radius", _this.radius);
  62038. effect.setTexture("depthSampler", _this._depthTexture);
  62039. if (_this._firstUpdate) {
  62040. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62041. }
  62042. };
  62043. 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");
  62044. this._blurVPostProcess.onApply = function (effect) {
  62045. if (!_this._scene.activeCamera) {
  62046. return;
  62047. }
  62048. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  62049. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62050. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62051. effect.setFloat("radius", _this.radius);
  62052. effect.setTexture("depthSampler", _this._depthTexture);
  62053. if (_this._firstUpdate) {
  62054. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62055. _this._firstUpdate = false;
  62056. }
  62057. };
  62058. };
  62059. SSAO2RenderingPipeline.prototype._rebuild = function () {
  62060. this._firstUpdate = true;
  62061. _super.prototype._rebuild.call(this);
  62062. };
  62063. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  62064. var numSamples = this.samples;
  62065. var result = [];
  62066. var vector, scale;
  62067. var rand = function (min, max) {
  62068. return Math.random() * (max - min) + min;
  62069. };
  62070. var i = 0;
  62071. while (i < numSamples) {
  62072. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  62073. vector.normalize();
  62074. scale = i / numSamples;
  62075. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  62076. vector.scaleInPlace(scale);
  62077. result.push(vector.x, vector.y, vector.z);
  62078. i++;
  62079. }
  62080. return result;
  62081. };
  62082. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62083. var _this = this;
  62084. var numSamples = this.samples;
  62085. this._sampleSphere = this._generateHemisphere();
  62086. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  62087. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62088. "base", "range", "projection", "near", "far", "texelSize",
  62089. "xViewport", "yViewport", "maxZ", "minZAspect"
  62090. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62091. this._ssaoPostProcess.onApply = function (effect) {
  62092. if (_this._firstUpdate) {
  62093. effect.setArray3("sampleSphere", _this._sampleSphere);
  62094. effect.setFloat("randTextureTiles", 4.0);
  62095. }
  62096. if (!_this._scene.activeCamera) {
  62097. return;
  62098. }
  62099. effect.setFloat("samplesFactor", 1 / _this.samples);
  62100. effect.setFloat("totalStrength", _this.totalStrength);
  62101. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  62102. effect.setFloat("radius", _this.radius);
  62103. effect.setFloat("maxZ", _this.maxZ);
  62104. effect.setFloat("minZAspect", _this.minZAspect);
  62105. effect.setFloat("base", _this.base);
  62106. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62107. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62108. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  62109. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  62110. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  62111. effect.setTexture("textureSampler", _this._depthTexture);
  62112. effect.setTexture("normalSampler", _this._normalTexture);
  62113. effect.setTexture("randomSampler", _this._randomTexture);
  62114. };
  62115. };
  62116. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62117. var _this = this;
  62118. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62119. this._ssaoCombinePostProcess.onApply = function (effect) {
  62120. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62121. };
  62122. };
  62123. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  62124. var size = 512;
  62125. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62126. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62127. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62128. var context = this._randomTexture.getContext();
  62129. var rand = function (min, max) {
  62130. return Math.random() * (max - min) + min;
  62131. };
  62132. var randVector = BABYLON.Vector3.Zero();
  62133. for (var x = 0; x < size; x++) {
  62134. for (var y = 0; y < size; y++) {
  62135. randVector.x = rand(0.0, 1.0);
  62136. randVector.y = rand(0.0, 1.0);
  62137. randVector.z = 0.0;
  62138. randVector.normalize();
  62139. randVector.scaleInPlace(255);
  62140. randVector.x = Math.floor(randVector.x);
  62141. randVector.y = Math.floor(randVector.y);
  62142. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62143. context.fillRect(x, y, 1, 1);
  62144. }
  62145. }
  62146. this._randomTexture.update(false);
  62147. };
  62148. __decorate([
  62149. BABYLON.serialize()
  62150. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  62151. __decorate([
  62152. BABYLON.serialize()
  62153. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  62154. __decorate([
  62155. BABYLON.serialize()
  62156. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  62157. __decorate([
  62158. BABYLON.serialize("samples")
  62159. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  62160. __decorate([
  62161. BABYLON.serialize("expensiveBlur")
  62162. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  62163. __decorate([
  62164. BABYLON.serialize()
  62165. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  62166. __decorate([
  62167. BABYLON.serialize()
  62168. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  62169. return SSAO2RenderingPipeline;
  62170. }(BABYLON.PostProcessRenderPipeline));
  62171. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  62172. })(BABYLON || (BABYLON = {}));
  62173. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  62174. // BABYLON.JS Chromatic Aberration GLSL Shader
  62175. // Author: Olivier Guyot
  62176. // Separates very slightly R, G and B colors on the edges of the screen
  62177. // Inspired by Francois Tarlier & Martins Upitis
  62178. var BABYLON;
  62179. (function (BABYLON) {
  62180. var LensRenderingPipeline = /** @class */ (function (_super) {
  62181. __extends(LensRenderingPipeline, _super);
  62182. /**
  62183. * @constructor
  62184. *
  62185. * Effect parameters are as follow:
  62186. * {
  62187. * chromatic_aberration: number; // from 0 to x (1 for realism)
  62188. * edge_blur: number; // from 0 to x (1 for realism)
  62189. * distortion: number; // from 0 to x (1 for realism)
  62190. * grain_amount: number; // from 0 to 1
  62191. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  62192. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  62193. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  62194. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  62195. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  62196. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  62197. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  62198. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  62199. * }
  62200. * Note: if an effect parameter is unset, effect is disabled
  62201. *
  62202. * @param {string} name - The rendering pipeline name
  62203. * @param {object} parameters - An object containing all parameters (see above)
  62204. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62205. * @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)
  62206. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62207. */
  62208. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  62209. if (ratio === void 0) { ratio = 1.0; }
  62210. var _this = _super.call(this, scene.getEngine(), name) || this;
  62211. // Lens effects can be of the following:
  62212. // - chromatic aberration (slight shift of RGB colors)
  62213. // - blur on the edge of the lens
  62214. // - lens distortion
  62215. // - depth-of-field blur & highlights enhancing
  62216. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  62217. // - grain effect (noise or custom texture)
  62218. // Two additional texture samplers are needed:
  62219. // - depth map (for depth-of-field)
  62220. // - grain texture
  62221. /**
  62222. * The chromatic aberration PostProcess id in the pipeline
  62223. * @type {string}
  62224. */
  62225. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  62226. /**
  62227. * The highlights enhancing PostProcess id in the pipeline
  62228. * @type {string}
  62229. */
  62230. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  62231. /**
  62232. * The depth-of-field PostProcess id in the pipeline
  62233. * @type {string}
  62234. */
  62235. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  62236. _this._scene = scene;
  62237. // Fetch texture samplers
  62238. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62239. if (parameters.grain_texture) {
  62240. _this._grainTexture = parameters.grain_texture;
  62241. }
  62242. else {
  62243. _this._createGrainTexture();
  62244. }
  62245. // save parameters
  62246. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  62247. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  62248. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  62249. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  62250. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  62251. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  62252. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  62253. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  62254. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  62255. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  62256. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  62257. // Create effects
  62258. _this._createChromaticAberrationPostProcess(ratio);
  62259. _this._createHighlightsPostProcess(ratio);
  62260. _this._createDepthOfFieldPostProcess(ratio / 4);
  62261. // Set up pipeline
  62262. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  62263. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  62264. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  62265. if (_this._highlightsGain === -1) {
  62266. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  62267. }
  62268. // Finish
  62269. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62270. if (cameras) {
  62271. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62272. }
  62273. return _this;
  62274. }
  62275. // public methods (self explanatory)
  62276. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  62277. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  62278. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  62279. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  62280. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  62281. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  62282. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  62283. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  62284. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  62285. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  62286. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  62287. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  62288. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  62289. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  62290. };
  62291. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  62292. this._highlightsPostProcess.updateEffect();
  62293. };
  62294. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  62295. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  62296. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  62297. this._highlightsGain = amount;
  62298. };
  62299. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  62300. if (this._highlightsGain === -1) {
  62301. this._highlightsGain = 1.0;
  62302. }
  62303. this._highlightsThreshold = amount;
  62304. };
  62305. LensRenderingPipeline.prototype.disableHighlights = function () {
  62306. this._highlightsGain = -1;
  62307. };
  62308. /**
  62309. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  62310. */
  62311. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62312. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62313. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62314. this._chromaticAberrationPostProcess = null;
  62315. this._highlightsPostProcess = null;
  62316. this._depthOfFieldPostProcess = null;
  62317. this._grainTexture.dispose();
  62318. if (disableDepthRender)
  62319. this._scene.disableDepthRenderer();
  62320. };
  62321. // colors shifting and distortion
  62322. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  62323. var _this = this;
  62324. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  62325. [], // samplers
  62326. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62327. this._chromaticAberrationPostProcess.onApply = function (effect) {
  62328. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  62329. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62330. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62331. };
  62332. };
  62333. // highlights enhancing
  62334. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  62335. var _this = this;
  62336. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  62337. [], // samplers
  62338. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  62339. this._highlightsPostProcess.onApply = function (effect) {
  62340. effect.setFloat('gain', _this._highlightsGain);
  62341. effect.setFloat('threshold', _this._highlightsThreshold);
  62342. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  62343. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62344. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62345. };
  62346. };
  62347. // colors shifting and distortion
  62348. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  62349. var _this = this;
  62350. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  62351. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  62352. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  62353. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62354. this._depthOfFieldPostProcess.onApply = function (effect) {
  62355. effect.setTexture("depthSampler", _this._depthTexture);
  62356. effect.setTexture("grainSampler", _this._grainTexture);
  62357. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  62358. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  62359. effect.setFloat('grain_amount', _this._grainAmount);
  62360. effect.setBool('blur_noise', _this._blurNoise);
  62361. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62362. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62363. effect.setFloat('distortion', _this._distortion);
  62364. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  62365. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  62366. effect.setFloat('aperture', _this._dofAperture);
  62367. effect.setFloat('darken', _this._dofDarken);
  62368. effect.setFloat('edge_blur', _this._edgeBlur);
  62369. effect.setBool('highlights', (_this._highlightsGain !== -1));
  62370. if (_this._scene.activeCamera) {
  62371. effect.setFloat('near', _this._scene.activeCamera.minZ);
  62372. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  62373. }
  62374. };
  62375. };
  62376. // creates a black and white random noise texture, 512x512
  62377. LensRenderingPipeline.prototype._createGrainTexture = function () {
  62378. var size = 512;
  62379. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62380. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62381. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62382. var context = this._grainTexture.getContext();
  62383. var rand = function (min, max) {
  62384. return Math.random() * (max - min) + min;
  62385. };
  62386. var value;
  62387. for (var x = 0; x < size; x++) {
  62388. for (var y = 0; y < size; y++) {
  62389. value = Math.floor(rand(0.42, 0.58) * 255);
  62390. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  62391. context.fillRect(x, y, 1, 1);
  62392. }
  62393. }
  62394. this._grainTexture.update(false);
  62395. };
  62396. return LensRenderingPipeline;
  62397. }(BABYLON.PostProcessRenderPipeline));
  62398. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  62399. })(BABYLON || (BABYLON = {}));
  62400. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  62401. var BABYLON;
  62402. (function (BABYLON) {
  62403. var StandardRenderingPipeline = /** @class */ (function (_super) {
  62404. __extends(StandardRenderingPipeline, _super);
  62405. /**
  62406. * @constructor
  62407. * @param {string} name - The rendering pipeline name
  62408. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62409. * @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)
  62410. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  62411. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62412. */
  62413. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  62414. if (originalPostProcess === void 0) { originalPostProcess = null; }
  62415. var _this = _super.call(this, scene.getEngine(), name) || this;
  62416. _this.downSampleX4PostProcess = null;
  62417. _this.brightPassPostProcess = null;
  62418. _this.blurHPostProcesses = [];
  62419. _this.blurVPostProcesses = [];
  62420. _this.textureAdderPostProcess = null;
  62421. _this.volumetricLightPostProcess = null;
  62422. _this.volumetricLightSmoothXPostProcess = null;
  62423. _this.volumetricLightSmoothYPostProcess = null;
  62424. _this.volumetricLightMergePostProces = null;
  62425. _this.volumetricLightFinalPostProcess = null;
  62426. _this.luminancePostProcess = null;
  62427. _this.luminanceDownSamplePostProcesses = [];
  62428. _this.hdrPostProcess = null;
  62429. _this.textureAdderFinalPostProcess = null;
  62430. _this.lensFlareFinalPostProcess = null;
  62431. _this.hdrFinalPostProcess = null;
  62432. _this.lensFlarePostProcess = null;
  62433. _this.lensFlareComposePostProcess = null;
  62434. _this.motionBlurPostProcess = null;
  62435. _this.depthOfFieldPostProcess = null;
  62436. // Values
  62437. _this.brightThreshold = 1.0;
  62438. _this.blurWidth = 512.0;
  62439. _this.horizontalBlur = false;
  62440. _this.exposure = 1.0;
  62441. _this.lensTexture = null;
  62442. _this.volumetricLightCoefficient = 0.2;
  62443. _this.volumetricLightPower = 4.0;
  62444. _this.volumetricLightBlurScale = 64.0;
  62445. _this.sourceLight = null;
  62446. _this.hdrMinimumLuminance = 1.0;
  62447. _this.hdrDecreaseRate = 0.5;
  62448. _this.hdrIncreaseRate = 0.5;
  62449. _this.lensColorTexture = null;
  62450. _this.lensFlareStrength = 20.0;
  62451. _this.lensFlareGhostDispersal = 1.4;
  62452. _this.lensFlareHaloWidth = 0.7;
  62453. _this.lensFlareDistortionStrength = 16.0;
  62454. _this.lensStarTexture = null;
  62455. _this.lensFlareDirtTexture = null;
  62456. _this.depthOfFieldDistance = 10.0;
  62457. _this.depthOfFieldBlurWidth = 64.0;
  62458. _this.motionStrength = 1.0;
  62459. // IAnimatable
  62460. _this.animations = [];
  62461. _this._currentDepthOfFieldSource = null;
  62462. _this._hdrCurrentLuminance = 1.0;
  62463. // Getters and setters
  62464. _this._bloomEnabled = true;
  62465. _this._depthOfFieldEnabled = false;
  62466. _this._vlsEnabled = false;
  62467. _this._lensFlareEnabled = false;
  62468. _this._hdrEnabled = false;
  62469. _this._motionBlurEnabled = false;
  62470. _this._motionBlurSamples = 64.0;
  62471. _this._volumetricLightStepsCount = 50.0;
  62472. _this._cameras = cameras || [];
  62473. // Initialize
  62474. _this._scene = scene;
  62475. _this._basePostProcess = originalPostProcess;
  62476. _this._ratio = ratio;
  62477. // Misc
  62478. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62479. // Finish
  62480. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62481. _this._buildPipeline();
  62482. return _this;
  62483. }
  62484. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  62485. get: function () {
  62486. return this._bloomEnabled;
  62487. },
  62488. set: function (enabled) {
  62489. if (this._bloomEnabled === enabled) {
  62490. return;
  62491. }
  62492. this._bloomEnabled = enabled;
  62493. this._buildPipeline();
  62494. },
  62495. enumerable: true,
  62496. configurable: true
  62497. });
  62498. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  62499. get: function () {
  62500. return this._depthOfFieldEnabled;
  62501. },
  62502. set: function (enabled) {
  62503. if (this._depthOfFieldEnabled === enabled) {
  62504. return;
  62505. }
  62506. this._depthOfFieldEnabled = enabled;
  62507. this._buildPipeline();
  62508. },
  62509. enumerable: true,
  62510. configurable: true
  62511. });
  62512. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  62513. get: function () {
  62514. return this._lensFlareEnabled;
  62515. },
  62516. set: function (enabled) {
  62517. if (this._lensFlareEnabled === enabled) {
  62518. return;
  62519. }
  62520. this._lensFlareEnabled = enabled;
  62521. this._buildPipeline();
  62522. },
  62523. enumerable: true,
  62524. configurable: true
  62525. });
  62526. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  62527. get: function () {
  62528. return this._hdrEnabled;
  62529. },
  62530. set: function (enabled) {
  62531. if (this._hdrEnabled === enabled) {
  62532. return;
  62533. }
  62534. this._hdrEnabled = enabled;
  62535. this._buildPipeline();
  62536. },
  62537. enumerable: true,
  62538. configurable: true
  62539. });
  62540. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  62541. get: function () {
  62542. return this._vlsEnabled;
  62543. },
  62544. set: function (enabled) {
  62545. if (this._vlsEnabled === enabled) {
  62546. return;
  62547. }
  62548. if (enabled) {
  62549. var geometry = this._scene.enableGeometryBufferRenderer();
  62550. if (!geometry) {
  62551. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  62552. return;
  62553. }
  62554. }
  62555. this._vlsEnabled = enabled;
  62556. this._buildPipeline();
  62557. },
  62558. enumerable: true,
  62559. configurable: true
  62560. });
  62561. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  62562. get: function () {
  62563. return this._motionBlurEnabled;
  62564. },
  62565. set: function (enabled) {
  62566. if (this._motionBlurEnabled === enabled) {
  62567. return;
  62568. }
  62569. this._motionBlurEnabled = enabled;
  62570. this._buildPipeline();
  62571. },
  62572. enumerable: true,
  62573. configurable: true
  62574. });
  62575. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  62576. get: function () {
  62577. return this._volumetricLightStepsCount;
  62578. },
  62579. set: function (count) {
  62580. if (this.volumetricLightPostProcess) {
  62581. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  62582. }
  62583. this._volumetricLightStepsCount = count;
  62584. },
  62585. enumerable: true,
  62586. configurable: true
  62587. });
  62588. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  62589. get: function () {
  62590. return this._motionBlurSamples;
  62591. },
  62592. set: function (samples) {
  62593. if (this.motionBlurPostProcess) {
  62594. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  62595. }
  62596. this._motionBlurSamples = samples;
  62597. },
  62598. enumerable: true,
  62599. configurable: true
  62600. });
  62601. StandardRenderingPipeline.prototype._buildPipeline = function () {
  62602. var _this = this;
  62603. var ratio = this._ratio;
  62604. var scene = this._scene;
  62605. this._disposePostProcesses();
  62606. this._reset();
  62607. // Create pass post-process
  62608. if (!this._basePostProcess) {
  62609. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  62610. this.originalPostProcess.onApply = function (effect) {
  62611. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  62612. };
  62613. }
  62614. else {
  62615. this.originalPostProcess = this._basePostProcess;
  62616. }
  62617. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  62618. this._currentDepthOfFieldSource = this.originalPostProcess;
  62619. if (this._vlsEnabled) {
  62620. // Create volumetric light
  62621. this._createVolumetricLightPostProcess(scene, ratio);
  62622. // Create volumetric light final post-process
  62623. 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);
  62624. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  62625. }
  62626. if (this._bloomEnabled) {
  62627. // Create down sample X4 post-process
  62628. this._createDownSampleX4PostProcess(scene, ratio / 2);
  62629. // Create bright pass post-process
  62630. this._createBrightPassPostProcess(scene, ratio / 2);
  62631. // Create gaussian blur post-processes (down sampling blurs)
  62632. this._createBlurPostProcesses(scene, ratio / 4, 1);
  62633. // Create texture adder post-process
  62634. this._createTextureAdderPostProcess(scene, ratio);
  62635. // Create depth-of-field source post-process
  62636. 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);
  62637. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  62638. }
  62639. if (this._lensFlareEnabled) {
  62640. // Create lens flare post-process
  62641. this._createLensFlarePostProcess(scene, ratio);
  62642. // Create depth-of-field source post-process post lens-flare and disable it now
  62643. 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);
  62644. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  62645. }
  62646. if (this._hdrEnabled) {
  62647. // Create luminance
  62648. this._createLuminancePostProcesses(scene, this._floatTextureType);
  62649. // Create HDR
  62650. this._createHdrPostProcess(scene, ratio);
  62651. // Create depth-of-field source post-process post hdr and disable it now
  62652. 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);
  62653. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  62654. }
  62655. if (this._depthOfFieldEnabled) {
  62656. // Create gaussian blur used by depth-of-field
  62657. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  62658. // Create depth-of-field post-process
  62659. this._createDepthOfFieldPostProcess(scene, ratio);
  62660. }
  62661. if (this._motionBlurEnabled) {
  62662. // Create motion blur post-process
  62663. this._createMotionBlurPostProcess(scene, ratio);
  62664. }
  62665. if (this._cameras !== null) {
  62666. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  62667. }
  62668. };
  62669. // Down Sample X4 Post-Processs
  62670. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  62671. var _this = this;
  62672. var downSampleX4Offsets = new Array(32);
  62673. 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);
  62674. this.downSampleX4PostProcess.onApply = function (effect) {
  62675. var id = 0;
  62676. var width = _this.downSampleX4PostProcess.width;
  62677. var height = _this.downSampleX4PostProcess.height;
  62678. for (var i = -2; i < 2; i++) {
  62679. for (var j = -2; j < 2; j++) {
  62680. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  62681. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  62682. id += 2;
  62683. }
  62684. }
  62685. effect.setArray2("dsOffsets", downSampleX4Offsets);
  62686. };
  62687. // Add to pipeline
  62688. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  62689. };
  62690. // Brightpass Post-Process
  62691. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  62692. var _this = this;
  62693. var brightOffsets = new Array(8);
  62694. 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);
  62695. this.brightPassPostProcess.onApply = function (effect) {
  62696. var sU = (1.0 / _this.brightPassPostProcess.width);
  62697. var sV = (1.0 / _this.brightPassPostProcess.height);
  62698. brightOffsets[0] = -0.5 * sU;
  62699. brightOffsets[1] = 0.5 * sV;
  62700. brightOffsets[2] = 0.5 * sU;
  62701. brightOffsets[3] = 0.5 * sV;
  62702. brightOffsets[4] = -0.5 * sU;
  62703. brightOffsets[5] = -0.5 * sV;
  62704. brightOffsets[6] = 0.5 * sU;
  62705. brightOffsets[7] = -0.5 * sV;
  62706. effect.setArray2("dsOffsets", brightOffsets);
  62707. effect.setFloat("brightThreshold", _this.brightThreshold);
  62708. };
  62709. // Add to pipeline
  62710. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  62711. };
  62712. // Create blur H&V post-processes
  62713. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  62714. var _this = this;
  62715. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  62716. var engine = scene.getEngine();
  62717. 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);
  62718. 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);
  62719. blurX.onActivateObservable.add(function () {
  62720. var dw = blurX.width / engine.getRenderWidth();
  62721. blurX.kernel = _this[blurWidthKey] * dw;
  62722. });
  62723. blurY.onActivateObservable.add(function () {
  62724. var dw = blurY.height / engine.getRenderHeight();
  62725. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  62726. });
  62727. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  62728. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  62729. this.blurHPostProcesses.push(blurX);
  62730. this.blurVPostProcesses.push(blurY);
  62731. };
  62732. // Create texture adder post-process
  62733. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  62734. var _this = this;
  62735. 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);
  62736. this.textureAdderPostProcess.onApply = function (effect) {
  62737. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  62738. effect.setTexture("lensSampler", _this.lensTexture);
  62739. effect.setFloat("exposure", _this.exposure);
  62740. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  62741. };
  62742. // Add to pipeline
  62743. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  62744. };
  62745. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  62746. var _this = this;
  62747. var geometryRenderer = scene.enableGeometryBufferRenderer();
  62748. geometryRenderer.enablePosition = true;
  62749. var geometry = geometryRenderer.getGBuffer();
  62750. // Base post-process
  62751. 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));
  62752. var depthValues = BABYLON.Vector2.Zero();
  62753. this.volumetricLightPostProcess.onApply = function (effect) {
  62754. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  62755. var generator = _this.sourceLight.getShadowGenerator();
  62756. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  62757. effect.setTexture("positionSampler", geometry.textures[2]);
  62758. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  62759. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  62760. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  62761. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  62762. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  62763. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  62764. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  62765. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  62766. effect.setVector2("depthValues", depthValues);
  62767. }
  62768. };
  62769. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  62770. // Smooth
  62771. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  62772. // Merge
  62773. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  62774. this.volumetricLightMergePostProces.onApply = function (effect) {
  62775. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  62776. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  62777. };
  62778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  62779. };
  62780. // Create luminance
  62781. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  62782. var _this = this;
  62783. // Create luminance
  62784. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  62785. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  62786. var offsets = [];
  62787. this.luminancePostProcess.onApply = function (effect) {
  62788. var sU = (1.0 / _this.luminancePostProcess.width);
  62789. var sV = (1.0 / _this.luminancePostProcess.height);
  62790. offsets[0] = -0.5 * sU;
  62791. offsets[1] = 0.5 * sV;
  62792. offsets[2] = 0.5 * sU;
  62793. offsets[3] = 0.5 * sV;
  62794. offsets[4] = -0.5 * sU;
  62795. offsets[5] = -0.5 * sV;
  62796. offsets[6] = 0.5 * sU;
  62797. offsets[7] = -0.5 * sV;
  62798. effect.setArray2("lumOffsets", offsets);
  62799. };
  62800. // Add to pipeline
  62801. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  62802. // Create down sample luminance
  62803. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  62804. var size = Math.pow(3, i);
  62805. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  62806. if (i === 0) {
  62807. defines += "#define FINAL_DOWN_SAMPLER";
  62808. }
  62809. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  62810. this.luminanceDownSamplePostProcesses.push(postProcess);
  62811. }
  62812. // Create callbacks and add effects
  62813. var lastLuminance = this.luminancePostProcess;
  62814. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  62815. var downSampleOffsets = new Array(18);
  62816. pp.onApply = function (effect) {
  62817. if (!lastLuminance) {
  62818. return;
  62819. }
  62820. var id = 0;
  62821. for (var x = -1; x < 2; x++) {
  62822. for (var y = -1; y < 2; y++) {
  62823. downSampleOffsets[id] = x / lastLuminance.width;
  62824. downSampleOffsets[id + 1] = y / lastLuminance.height;
  62825. id += 2;
  62826. }
  62827. }
  62828. effect.setArray2("dsOffsets", downSampleOffsets);
  62829. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  62830. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  62831. lastLuminance = _this.luminancePostProcess;
  62832. }
  62833. else {
  62834. lastLuminance = pp;
  62835. }
  62836. };
  62837. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  62838. pp.onAfterRender = function (effect) {
  62839. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  62840. 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);
  62841. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  62842. };
  62843. }
  62844. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  62845. });
  62846. };
  62847. // Create HDR post-process
  62848. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  62849. var _this = this;
  62850. 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);
  62851. var outputLiminance = 1;
  62852. var time = 0;
  62853. var lastTime = 0;
  62854. this.hdrPostProcess.onApply = function (effect) {
  62855. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  62856. time += scene.getEngine().getDeltaTime();
  62857. if (outputLiminance < 0) {
  62858. outputLiminance = _this._hdrCurrentLuminance;
  62859. }
  62860. else {
  62861. var dt = (lastTime - time) / 1000.0;
  62862. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  62863. outputLiminance += _this.hdrDecreaseRate * dt;
  62864. }
  62865. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  62866. outputLiminance -= _this.hdrIncreaseRate * dt;
  62867. }
  62868. else {
  62869. outputLiminance = _this._hdrCurrentLuminance;
  62870. }
  62871. }
  62872. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  62873. effect.setFloat("averageLuminance", outputLiminance);
  62874. lastTime = time;
  62875. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  62876. };
  62877. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  62878. };
  62879. // Create lens flare post-process
  62880. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  62881. var _this = this;
  62882. 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);
  62883. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  62884. this._createBlurPostProcesses(scene, ratio / 4, 2);
  62885. 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);
  62886. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  62887. var resolution = new BABYLON.Vector2(0, 0);
  62888. // Lens flare
  62889. this.lensFlarePostProcess.onApply = function (effect) {
  62890. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  62891. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  62892. effect.setFloat("strength", _this.lensFlareStrength);
  62893. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  62894. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  62895. // Shift
  62896. resolution.x = _this.lensFlarePostProcess.width;
  62897. resolution.y = _this.lensFlarePostProcess.height;
  62898. effect.setVector2("resolution", resolution);
  62899. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  62900. };
  62901. // Compose
  62902. 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);
  62903. 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);
  62904. this.lensFlareComposePostProcess.onApply = function (effect) {
  62905. if (!_this._scene.activeCamera) {
  62906. return;
  62907. }
  62908. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  62909. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  62910. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  62911. // Lens start rotation matrix
  62912. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  62913. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  62914. 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));
  62915. camRot *= 4.0;
  62916. 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);
  62917. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  62918. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  62919. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  62920. };
  62921. };
  62922. // Create depth-of-field post-process
  62923. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  62924. var _this = this;
  62925. 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);
  62926. this.depthOfFieldPostProcess.onApply = function (effect) {
  62927. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  62928. effect.setTexture("depthSampler", _this._getDepthTexture());
  62929. effect.setFloat("distance", _this.depthOfFieldDistance);
  62930. };
  62931. // Add to pipeline
  62932. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  62933. };
  62934. // Create motion blur post-process
  62935. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  62936. var _this = this;
  62937. 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);
  62938. var motionScale = 0;
  62939. var prevViewProjection = BABYLON.Matrix.Identity();
  62940. var invViewProjection = BABYLON.Matrix.Identity();
  62941. var viewProjection = BABYLON.Matrix.Identity();
  62942. var screenSize = BABYLON.Vector2.Zero();
  62943. this.motionBlurPostProcess.onApply = function (effect) {
  62944. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  62945. viewProjection.invertToRef(invViewProjection);
  62946. effect.setMatrix("inverseViewProjection", invViewProjection);
  62947. effect.setMatrix("prevViewProjection", prevViewProjection);
  62948. prevViewProjection = viewProjection;
  62949. screenSize.x = _this.motionBlurPostProcess.width;
  62950. screenSize.y = _this.motionBlurPostProcess.height;
  62951. effect.setVector2("screenSize", screenSize);
  62952. motionScale = scene.getEngine().getFps() / 60.0;
  62953. effect.setFloat("motionScale", motionScale);
  62954. effect.setFloat("motionStrength", _this.motionStrength);
  62955. effect.setTexture("depthSampler", _this._getDepthTexture());
  62956. };
  62957. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  62958. };
  62959. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  62960. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  62961. var renderer = this._scene.enableGeometryBufferRenderer();
  62962. return renderer.getGBuffer().textures[0];
  62963. }
  62964. return this._scene.enableDepthRenderer().getDepthMap();
  62965. };
  62966. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  62967. for (var i = 0; i < this._cameras.length; i++) {
  62968. var camera = this._cameras[i];
  62969. if (this.originalPostProcess) {
  62970. this.originalPostProcess.dispose(camera);
  62971. }
  62972. if (this.downSampleX4PostProcess) {
  62973. this.downSampleX4PostProcess.dispose(camera);
  62974. }
  62975. if (this.brightPassPostProcess) {
  62976. this.brightPassPostProcess.dispose(camera);
  62977. }
  62978. if (this.textureAdderPostProcess) {
  62979. this.textureAdderPostProcess.dispose(camera);
  62980. }
  62981. if (this.textureAdderFinalPostProcess) {
  62982. this.textureAdderFinalPostProcess.dispose(camera);
  62983. }
  62984. if (this.volumetricLightPostProcess) {
  62985. this.volumetricLightPostProcess.dispose(camera);
  62986. }
  62987. if (this.volumetricLightSmoothXPostProcess) {
  62988. this.volumetricLightSmoothXPostProcess.dispose(camera);
  62989. }
  62990. if (this.volumetricLightSmoothYPostProcess) {
  62991. this.volumetricLightSmoothYPostProcess.dispose(camera);
  62992. }
  62993. if (this.volumetricLightMergePostProces) {
  62994. this.volumetricLightMergePostProces.dispose(camera);
  62995. }
  62996. if (this.volumetricLightFinalPostProcess) {
  62997. this.volumetricLightFinalPostProcess.dispose(camera);
  62998. }
  62999. if (this.lensFlarePostProcess) {
  63000. this.lensFlarePostProcess.dispose(camera);
  63001. }
  63002. if (this.lensFlareComposePostProcess) {
  63003. this.lensFlareComposePostProcess.dispose(camera);
  63004. }
  63005. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  63006. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  63007. }
  63008. if (this.luminancePostProcess) {
  63009. this.luminancePostProcess.dispose(camera);
  63010. }
  63011. if (this.hdrPostProcess) {
  63012. this.hdrPostProcess.dispose(camera);
  63013. }
  63014. if (this.hdrFinalPostProcess) {
  63015. this.hdrFinalPostProcess.dispose(camera);
  63016. }
  63017. if (this.depthOfFieldPostProcess) {
  63018. this.depthOfFieldPostProcess.dispose(camera);
  63019. }
  63020. if (this.motionBlurPostProcess) {
  63021. this.motionBlurPostProcess.dispose(camera);
  63022. }
  63023. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  63024. this.blurHPostProcesses[j].dispose(camera);
  63025. }
  63026. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  63027. this.blurVPostProcesses[j].dispose(camera);
  63028. }
  63029. }
  63030. this.originalPostProcess = null;
  63031. this.downSampleX4PostProcess = null;
  63032. this.brightPassPostProcess = null;
  63033. this.textureAdderPostProcess = null;
  63034. this.textureAdderFinalPostProcess = null;
  63035. this.volumetricLightPostProcess = null;
  63036. this.volumetricLightSmoothXPostProcess = null;
  63037. this.volumetricLightSmoothYPostProcess = null;
  63038. this.volumetricLightMergePostProces = null;
  63039. this.volumetricLightFinalPostProcess = null;
  63040. this.lensFlarePostProcess = null;
  63041. this.lensFlareComposePostProcess = null;
  63042. this.luminancePostProcess = null;
  63043. this.hdrPostProcess = null;
  63044. this.hdrFinalPostProcess = null;
  63045. this.depthOfFieldPostProcess = null;
  63046. this.motionBlurPostProcess = null;
  63047. this.luminanceDownSamplePostProcesses = [];
  63048. this.blurHPostProcesses = [];
  63049. this.blurVPostProcesses = [];
  63050. };
  63051. // Dispose
  63052. StandardRenderingPipeline.prototype.dispose = function () {
  63053. this._disposePostProcesses();
  63054. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63055. _super.prototype.dispose.call(this);
  63056. };
  63057. // Serialize rendering pipeline
  63058. StandardRenderingPipeline.prototype.serialize = function () {
  63059. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63060. serializationObject.customType = "StandardRenderingPipeline";
  63061. return serializationObject;
  63062. };
  63063. /**
  63064. * Static members
  63065. */
  63066. // Parse serialized pipeline
  63067. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63068. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  63069. };
  63070. // Luminance steps
  63071. StandardRenderingPipeline.LuminanceSteps = 6;
  63072. __decorate([
  63073. BABYLON.serialize()
  63074. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  63075. __decorate([
  63076. BABYLON.serialize()
  63077. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  63078. __decorate([
  63079. BABYLON.serialize()
  63080. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  63081. __decorate([
  63082. BABYLON.serialize()
  63083. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  63084. __decorate([
  63085. BABYLON.serializeAsTexture("lensTexture")
  63086. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  63087. __decorate([
  63088. BABYLON.serialize()
  63089. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  63090. __decorate([
  63091. BABYLON.serialize()
  63092. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  63093. __decorate([
  63094. BABYLON.serialize()
  63095. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  63096. __decorate([
  63097. BABYLON.serialize()
  63098. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  63099. __decorate([
  63100. BABYLON.serialize()
  63101. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  63102. __decorate([
  63103. BABYLON.serialize()
  63104. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  63105. __decorate([
  63106. BABYLON.serializeAsTexture("lensColorTexture")
  63107. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  63108. __decorate([
  63109. BABYLON.serialize()
  63110. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  63111. __decorate([
  63112. BABYLON.serialize()
  63113. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  63114. __decorate([
  63115. BABYLON.serialize()
  63116. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  63117. __decorate([
  63118. BABYLON.serialize()
  63119. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  63120. __decorate([
  63121. BABYLON.serializeAsTexture("lensStarTexture")
  63122. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  63123. __decorate([
  63124. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  63125. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  63126. __decorate([
  63127. BABYLON.serialize()
  63128. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  63129. __decorate([
  63130. BABYLON.serialize()
  63131. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  63132. __decorate([
  63133. BABYLON.serialize()
  63134. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  63135. __decorate([
  63136. BABYLON.serialize()
  63137. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  63138. __decorate([
  63139. BABYLON.serialize()
  63140. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  63141. __decorate([
  63142. BABYLON.serialize()
  63143. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  63144. __decorate([
  63145. BABYLON.serialize()
  63146. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  63147. __decorate([
  63148. BABYLON.serialize()
  63149. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  63150. __decorate([
  63151. BABYLON.serialize()
  63152. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  63153. __decorate([
  63154. BABYLON.serialize()
  63155. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  63156. __decorate([
  63157. BABYLON.serialize()
  63158. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  63159. __decorate([
  63160. BABYLON.serialize()
  63161. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  63162. return StandardRenderingPipeline;
  63163. }(BABYLON.PostProcessRenderPipeline));
  63164. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  63165. })(BABYLON || (BABYLON = {}));
  63166. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  63167. var BABYLON;
  63168. (function (BABYLON) {
  63169. var FxaaPostProcess = /** @class */ (function (_super) {
  63170. __extends(FxaaPostProcess, _super);
  63171. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  63172. if (camera === void 0) { camera = null; }
  63173. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63174. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  63175. _this.onApplyObservable.add(function (effect) {
  63176. var texelSize = _this.texelSize;
  63177. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  63178. });
  63179. return _this;
  63180. }
  63181. return FxaaPostProcess;
  63182. }(BABYLON.PostProcess));
  63183. BABYLON.FxaaPostProcess = FxaaPostProcess;
  63184. })(BABYLON || (BABYLON = {}));
  63185. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  63186. var BABYLON;
  63187. (function (BABYLON) {
  63188. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  63189. __extends(DefaultRenderingPipeline, _super);
  63190. /**
  63191. * @constructor
  63192. * @param {string} name - The rendering pipeline name
  63193. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63194. * @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)
  63195. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63196. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  63197. */
  63198. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  63199. if (automaticBuild === void 0) { automaticBuild = true; }
  63200. var _this = _super.call(this, scene.getEngine(), name) || this;
  63201. _this.PassPostProcessId = "PassPostProcessEffect";
  63202. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  63203. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  63204. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  63205. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  63206. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  63207. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  63208. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  63209. // IAnimatable
  63210. _this.animations = [];
  63211. // Values
  63212. _this._bloomEnabled = false;
  63213. _this._fxaaEnabled = false;
  63214. _this._imageProcessingEnabled = true;
  63215. _this._bloomScale = 0.6;
  63216. _this._buildAllowed = true;
  63217. /**
  63218. * Specifies the size of the bloom blur kernel, relative to the final output size
  63219. */
  63220. _this.bloomKernel = 64;
  63221. /**
  63222. * Specifies the weight of the bloom in the final rendering
  63223. */
  63224. _this._bloomWeight = 0.15;
  63225. _this._cameras = cameras || [];
  63226. _this._buildAllowed = automaticBuild;
  63227. // Initialize
  63228. _this._scene = scene;
  63229. var caps = _this._scene.getEngine().getCaps();
  63230. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  63231. // Misc
  63232. if (_this._hdr) {
  63233. if (caps.textureHalfFloatRender) {
  63234. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63235. }
  63236. else if (caps.textureFloatRender) {
  63237. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63238. }
  63239. }
  63240. else {
  63241. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63242. }
  63243. // Attach
  63244. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63245. _this._buildPipeline();
  63246. return _this;
  63247. }
  63248. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  63249. get: function () {
  63250. return this._bloomWeight;
  63251. },
  63252. set: function (value) {
  63253. if (this._bloomWeight === value) {
  63254. return;
  63255. }
  63256. this._bloomWeight = value;
  63257. if (this._hdr && this.copyBack) {
  63258. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  63259. }
  63260. },
  63261. enumerable: true,
  63262. configurable: true
  63263. });
  63264. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  63265. get: function () {
  63266. return this._bloomScale;
  63267. },
  63268. set: function (value) {
  63269. if (this._bloomScale === value) {
  63270. return;
  63271. }
  63272. this._bloomScale = value;
  63273. this._buildPipeline();
  63274. },
  63275. enumerable: true,
  63276. configurable: true
  63277. });
  63278. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  63279. get: function () {
  63280. return this._bloomEnabled;
  63281. },
  63282. set: function (enabled) {
  63283. if (this._bloomEnabled === enabled) {
  63284. return;
  63285. }
  63286. this._bloomEnabled = enabled;
  63287. this._buildPipeline();
  63288. },
  63289. enumerable: true,
  63290. configurable: true
  63291. });
  63292. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  63293. get: function () {
  63294. return this._fxaaEnabled;
  63295. },
  63296. set: function (enabled) {
  63297. if (this._fxaaEnabled === enabled) {
  63298. return;
  63299. }
  63300. this._fxaaEnabled = enabled;
  63301. this._buildPipeline();
  63302. },
  63303. enumerable: true,
  63304. configurable: true
  63305. });
  63306. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  63307. get: function () {
  63308. return this._imageProcessingEnabled;
  63309. },
  63310. set: function (enabled) {
  63311. if (this._imageProcessingEnabled === enabled) {
  63312. return;
  63313. }
  63314. this._imageProcessingEnabled = enabled;
  63315. this._buildPipeline();
  63316. },
  63317. enumerable: true,
  63318. configurable: true
  63319. });
  63320. /**
  63321. * Force the compilation of the entire pipeline.
  63322. */
  63323. DefaultRenderingPipeline.prototype.prepare = function () {
  63324. var previousState = this._buildAllowed;
  63325. this._buildAllowed = true;
  63326. this._buildPipeline();
  63327. this._buildAllowed = previousState;
  63328. };
  63329. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  63330. var _this = this;
  63331. if (!this._buildAllowed) {
  63332. return;
  63333. }
  63334. var engine = this._scene.getEngine();
  63335. this._disposePostProcesses();
  63336. this._reset();
  63337. if (this.bloomEnabled) {
  63338. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63339. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  63340. if (!this._hdr) {
  63341. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63342. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  63343. this.highlights.autoClear = false;
  63344. this.highlights.alwaysForcePOT = true;
  63345. }
  63346. 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);
  63347. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  63348. this.blurX.alwaysForcePOT = true;
  63349. this.blurX.autoClear = false;
  63350. this.blurX.onActivateObservable.add(function () {
  63351. var dw = _this.blurX.width / engine.getRenderWidth(true);
  63352. _this.blurX.kernel = _this.bloomKernel * dw;
  63353. });
  63354. 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);
  63355. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  63356. this.blurY.alwaysForcePOT = true;
  63357. this.blurY.autoClear = false;
  63358. this.blurY.onActivateObservable.add(function () {
  63359. var dh = _this.blurY.height / engine.getRenderHeight(true);
  63360. _this.blurY.kernel = _this.bloomKernel * dh;
  63361. });
  63362. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63363. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  63364. this.copyBack.alwaysForcePOT = true;
  63365. if (this._hdr) {
  63366. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  63367. var w = this.bloomWeight;
  63368. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  63369. }
  63370. else {
  63371. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  63372. }
  63373. this.copyBack.autoClear = false;
  63374. }
  63375. if (this._imageProcessingEnabled) {
  63376. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63377. if (this._hdr) {
  63378. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  63379. }
  63380. else {
  63381. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  63382. }
  63383. }
  63384. if (this.fxaaEnabled) {
  63385. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63386. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  63387. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63388. }
  63389. else if (this._hdr && this.imageProcessing) {
  63390. this.finalMerge = this.imageProcessing;
  63391. }
  63392. else {
  63393. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63394. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  63395. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63396. }
  63397. if (this.bloomEnabled) {
  63398. if (this._hdr) {
  63399. this.copyBack.shareOutputWith(this.blurX);
  63400. if (this.imageProcessing) {
  63401. this.imageProcessing.shareOutputWith(this.pass);
  63402. this.imageProcessing.autoClear = false;
  63403. }
  63404. else if (this.fxaa) {
  63405. this.fxaa.shareOutputWith(this.pass);
  63406. }
  63407. else {
  63408. this.finalMerge.shareOutputWith(this.pass);
  63409. }
  63410. }
  63411. else {
  63412. if (this.fxaa) {
  63413. this.fxaa.shareOutputWith(this.pass);
  63414. }
  63415. else {
  63416. this.finalMerge.shareOutputWith(this.pass);
  63417. }
  63418. }
  63419. }
  63420. if (this._cameras !== null) {
  63421. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63422. }
  63423. };
  63424. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  63425. for (var i = 0; i < this._cameras.length; i++) {
  63426. var camera = this._cameras[i];
  63427. if (this.pass) {
  63428. this.pass.dispose(camera);
  63429. }
  63430. if (this.highlights) {
  63431. this.highlights.dispose(camera);
  63432. }
  63433. if (this.blurX) {
  63434. this.blurX.dispose(camera);
  63435. }
  63436. if (this.blurY) {
  63437. this.blurY.dispose(camera);
  63438. }
  63439. if (this.copyBack) {
  63440. this.copyBack.dispose(camera);
  63441. }
  63442. if (this.imageProcessing) {
  63443. this.imageProcessing.dispose(camera);
  63444. }
  63445. if (this.fxaa) {
  63446. this.fxaa.dispose(camera);
  63447. }
  63448. if (this.finalMerge) {
  63449. this.finalMerge.dispose(camera);
  63450. }
  63451. }
  63452. this.pass = null;
  63453. this.highlights = null;
  63454. this.blurX = null;
  63455. this.blurY = null;
  63456. this.copyBack = null;
  63457. this.imageProcessing = null;
  63458. this.fxaa = null;
  63459. this.finalMerge = null;
  63460. };
  63461. // Dispose
  63462. DefaultRenderingPipeline.prototype.dispose = function () {
  63463. this._disposePostProcesses();
  63464. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63465. _super.prototype.dispose.call(this);
  63466. };
  63467. // Serialize rendering pipeline
  63468. DefaultRenderingPipeline.prototype.serialize = function () {
  63469. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63470. serializationObject.customType = "DefaultRenderingPipeline";
  63471. return serializationObject;
  63472. };
  63473. // Parse serialized pipeline
  63474. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63475. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  63476. };
  63477. __decorate([
  63478. BABYLON.serialize()
  63479. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  63480. __decorate([
  63481. BABYLON.serialize()
  63482. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  63483. __decorate([
  63484. BABYLON.serialize()
  63485. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  63486. __decorate([
  63487. BABYLON.serialize()
  63488. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  63489. __decorate([
  63490. BABYLON.serialize()
  63491. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  63492. __decorate([
  63493. BABYLON.serialize()
  63494. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  63495. __decorate([
  63496. BABYLON.serialize()
  63497. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  63498. __decorate([
  63499. BABYLON.serialize()
  63500. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  63501. return DefaultRenderingPipeline;
  63502. }(BABYLON.PostProcessRenderPipeline));
  63503. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  63504. })(BABYLON || (BABYLON = {}));
  63505. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  63506. var BABYLON;
  63507. (function (BABYLON) {
  63508. /**
  63509. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  63510. */
  63511. var GeometryBufferRenderer = /** @class */ (function () {
  63512. /**
  63513. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  63514. * @param scene The scene the buffer belongs to
  63515. * @param ratio How big is the buffer related to the main canvas.
  63516. */
  63517. function GeometryBufferRenderer(scene, ratio) {
  63518. if (ratio === void 0) { ratio = 1; }
  63519. this._enablePosition = false;
  63520. this._scene = scene;
  63521. this._ratio = ratio;
  63522. // Render target
  63523. this._createRenderTargets();
  63524. }
  63525. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  63526. /**
  63527. * Set the render list (meshes to be rendered) used in the G buffer.
  63528. */
  63529. set: function (meshes) {
  63530. this._multiRenderTarget.renderList = meshes;
  63531. },
  63532. enumerable: true,
  63533. configurable: true
  63534. });
  63535. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  63536. /**
  63537. * Gets wether or not G buffer are supported by the running hardware.
  63538. * This requires draw buffer supports
  63539. */
  63540. get: function () {
  63541. return this._multiRenderTarget.isSupported;
  63542. },
  63543. enumerable: true,
  63544. configurable: true
  63545. });
  63546. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  63547. /**
  63548. * Gets wether or not position are enabled for the G buffer.
  63549. */
  63550. get: function () {
  63551. return this._enablePosition;
  63552. },
  63553. /**
  63554. * Sets wether or not position are enabled for the G buffer.
  63555. */
  63556. set: function (enable) {
  63557. this._enablePosition = enable;
  63558. this.dispose();
  63559. this._createRenderTargets();
  63560. },
  63561. enumerable: true,
  63562. configurable: true
  63563. });
  63564. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  63565. /**
  63566. * Gets the scene associated with the buffer.
  63567. */
  63568. get: function () {
  63569. return this._scene;
  63570. },
  63571. enumerable: true,
  63572. configurable: true
  63573. });
  63574. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  63575. /**
  63576. * Gets the ratio used by the buffer during its creation.
  63577. * How big is the buffer related to the main canvas.
  63578. */
  63579. get: function () {
  63580. return this._ratio;
  63581. },
  63582. enumerable: true,
  63583. configurable: true
  63584. });
  63585. /**
  63586. * Checks wether everything is ready to render a submesh to the G buffer.
  63587. * @param subMesh the submesh to check readiness for
  63588. * @param useInstances is the mesh drawn using instance or not
  63589. * @returns true if ready otherwise false
  63590. */
  63591. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  63592. var material = subMesh.getMaterial();
  63593. if (material && material.disableDepthWrite) {
  63594. return false;
  63595. }
  63596. var defines = [];
  63597. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  63598. var mesh = subMesh.getMesh();
  63599. // Alpha test
  63600. if (material && material.needAlphaTesting()) {
  63601. defines.push("#define ALPHATEST");
  63602. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63603. attribs.push(BABYLON.VertexBuffer.UVKind);
  63604. defines.push("#define UV1");
  63605. }
  63606. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63607. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63608. defines.push("#define UV2");
  63609. }
  63610. }
  63611. // Buffers
  63612. if (this._enablePosition) {
  63613. defines.push("#define POSITION");
  63614. }
  63615. // Bones
  63616. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63617. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63618. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63619. if (mesh.numBoneInfluencers > 4) {
  63620. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63621. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63622. }
  63623. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63624. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  63625. }
  63626. else {
  63627. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63628. }
  63629. // Instances
  63630. if (useInstances) {
  63631. defines.push("#define INSTANCES");
  63632. attribs.push("world0");
  63633. attribs.push("world1");
  63634. attribs.push("world2");
  63635. attribs.push("world3");
  63636. }
  63637. // Get correct effect
  63638. var join = defines.join("\n");
  63639. if (this._cachedDefines !== join) {
  63640. this._cachedDefines = join;
  63641. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  63642. }
  63643. return this._effect.isReady();
  63644. };
  63645. /**
  63646. * Gets the current underlying G Buffer.
  63647. * @returns the buffer
  63648. */
  63649. GeometryBufferRenderer.prototype.getGBuffer = function () {
  63650. return this._multiRenderTarget;
  63651. };
  63652. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  63653. /**
  63654. * Gets the number of samples used to render the buffer (anti aliasing).
  63655. */
  63656. get: function () {
  63657. return this._multiRenderTarget.samples;
  63658. },
  63659. /**
  63660. * Sets the number of samples used to render the buffer (anti aliasing).
  63661. */
  63662. set: function (value) {
  63663. this._multiRenderTarget.samples = value;
  63664. },
  63665. enumerable: true,
  63666. configurable: true
  63667. });
  63668. /**
  63669. * Disposes the renderer and frees up associated resources.
  63670. */
  63671. GeometryBufferRenderer.prototype.dispose = function () {
  63672. this.getGBuffer().dispose();
  63673. };
  63674. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  63675. var _this = this;
  63676. var engine = this._scene.getEngine();
  63677. var count = this._enablePosition ? 3 : 2;
  63678. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  63679. if (!this.isSupported) {
  63680. return;
  63681. }
  63682. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63683. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63684. this._multiRenderTarget.refreshRate = 1;
  63685. this._multiRenderTarget.renderParticles = false;
  63686. this._multiRenderTarget.renderList = null;
  63687. // set default depth value to 1.0 (far away)
  63688. this._multiRenderTarget.onClearObservable.add(function (engine) {
  63689. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  63690. });
  63691. // Custom render function
  63692. var renderSubMesh = function (subMesh) {
  63693. var mesh = subMesh.getRenderingMesh();
  63694. var scene = _this._scene;
  63695. var engine = scene.getEngine();
  63696. var material = subMesh.getMaterial();
  63697. if (!material) {
  63698. return;
  63699. }
  63700. // Culling
  63701. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  63702. // Managing instances
  63703. var batch = mesh._getInstancesRenderList(subMesh._id);
  63704. if (batch.mustReturn) {
  63705. return;
  63706. }
  63707. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  63708. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  63709. engine.enableEffect(_this._effect);
  63710. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  63711. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  63712. _this._effect.setMatrix("view", scene.getViewMatrix());
  63713. // Alpha test
  63714. if (material && material.needAlphaTesting()) {
  63715. var alphaTexture = material.getAlphaTestTexture();
  63716. if (alphaTexture) {
  63717. _this._effect.setTexture("diffuseSampler", alphaTexture);
  63718. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63719. }
  63720. }
  63721. // Bones
  63722. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  63723. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63724. }
  63725. // Draw
  63726. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  63727. }
  63728. };
  63729. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  63730. var index;
  63731. if (depthOnlySubMeshes.length) {
  63732. engine.setColorWrite(false);
  63733. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  63734. renderSubMesh(depthOnlySubMeshes.data[index]);
  63735. }
  63736. engine.setColorWrite(true);
  63737. }
  63738. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63739. renderSubMesh(opaqueSubMeshes.data[index]);
  63740. }
  63741. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63742. renderSubMesh(alphaTestSubMeshes.data[index]);
  63743. }
  63744. };
  63745. };
  63746. return GeometryBufferRenderer;
  63747. }());
  63748. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  63749. })(BABYLON || (BABYLON = {}));
  63750. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  63751. var BABYLON;
  63752. (function (BABYLON) {
  63753. var RefractionPostProcess = /** @class */ (function (_super) {
  63754. __extends(RefractionPostProcess, _super);
  63755. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  63756. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  63757. _this.color = color;
  63758. _this.depth = depth;
  63759. _this.colorLevel = colorLevel;
  63760. _this.onActivateObservable.add(function (cam) {
  63761. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  63762. });
  63763. _this.onApplyObservable.add(function (effect) {
  63764. effect.setColor3("baseColor", _this.color);
  63765. effect.setFloat("depth", _this.depth);
  63766. effect.setFloat("colorLevel", _this.colorLevel);
  63767. effect.setTexture("refractionSampler", _this._refRexture);
  63768. });
  63769. return _this;
  63770. }
  63771. // Methods
  63772. RefractionPostProcess.prototype.dispose = function (camera) {
  63773. if (this._refRexture) {
  63774. this._refRexture.dispose();
  63775. }
  63776. _super.prototype.dispose.call(this, camera);
  63777. };
  63778. return RefractionPostProcess;
  63779. }(BABYLON.PostProcess));
  63780. BABYLON.RefractionPostProcess = RefractionPostProcess;
  63781. })(BABYLON || (BABYLON = {}));
  63782. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  63783. var BABYLON;
  63784. (function (BABYLON) {
  63785. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  63786. __extends(BlackAndWhitePostProcess, _super);
  63787. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  63788. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  63789. _this.degree = 1;
  63790. _this.onApplyObservable.add(function (effect) {
  63791. effect.setFloat("degree", _this.degree);
  63792. });
  63793. return _this;
  63794. }
  63795. return BlackAndWhitePostProcess;
  63796. }(BABYLON.PostProcess));
  63797. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  63798. })(BABYLON || (BABYLON = {}));
  63799. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  63800. var BABYLON;
  63801. (function (BABYLON) {
  63802. var ConvolutionPostProcess = /** @class */ (function (_super) {
  63803. __extends(ConvolutionPostProcess, _super);
  63804. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  63805. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  63806. _this.kernel = kernel;
  63807. _this.onApply = function (effect) {
  63808. effect.setFloat2("screenSize", _this.width, _this.height);
  63809. effect.setArray("kernel", _this.kernel);
  63810. };
  63811. return _this;
  63812. }
  63813. // Statics
  63814. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  63815. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  63816. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  63817. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  63818. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  63819. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  63820. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  63821. return ConvolutionPostProcess;
  63822. }(BABYLON.PostProcess));
  63823. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  63824. })(BABYLON || (BABYLON = {}));
  63825. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  63826. var BABYLON;
  63827. (function (BABYLON) {
  63828. var FilterPostProcess = /** @class */ (function (_super) {
  63829. __extends(FilterPostProcess, _super);
  63830. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  63831. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  63832. _this.kernelMatrix = kernelMatrix;
  63833. _this.onApply = function (effect) {
  63834. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  63835. };
  63836. return _this;
  63837. }
  63838. return FilterPostProcess;
  63839. }(BABYLON.PostProcess));
  63840. BABYLON.FilterPostProcess = FilterPostProcess;
  63841. })(BABYLON || (BABYLON = {}));
  63842. //# sourceMappingURL=babylon.filterPostProcess.js.map
  63843. var BABYLON;
  63844. (function (BABYLON) {
  63845. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  63846. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  63847. __extends(VolumetricLightScatteringPostProcess, _super);
  63848. /**
  63849. * @constructor
  63850. * @param {string} name - The post-process name
  63851. * @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)
  63852. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  63853. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  63854. * @param {number} samples - The post-process quality, default 100
  63855. * @param {number} samplingMode - The post-process filtering mode
  63856. * @param {BABYLON.Engine} engine - The babylon engine
  63857. * @param {boolean} reusable - If the post-process is reusable
  63858. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  63859. */
  63860. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  63861. if (samples === void 0) { samples = 100; }
  63862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63863. 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;
  63864. _this._screenCoordinates = BABYLON.Vector2.Zero();
  63865. /**
  63866. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  63867. * @type {Vector3}
  63868. */
  63869. _this.customMeshPosition = BABYLON.Vector3.Zero();
  63870. /**
  63871. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  63872. * @type {boolean}
  63873. */
  63874. _this.useCustomMeshPosition = false;
  63875. /**
  63876. * If the post-process should inverse the light scattering direction
  63877. * @type {boolean}
  63878. */
  63879. _this.invert = true;
  63880. /**
  63881. * Array containing the excluded meshes not rendered in the internal pass
  63882. */
  63883. _this.excludedMeshes = new Array();
  63884. /**
  63885. * Controls the overall intensity of the post-process
  63886. * @type {number}
  63887. */
  63888. _this.exposure = 0.3;
  63889. /**
  63890. * Dissipates each sample's contribution in range [0, 1]
  63891. * @type {number}
  63892. */
  63893. _this.decay = 0.96815;
  63894. /**
  63895. * Controls the overall intensity of each sample
  63896. * @type {number}
  63897. */
  63898. _this.weight = 0.58767;
  63899. /**
  63900. * Controls the density of each sample
  63901. * @type {number}
  63902. */
  63903. _this.density = 0.926;
  63904. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  63905. engine = scene.getEngine();
  63906. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  63907. // Configure mesh
  63908. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  63909. // Configure
  63910. _this._createPass(scene, ratio.passRatio || ratio);
  63911. _this.onActivate = function (camera) {
  63912. if (!_this.isSupported) {
  63913. _this.dispose(camera);
  63914. }
  63915. _this.onActivate = null;
  63916. };
  63917. _this.onApplyObservable.add(function (effect) {
  63918. _this._updateMeshScreenCoordinates(scene);
  63919. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  63920. effect.setFloat("exposure", _this.exposure);
  63921. effect.setFloat("decay", _this.decay);
  63922. effect.setFloat("weight", _this.weight);
  63923. effect.setFloat("density", _this.density);
  63924. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  63925. });
  63926. return _this;
  63927. }
  63928. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  63929. get: function () {
  63930. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  63931. return false;
  63932. },
  63933. set: function (useDiffuseColor) {
  63934. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  63935. },
  63936. enumerable: true,
  63937. configurable: true
  63938. });
  63939. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  63940. return "VolumetricLightScatteringPostProcess";
  63941. };
  63942. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  63943. var mesh = subMesh.getMesh();
  63944. // Render this.mesh as default
  63945. if (mesh === this.mesh && mesh.material) {
  63946. return mesh.material.isReady(mesh);
  63947. }
  63948. var defines = [];
  63949. var attribs = [BABYLON.VertexBuffer.PositionKind];
  63950. var material = subMesh.getMaterial();
  63951. // Alpha test
  63952. if (material) {
  63953. if (material.needAlphaTesting()) {
  63954. defines.push("#define ALPHATEST");
  63955. }
  63956. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63957. attribs.push(BABYLON.VertexBuffer.UVKind);
  63958. defines.push("#define UV1");
  63959. }
  63960. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63961. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63962. defines.push("#define UV2");
  63963. }
  63964. }
  63965. // Bones
  63966. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63967. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63968. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63969. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63970. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  63971. }
  63972. else {
  63973. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63974. }
  63975. // Instances
  63976. if (useInstances) {
  63977. defines.push("#define INSTANCES");
  63978. attribs.push("world0");
  63979. attribs.push("world1");
  63980. attribs.push("world2");
  63981. attribs.push("world3");
  63982. }
  63983. // Get correct effect
  63984. var join = defines.join("\n");
  63985. if (this._cachedDefines !== join) {
  63986. this._cachedDefines = join;
  63987. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  63988. }
  63989. return this._volumetricLightScatteringPass.isReady();
  63990. };
  63991. /**
  63992. * Sets the new light position for light scattering effect
  63993. * @param {BABYLON.Vector3} The new custom light position
  63994. */
  63995. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  63996. this.customMeshPosition = position;
  63997. };
  63998. /**
  63999. * Returns the light position for light scattering effect
  64000. * @return {BABYLON.Vector3} The custom light position
  64001. */
  64002. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  64003. return this.customMeshPosition;
  64004. };
  64005. /**
  64006. * Disposes the internal assets and detaches the post-process from the camera
  64007. */
  64008. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  64009. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  64010. if (rttIndex !== -1) {
  64011. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  64012. }
  64013. this._volumetricLightScatteringRTT.dispose();
  64014. _super.prototype.dispose.call(this, camera);
  64015. };
  64016. /**
  64017. * Returns the render target texture used by the post-process
  64018. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  64019. */
  64020. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  64021. return this._volumetricLightScatteringRTT;
  64022. };
  64023. // Private methods
  64024. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  64025. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  64026. return true;
  64027. }
  64028. return false;
  64029. };
  64030. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  64031. var _this = this;
  64032. var engine = scene.getEngine();
  64033. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64034. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64035. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64036. this._volumetricLightScatteringRTT.renderList = null;
  64037. this._volumetricLightScatteringRTT.renderParticles = false;
  64038. var camera = this.getCamera();
  64039. if (camera) {
  64040. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64041. }
  64042. else {
  64043. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64044. }
  64045. // Custom render function for submeshes
  64046. var renderSubMesh = function (subMesh) {
  64047. var mesh = subMesh.getRenderingMesh();
  64048. if (_this._meshExcluded(mesh)) {
  64049. return;
  64050. }
  64051. var material = subMesh.getMaterial();
  64052. if (!material) {
  64053. return;
  64054. }
  64055. var scene = mesh.getScene();
  64056. var engine = scene.getEngine();
  64057. // Culling
  64058. engine.setState(material.backFaceCulling);
  64059. // Managing instances
  64060. var batch = mesh._getInstancesRenderList(subMesh._id);
  64061. if (batch.mustReturn) {
  64062. return;
  64063. }
  64064. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64065. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  64066. var effect = _this._volumetricLightScatteringPass;
  64067. if (mesh === _this.mesh) {
  64068. if (subMesh.effect) {
  64069. effect = subMesh.effect;
  64070. }
  64071. else {
  64072. effect = material.getEffect();
  64073. }
  64074. }
  64075. engine.enableEffect(effect);
  64076. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  64077. if (mesh === _this.mesh) {
  64078. material.bind(mesh.getWorldMatrix(), mesh);
  64079. }
  64080. else {
  64081. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  64082. // Alpha test
  64083. if (material && material.needAlphaTesting()) {
  64084. var alphaTexture = material.getAlphaTestTexture();
  64085. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  64086. if (alphaTexture) {
  64087. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64088. }
  64089. }
  64090. // Bones
  64091. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64092. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64093. }
  64094. }
  64095. // Draw
  64096. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  64097. }
  64098. };
  64099. // Render target texture callbacks
  64100. var savedSceneClearColor;
  64101. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  64102. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  64103. savedSceneClearColor = scene.clearColor;
  64104. scene.clearColor = sceneClearColor;
  64105. });
  64106. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  64107. scene.clearColor = savedSceneClearColor;
  64108. });
  64109. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64110. var engine = scene.getEngine();
  64111. var index;
  64112. if (depthOnlySubMeshes.length) {
  64113. engine.setColorWrite(false);
  64114. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64115. renderSubMesh(depthOnlySubMeshes.data[index]);
  64116. }
  64117. engine.setColorWrite(true);
  64118. }
  64119. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64120. renderSubMesh(opaqueSubMeshes.data[index]);
  64121. }
  64122. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64123. renderSubMesh(alphaTestSubMeshes.data[index]);
  64124. }
  64125. if (transparentSubMeshes.length) {
  64126. // Sort sub meshes
  64127. for (index = 0; index < transparentSubMeshes.length; index++) {
  64128. var submesh = transparentSubMeshes.data[index];
  64129. var boundingInfo = submesh.getBoundingInfo();
  64130. if (boundingInfo && scene.activeCamera) {
  64131. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  64132. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  64133. }
  64134. }
  64135. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  64136. sortedArray.sort(function (a, b) {
  64137. // Alpha index first
  64138. if (a._alphaIndex > b._alphaIndex) {
  64139. return 1;
  64140. }
  64141. if (a._alphaIndex < b._alphaIndex) {
  64142. return -1;
  64143. }
  64144. // Then distance to camera
  64145. if (a._distanceToCamera < b._distanceToCamera) {
  64146. return 1;
  64147. }
  64148. if (a._distanceToCamera > b._distanceToCamera) {
  64149. return -1;
  64150. }
  64151. return 0;
  64152. });
  64153. // Render sub meshes
  64154. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64155. for (index = 0; index < sortedArray.length; index++) {
  64156. renderSubMesh(sortedArray[index]);
  64157. }
  64158. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64159. }
  64160. };
  64161. };
  64162. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  64163. var transform = scene.getTransformMatrix();
  64164. var meshPosition;
  64165. if (this.useCustomMeshPosition) {
  64166. meshPosition = this.customMeshPosition;
  64167. }
  64168. else if (this.attachedNode) {
  64169. meshPosition = this.attachedNode.position;
  64170. }
  64171. else {
  64172. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  64173. }
  64174. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  64175. this._screenCoordinates.x = pos.x / this._viewPort.width;
  64176. this._screenCoordinates.y = pos.y / this._viewPort.height;
  64177. if (this.invert)
  64178. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  64179. };
  64180. // Static methods
  64181. /**
  64182. * Creates a default mesh for the Volumeric Light Scattering post-process
  64183. * @param {string} The mesh name
  64184. * @param {BABYLON.Scene} The scene where to create the mesh
  64185. * @return {BABYLON.Mesh} the default mesh
  64186. */
  64187. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  64188. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  64189. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  64190. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  64191. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  64192. mesh.material = material;
  64193. return mesh;
  64194. };
  64195. __decorate([
  64196. BABYLON.serializeAsVector3()
  64197. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  64198. __decorate([
  64199. BABYLON.serialize()
  64200. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  64201. __decorate([
  64202. BABYLON.serialize()
  64203. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  64204. __decorate([
  64205. BABYLON.serializeAsMeshReference()
  64206. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  64207. __decorate([
  64208. BABYLON.serialize()
  64209. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  64210. __decorate([
  64211. BABYLON.serialize()
  64212. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  64213. __decorate([
  64214. BABYLON.serialize()
  64215. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  64216. __decorate([
  64217. BABYLON.serialize()
  64218. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  64219. __decorate([
  64220. BABYLON.serialize()
  64221. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  64222. return VolumetricLightScatteringPostProcess;
  64223. }(BABYLON.PostProcess));
  64224. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  64225. })(BABYLON || (BABYLON = {}));
  64226. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  64227. //
  64228. // This post-process allows the modification of rendered colors by using
  64229. // a 'look-up table' (LUT). This effect is also called Color Grading.
  64230. //
  64231. // The object needs to be provided an url to a texture containing the color
  64232. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  64233. // Use an image editing software to tweak the LUT to match your needs.
  64234. //
  64235. // For an example of a color LUT, see here:
  64236. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  64237. // For explanations on color grading, see here:
  64238. // http://udn.epicgames.com/Three/ColorGrading.html
  64239. //
  64240. var BABYLON;
  64241. (function (BABYLON) {
  64242. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  64243. __extends(ColorCorrectionPostProcess, _super);
  64244. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  64245. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  64246. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64247. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  64248. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64249. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64250. _this.onApply = function (effect) {
  64251. effect.setTexture("colorTable", _this._colorTableTexture);
  64252. };
  64253. return _this;
  64254. }
  64255. return ColorCorrectionPostProcess;
  64256. }(BABYLON.PostProcess));
  64257. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  64258. })(BABYLON || (BABYLON = {}));
  64259. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  64260. var BABYLON;
  64261. (function (BABYLON) {
  64262. var TonemappingOperator;
  64263. (function (TonemappingOperator) {
  64264. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  64265. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  64266. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  64267. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  64268. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  64269. ;
  64270. var TonemapPostProcess = /** @class */ (function (_super) {
  64271. __extends(TonemapPostProcess, _super);
  64272. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  64273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64274. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64275. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  64276. _this._operator = _operator;
  64277. _this.exposureAdjustment = exposureAdjustment;
  64278. var defines = "#define ";
  64279. if (_this._operator === TonemappingOperator.Hable)
  64280. defines += "HABLE_TONEMAPPING";
  64281. else if (_this._operator === TonemappingOperator.Reinhard)
  64282. defines += "REINHARD_TONEMAPPING";
  64283. else if (_this._operator === TonemappingOperator.HejiDawson)
  64284. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  64285. else if (_this._operator === TonemappingOperator.Photographic)
  64286. defines += "PHOTOGRAPHIC_TONEMAPPING";
  64287. //sadly a second call to create the effect.
  64288. _this.updateEffect(defines);
  64289. _this.onApply = function (effect) {
  64290. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  64291. };
  64292. return _this;
  64293. }
  64294. return TonemapPostProcess;
  64295. }(BABYLON.PostProcess));
  64296. BABYLON.TonemapPostProcess = TonemapPostProcess;
  64297. })(BABYLON || (BABYLON = {}));
  64298. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  64299. var BABYLON;
  64300. (function (BABYLON) {
  64301. var DisplayPassPostProcess = /** @class */ (function (_super) {
  64302. __extends(DisplayPassPostProcess, _super);
  64303. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  64304. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  64305. }
  64306. return DisplayPassPostProcess;
  64307. }(BABYLON.PostProcess));
  64308. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  64309. })(BABYLON || (BABYLON = {}));
  64310. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  64311. var BABYLON;
  64312. (function (BABYLON) {
  64313. var HighlightsPostProcess = /** @class */ (function (_super) {
  64314. __extends(HighlightsPostProcess, _super);
  64315. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64316. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64317. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64318. }
  64319. return HighlightsPostProcess;
  64320. }(BABYLON.PostProcess));
  64321. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  64322. })(BABYLON || (BABYLON = {}));
  64323. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  64324. var BABYLON;
  64325. (function (BABYLON) {
  64326. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  64327. __extends(ImageProcessingPostProcess, _super);
  64328. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  64329. if (camera === void 0) { camera = null; }
  64330. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64331. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  64332. _this._fromLinearSpace = true;
  64333. /**
  64334. * Defines cache preventing GC.
  64335. */
  64336. _this._defines = {
  64337. IMAGEPROCESSING: false,
  64338. VIGNETTE: false,
  64339. VIGNETTEBLENDMODEMULTIPLY: false,
  64340. VIGNETTEBLENDMODEOPAQUE: false,
  64341. TONEMAPPING: false,
  64342. CONTRAST: false,
  64343. COLORCURVES: false,
  64344. COLORGRADING: false,
  64345. COLORGRADING3D: false,
  64346. FROMLINEARSPACE: false,
  64347. SAMPLER3DGREENDEPTH: false,
  64348. SAMPLER3DBGRMAP: false,
  64349. IMAGEPROCESSINGPOSTPROCESS: false,
  64350. EXPOSURE: false,
  64351. };
  64352. // Setup the configuration as forced by the constructor. This would then not force the
  64353. // scene materials output in linear space and let untouched the default forward pass.
  64354. if (imageProcessingConfiguration) {
  64355. imageProcessingConfiguration.applyByPostProcess = true;
  64356. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  64357. // This will cause the shader to be compiled
  64358. _this.fromLinearSpace = false;
  64359. }
  64360. else {
  64361. _this._attachImageProcessingConfiguration(null, true);
  64362. _this.imageProcessingConfiguration.applyByPostProcess = true;
  64363. }
  64364. _this.onApply = function (effect) {
  64365. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  64366. };
  64367. return _this;
  64368. }
  64369. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  64370. /**
  64371. * Gets the image processing configuration used either in this material.
  64372. */
  64373. get: function () {
  64374. return this._imageProcessingConfiguration;
  64375. },
  64376. /**
  64377. * Sets the Default image processing configuration used either in the this material.
  64378. *
  64379. * If sets to null, the scene one is in use.
  64380. */
  64381. set: function (value) {
  64382. this._attachImageProcessingConfiguration(value);
  64383. },
  64384. enumerable: true,
  64385. configurable: true
  64386. });
  64387. /**
  64388. * Attaches a new image processing configuration to the PBR Material.
  64389. * @param configuration
  64390. */
  64391. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  64392. var _this = this;
  64393. if (doNotBuild === void 0) { doNotBuild = false; }
  64394. if (configuration === this._imageProcessingConfiguration) {
  64395. return;
  64396. }
  64397. // Detaches observer.
  64398. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64399. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64400. }
  64401. // Pick the scene configuration if needed.
  64402. if (!configuration) {
  64403. var scene = null;
  64404. var engine = this.getEngine();
  64405. var camera = this.getCamera();
  64406. if (camera) {
  64407. scene = camera.getScene();
  64408. }
  64409. else if (engine && engine.scenes) {
  64410. var scenes = engine.scenes;
  64411. scene = scenes[scenes.length - 1];
  64412. }
  64413. else {
  64414. scene = BABYLON.Engine.LastCreatedScene;
  64415. }
  64416. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  64417. }
  64418. else {
  64419. this._imageProcessingConfiguration = configuration;
  64420. }
  64421. // Attaches observer.
  64422. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  64423. _this._updateParameters();
  64424. });
  64425. // Ensure the effect will be rebuilt.
  64426. if (!doNotBuild) {
  64427. this._updateParameters();
  64428. }
  64429. };
  64430. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  64431. /**
  64432. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64433. */
  64434. get: function () {
  64435. return this.imageProcessingConfiguration.colorCurves;
  64436. },
  64437. /**
  64438. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64439. */
  64440. set: function (value) {
  64441. this.imageProcessingConfiguration.colorCurves = value;
  64442. },
  64443. enumerable: true,
  64444. configurable: true
  64445. });
  64446. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  64447. /**
  64448. * Gets wether the color curves effect is enabled.
  64449. */
  64450. get: function () {
  64451. return this.imageProcessingConfiguration.colorCurvesEnabled;
  64452. },
  64453. /**
  64454. * Sets wether the color curves effect is enabled.
  64455. */
  64456. set: function (value) {
  64457. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  64458. },
  64459. enumerable: true,
  64460. configurable: true
  64461. });
  64462. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  64463. /**
  64464. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64465. */
  64466. get: function () {
  64467. return this.imageProcessingConfiguration.colorGradingTexture;
  64468. },
  64469. /**
  64470. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64471. */
  64472. set: function (value) {
  64473. this.imageProcessingConfiguration.colorGradingTexture = value;
  64474. },
  64475. enumerable: true,
  64476. configurable: true
  64477. });
  64478. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  64479. /**
  64480. * Gets wether the color grading effect is enabled.
  64481. */
  64482. get: function () {
  64483. return this.imageProcessingConfiguration.colorGradingEnabled;
  64484. },
  64485. /**
  64486. * Gets wether the color grading effect is enabled.
  64487. */
  64488. set: function (value) {
  64489. this.imageProcessingConfiguration.colorGradingEnabled = value;
  64490. },
  64491. enumerable: true,
  64492. configurable: true
  64493. });
  64494. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  64495. /**
  64496. * Gets exposure used in the effect.
  64497. */
  64498. get: function () {
  64499. return this.imageProcessingConfiguration.exposure;
  64500. },
  64501. /**
  64502. * Sets exposure used in the effect.
  64503. */
  64504. set: function (value) {
  64505. this.imageProcessingConfiguration.exposure = value;
  64506. },
  64507. enumerable: true,
  64508. configurable: true
  64509. });
  64510. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  64511. /**
  64512. * Gets wether tonemapping is enabled or not.
  64513. */
  64514. get: function () {
  64515. return this._imageProcessingConfiguration.toneMappingEnabled;
  64516. },
  64517. /**
  64518. * Sets wether tonemapping is enabled or not
  64519. */
  64520. set: function (value) {
  64521. this._imageProcessingConfiguration.toneMappingEnabled = value;
  64522. },
  64523. enumerable: true,
  64524. configurable: true
  64525. });
  64526. ;
  64527. ;
  64528. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  64529. /**
  64530. * Gets contrast used in the effect.
  64531. */
  64532. get: function () {
  64533. return this.imageProcessingConfiguration.contrast;
  64534. },
  64535. /**
  64536. * Sets contrast used in the effect.
  64537. */
  64538. set: function (value) {
  64539. this.imageProcessingConfiguration.contrast = value;
  64540. },
  64541. enumerable: true,
  64542. configurable: true
  64543. });
  64544. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  64545. /**
  64546. * Gets Vignette stretch size.
  64547. */
  64548. get: function () {
  64549. return this.imageProcessingConfiguration.vignetteStretch;
  64550. },
  64551. /**
  64552. * Sets Vignette stretch size.
  64553. */
  64554. set: function (value) {
  64555. this.imageProcessingConfiguration.vignetteStretch = value;
  64556. },
  64557. enumerable: true,
  64558. configurable: true
  64559. });
  64560. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  64561. /**
  64562. * Gets Vignette centre X Offset.
  64563. */
  64564. get: function () {
  64565. return this.imageProcessingConfiguration.vignetteCentreX;
  64566. },
  64567. /**
  64568. * Sets Vignette centre X Offset.
  64569. */
  64570. set: function (value) {
  64571. this.imageProcessingConfiguration.vignetteCentreX = value;
  64572. },
  64573. enumerable: true,
  64574. configurable: true
  64575. });
  64576. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  64577. /**
  64578. * Gets Vignette centre Y Offset.
  64579. */
  64580. get: function () {
  64581. return this.imageProcessingConfiguration.vignetteCentreY;
  64582. },
  64583. /**
  64584. * Sets Vignette centre Y Offset.
  64585. */
  64586. set: function (value) {
  64587. this.imageProcessingConfiguration.vignetteCentreY = value;
  64588. },
  64589. enumerable: true,
  64590. configurable: true
  64591. });
  64592. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  64593. /**
  64594. * Gets Vignette weight or intensity of the vignette effect.
  64595. */
  64596. get: function () {
  64597. return this.imageProcessingConfiguration.vignetteWeight;
  64598. },
  64599. /**
  64600. * Sets Vignette weight or intensity of the vignette effect.
  64601. */
  64602. set: function (value) {
  64603. this.imageProcessingConfiguration.vignetteWeight = value;
  64604. },
  64605. enumerable: true,
  64606. configurable: true
  64607. });
  64608. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  64609. /**
  64610. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  64611. * if vignetteEnabled is set to true.
  64612. */
  64613. get: function () {
  64614. return this.imageProcessingConfiguration.vignetteColor;
  64615. },
  64616. /**
  64617. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  64618. * if vignetteEnabled is set to true.
  64619. */
  64620. set: function (value) {
  64621. this.imageProcessingConfiguration.vignetteColor = value;
  64622. },
  64623. enumerable: true,
  64624. configurable: true
  64625. });
  64626. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  64627. /**
  64628. * Gets Camera field of view used by the Vignette effect.
  64629. */
  64630. get: function () {
  64631. return this.imageProcessingConfiguration.vignetteCameraFov;
  64632. },
  64633. /**
  64634. * Sets Camera field of view used by the Vignette effect.
  64635. */
  64636. set: function (value) {
  64637. this.imageProcessingConfiguration.vignetteCameraFov = value;
  64638. },
  64639. enumerable: true,
  64640. configurable: true
  64641. });
  64642. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  64643. /**
  64644. * Gets the vignette blend mode allowing different kind of effect.
  64645. */
  64646. get: function () {
  64647. return this.imageProcessingConfiguration.vignetteBlendMode;
  64648. },
  64649. /**
  64650. * Sets the vignette blend mode allowing different kind of effect.
  64651. */
  64652. set: function (value) {
  64653. this.imageProcessingConfiguration.vignetteBlendMode = value;
  64654. },
  64655. enumerable: true,
  64656. configurable: true
  64657. });
  64658. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  64659. /**
  64660. * Gets wether the vignette effect is enabled.
  64661. */
  64662. get: function () {
  64663. return this.imageProcessingConfiguration.vignetteEnabled;
  64664. },
  64665. /**
  64666. * Sets wether the vignette effect is enabled.
  64667. */
  64668. set: function (value) {
  64669. this.imageProcessingConfiguration.vignetteEnabled = value;
  64670. },
  64671. enumerable: true,
  64672. configurable: true
  64673. });
  64674. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  64675. /**
  64676. * Gets wether the input of the processing is in Gamma or Linear Space.
  64677. */
  64678. get: function () {
  64679. return this._fromLinearSpace;
  64680. },
  64681. /**
  64682. * Sets wether the input of the processing is in Gamma or Linear Space.
  64683. */
  64684. set: function (value) {
  64685. if (this._fromLinearSpace === value) {
  64686. return;
  64687. }
  64688. this._fromLinearSpace = value;
  64689. this._updateParameters();
  64690. },
  64691. enumerable: true,
  64692. configurable: true
  64693. });
  64694. ImageProcessingPostProcess.prototype.getClassName = function () {
  64695. return "ImageProcessingPostProcess";
  64696. };
  64697. ImageProcessingPostProcess.prototype._updateParameters = function () {
  64698. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  64699. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  64700. var defines = "";
  64701. for (var define in this._defines) {
  64702. if (this._defines[define]) {
  64703. defines += "#define " + define + ";\r\n";
  64704. }
  64705. }
  64706. var samplers = ["textureSampler"];
  64707. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  64708. var uniforms = ["scale"];
  64709. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  64710. this.updateEffect(defines, uniforms, samplers);
  64711. };
  64712. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  64713. _super.prototype.dispose.call(this, camera);
  64714. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64715. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64716. }
  64717. this.imageProcessingConfiguration.applyByPostProcess = false;
  64718. };
  64719. __decorate([
  64720. BABYLON.serialize()
  64721. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  64722. return ImageProcessingPostProcess;
  64723. }(BABYLON.PostProcess));
  64724. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  64725. })(BABYLON || (BABYLON = {}));
  64726. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  64727. var BABYLON;
  64728. (function (BABYLON) {
  64729. var BlurPostProcess = /** @class */ (function (_super) {
  64730. __extends(BlurPostProcess, _super);
  64731. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  64732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64733. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64734. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  64735. _this.direction = direction;
  64736. _this._packedFloat = false;
  64737. _this.onApplyObservable.add(function (effect) {
  64738. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  64739. });
  64740. _this.kernel = kernel;
  64741. return _this;
  64742. }
  64743. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  64744. /**
  64745. * Gets the length in pixels of the blur sample region
  64746. */
  64747. get: function () {
  64748. return this._idealKernel;
  64749. },
  64750. /**
  64751. * Sets the length in pixels of the blur sample region
  64752. */
  64753. set: function (v) {
  64754. if (this._idealKernel === v) {
  64755. return;
  64756. }
  64757. v = Math.max(v, 1);
  64758. this._idealKernel = v;
  64759. this._kernel = this._nearestBestKernel(v);
  64760. this._updateParameters();
  64761. },
  64762. enumerable: true,
  64763. configurable: true
  64764. });
  64765. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  64766. /**
  64767. * Gets wether or not the blur is unpacking/repacking floats
  64768. */
  64769. get: function () {
  64770. return this._packedFloat;
  64771. },
  64772. /**
  64773. * Sets wether or not the blur needs to unpack/repack floats
  64774. */
  64775. set: function (v) {
  64776. if (this._packedFloat === v) {
  64777. return;
  64778. }
  64779. this._packedFloat = v;
  64780. this._updateParameters();
  64781. },
  64782. enumerable: true,
  64783. configurable: true
  64784. });
  64785. BlurPostProcess.prototype._updateParameters = function () {
  64786. // Generate sampling offsets and weights
  64787. var N = this._kernel;
  64788. var centerIndex = (N - 1) / 2;
  64789. // Generate Gaussian sampling weights over kernel
  64790. var offsets = [];
  64791. var weights = [];
  64792. var totalWeight = 0;
  64793. for (var i = 0; i < N; i++) {
  64794. var u = i / (N - 1);
  64795. var w = this._gaussianWeight(u * 2.0 - 1);
  64796. offsets[i] = (i - centerIndex);
  64797. weights[i] = w;
  64798. totalWeight += w;
  64799. }
  64800. // Normalize weights
  64801. for (var i = 0; i < weights.length; i++) {
  64802. weights[i] /= totalWeight;
  64803. }
  64804. // Optimize: combine samples to take advantage of hardware linear sampling
  64805. // Walk from left to center, combining pairs (symmetrically)
  64806. var linearSamplingWeights = [];
  64807. var linearSamplingOffsets = [];
  64808. var linearSamplingMap = [];
  64809. for (var i = 0; i <= centerIndex; i += 2) {
  64810. var j = Math.min(i + 1, Math.floor(centerIndex));
  64811. var singleCenterSample = i === j;
  64812. if (singleCenterSample) {
  64813. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  64814. }
  64815. else {
  64816. var sharedCell = j === centerIndex;
  64817. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  64818. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  64819. if (offsetLinear === 0) {
  64820. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  64821. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  64822. }
  64823. else {
  64824. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  64825. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  64826. }
  64827. }
  64828. }
  64829. for (var i = 0; i < linearSamplingMap.length; i++) {
  64830. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  64831. linearSamplingWeights[i] = linearSamplingMap[i].w;
  64832. }
  64833. // Replace with optimized
  64834. offsets = linearSamplingOffsets;
  64835. weights = linearSamplingWeights;
  64836. // Generate shaders
  64837. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  64838. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  64839. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  64840. var defines = "";
  64841. for (var i = 0; i < varyingCount; i++) {
  64842. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  64843. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  64844. }
  64845. var depCount = 0;
  64846. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  64847. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  64848. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  64849. depCount++;
  64850. }
  64851. if (this.packedFloat) {
  64852. defines += "#define PACKEDFLOAT 1";
  64853. }
  64854. this.updateEffect(defines, null, null, {
  64855. varyingCount: varyingCount,
  64856. depCount: depCount
  64857. });
  64858. };
  64859. /**
  64860. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  64861. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  64862. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  64863. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  64864. * The gaps between physical kernels are compensated for in the weighting of the samples
  64865. * @param idealKernel Ideal blur kernel.
  64866. * @return Nearest best kernel.
  64867. */
  64868. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  64869. var v = Math.round(idealKernel);
  64870. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  64871. var k = _a[_i];
  64872. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  64873. return Math.max(k, 3);
  64874. }
  64875. }
  64876. return Math.max(v, 3);
  64877. };
  64878. /**
  64879. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  64880. * @param x The point on the Gaussian distribution to sample.
  64881. * @return the value of the Gaussian function at x.
  64882. */
  64883. BlurPostProcess.prototype._gaussianWeight = function (x) {
  64884. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  64885. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  64886. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  64887. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  64888. // truncated at around 1.3% of peak strength.
  64889. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  64890. var sigma = (1 / 3);
  64891. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  64892. var exponent = -((x * x) / (2.0 * sigma * sigma));
  64893. var weight = (1.0 / denominator) * Math.exp(exponent);
  64894. return weight;
  64895. };
  64896. /**
  64897. * Generates a string that can be used as a floating point number in GLSL.
  64898. * @param x Value to print.
  64899. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  64900. * @return GLSL float string.
  64901. */
  64902. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  64903. if (decimalFigures === void 0) { decimalFigures = 8; }
  64904. return x.toFixed(decimalFigures).replace(/0+$/, '');
  64905. };
  64906. return BlurPostProcess;
  64907. }(BABYLON.PostProcess));
  64908. BABYLON.BlurPostProcess = BlurPostProcess;
  64909. })(BABYLON || (BABYLON = {}));
  64910. //# sourceMappingURL=babylon.blurPostProcess.js.map
  64911. var BABYLON;
  64912. (function (BABYLON) {
  64913. var Bone = /** @class */ (function (_super) {
  64914. __extends(Bone, _super);
  64915. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  64916. if (parentBone === void 0) { parentBone = null; }
  64917. if (localMatrix === void 0) { localMatrix = null; }
  64918. if (restPose === void 0) { restPose = null; }
  64919. if (baseMatrix === void 0) { baseMatrix = null; }
  64920. if (index === void 0) { index = null; }
  64921. var _this = _super.call(this, name, skeleton.getScene()) || this;
  64922. _this.name = name;
  64923. _this.children = new Array();
  64924. _this.animations = new Array();
  64925. // Set this value to map this bone to a different index in the transform matrices.
  64926. // Set this value to -1 to exclude the bone from the transform matrices.
  64927. _this._index = null;
  64928. _this._worldTransform = new BABYLON.Matrix();
  64929. _this._absoluteTransform = new BABYLON.Matrix();
  64930. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  64931. _this._scaleMatrix = BABYLON.Matrix.Identity();
  64932. _this._scaleVector = BABYLON.Vector3.One();
  64933. _this._negateScaleChildren = BABYLON.Vector3.One();
  64934. _this._scalingDeterminant = 1;
  64935. _this._skeleton = skeleton;
  64936. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  64937. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  64938. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  64939. _this._index = index;
  64940. skeleton.bones.push(_this);
  64941. _this.setParent(parentBone, false);
  64942. _this._updateDifferenceMatrix();
  64943. return _this;
  64944. }
  64945. Object.defineProperty(Bone.prototype, "_matrix", {
  64946. get: function () {
  64947. return this._localMatrix;
  64948. },
  64949. set: function (val) {
  64950. if (this._localMatrix) {
  64951. this._localMatrix.copyFrom(val);
  64952. }
  64953. else {
  64954. this._localMatrix = val;
  64955. }
  64956. },
  64957. enumerable: true,
  64958. configurable: true
  64959. });
  64960. // Members
  64961. Bone.prototype.getSkeleton = function () {
  64962. return this._skeleton;
  64963. };
  64964. Bone.prototype.getParent = function () {
  64965. return this._parent;
  64966. };
  64967. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  64968. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  64969. if (this._parent === parent) {
  64970. return;
  64971. }
  64972. if (this._parent) {
  64973. var index = this._parent.children.indexOf(this);
  64974. if (index !== -1) {
  64975. this._parent.children.splice(index, 1);
  64976. }
  64977. }
  64978. this._parent = parent;
  64979. if (this._parent) {
  64980. this._parent.children.push(this);
  64981. }
  64982. if (updateDifferenceMatrix) {
  64983. this._updateDifferenceMatrix();
  64984. }
  64985. };
  64986. Bone.prototype.getLocalMatrix = function () {
  64987. return this._localMatrix;
  64988. };
  64989. Bone.prototype.getBaseMatrix = function () {
  64990. return this._baseMatrix;
  64991. };
  64992. Bone.prototype.getRestPose = function () {
  64993. return this._restPose;
  64994. };
  64995. Bone.prototype.returnToRest = function () {
  64996. this.updateMatrix(this._restPose.clone());
  64997. };
  64998. Bone.prototype.getWorldMatrix = function () {
  64999. return this._worldTransform;
  65000. };
  65001. Bone.prototype.getInvertedAbsoluteTransform = function () {
  65002. return this._invertedAbsoluteTransform;
  65003. };
  65004. Bone.prototype.getAbsoluteTransform = function () {
  65005. return this._absoluteTransform;
  65006. };
  65007. Object.defineProperty(Bone.prototype, "position", {
  65008. // Properties (matches AbstractMesh properties)
  65009. get: function () {
  65010. return this.getPosition();
  65011. },
  65012. set: function (newPosition) {
  65013. this.setPosition(newPosition);
  65014. },
  65015. enumerable: true,
  65016. configurable: true
  65017. });
  65018. Object.defineProperty(Bone.prototype, "rotation", {
  65019. get: function () {
  65020. return this.getRotation();
  65021. },
  65022. set: function (newRotation) {
  65023. this.setRotation(newRotation);
  65024. },
  65025. enumerable: true,
  65026. configurable: true
  65027. });
  65028. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  65029. get: function () {
  65030. return this.getRotationQuaternion();
  65031. },
  65032. set: function (newRotation) {
  65033. this.setRotationQuaternion(newRotation);
  65034. },
  65035. enumerable: true,
  65036. configurable: true
  65037. });
  65038. Object.defineProperty(Bone.prototype, "scaling", {
  65039. get: function () {
  65040. return this.getScale();
  65041. },
  65042. set: function (newScaling) {
  65043. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  65044. },
  65045. enumerable: true,
  65046. configurable: true
  65047. });
  65048. // Methods
  65049. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  65050. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65051. this._baseMatrix = matrix.clone();
  65052. this._localMatrix = matrix.clone();
  65053. this._skeleton._markAsDirty();
  65054. if (updateDifferenceMatrix) {
  65055. this._updateDifferenceMatrix();
  65056. }
  65057. };
  65058. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  65059. if (!rootMatrix) {
  65060. rootMatrix = this._baseMatrix;
  65061. }
  65062. if (this._parent) {
  65063. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65064. }
  65065. else {
  65066. this._absoluteTransform.copyFrom(rootMatrix);
  65067. }
  65068. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  65069. for (var index = 0; index < this.children.length; index++) {
  65070. this.children[index]._updateDifferenceMatrix();
  65071. }
  65072. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  65073. };
  65074. Bone.prototype.markAsDirty = function () {
  65075. this._currentRenderId++;
  65076. this._skeleton._markAsDirty();
  65077. };
  65078. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  65079. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  65080. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  65081. // all animation may be coming from a library skeleton, so may need to create animation
  65082. if (this.animations.length === 0) {
  65083. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  65084. this.animations[0].setKeys([]);
  65085. }
  65086. // get animation info / verify there is such a range from the source bone
  65087. var sourceRange = source.animations[0].getRange(rangeName);
  65088. if (!sourceRange) {
  65089. return false;
  65090. }
  65091. var from = sourceRange.from;
  65092. var to = sourceRange.to;
  65093. var sourceKeys = source.animations[0].getKeys();
  65094. // rescaling prep
  65095. var sourceBoneLength = source.length;
  65096. var sourceParent = source.getParent();
  65097. var parent = this.getParent();
  65098. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  65099. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  65100. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  65101. var destKeys = this.animations[0].getKeys();
  65102. // loop vars declaration
  65103. var orig;
  65104. var origTranslation;
  65105. var mat;
  65106. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  65107. orig = sourceKeys[key];
  65108. if (orig.frame >= from && orig.frame <= to) {
  65109. if (rescaleAsRequired) {
  65110. mat = orig.value.clone();
  65111. // scale based on parent ratio, when bone has parent
  65112. if (parentScalingReqd) {
  65113. origTranslation = mat.getTranslation();
  65114. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  65115. // scale based on skeleton dimension ratio when root bone, and value is passed
  65116. }
  65117. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  65118. origTranslation = mat.getTranslation();
  65119. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  65120. // use original when root bone, and no data for skelDimensionsRatio
  65121. }
  65122. else {
  65123. mat = orig.value;
  65124. }
  65125. }
  65126. else {
  65127. mat = orig.value;
  65128. }
  65129. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  65130. }
  65131. }
  65132. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  65133. return true;
  65134. };
  65135. /**
  65136. * Translate the bone in local or world space.
  65137. * @param vec The amount to translate the bone.
  65138. * @param space The space that the translation is in.
  65139. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65140. */
  65141. Bone.prototype.translate = function (vec, space, mesh) {
  65142. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65143. var lm = this.getLocalMatrix();
  65144. if (space == BABYLON.Space.LOCAL) {
  65145. lm.m[12] += vec.x;
  65146. lm.m[13] += vec.y;
  65147. lm.m[14] += vec.z;
  65148. }
  65149. else {
  65150. var wm = null;
  65151. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65152. if (mesh) {
  65153. wm = mesh.getWorldMatrix();
  65154. }
  65155. this._skeleton.computeAbsoluteTransforms();
  65156. var tmat = Bone._tmpMats[0];
  65157. var tvec = Bone._tmpVecs[0];
  65158. if (this._parent) {
  65159. if (mesh && wm) {
  65160. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65161. tmat.multiplyToRef(wm, tmat);
  65162. }
  65163. else {
  65164. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65165. }
  65166. }
  65167. tmat.m[12] = 0;
  65168. tmat.m[13] = 0;
  65169. tmat.m[14] = 0;
  65170. tmat.invert();
  65171. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  65172. lm.m[12] += tvec.x;
  65173. lm.m[13] += tvec.y;
  65174. lm.m[14] += tvec.z;
  65175. }
  65176. this.markAsDirty();
  65177. };
  65178. /**
  65179. * Set the postion of the bone in local or world space.
  65180. * @param position The position to set the bone.
  65181. * @param space The space that the position is in.
  65182. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65183. */
  65184. Bone.prototype.setPosition = function (position, space, mesh) {
  65185. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65186. var lm = this.getLocalMatrix();
  65187. if (space == BABYLON.Space.LOCAL) {
  65188. lm.m[12] = position.x;
  65189. lm.m[13] = position.y;
  65190. lm.m[14] = position.z;
  65191. }
  65192. else {
  65193. var wm = null;
  65194. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65195. if (mesh) {
  65196. wm = mesh.getWorldMatrix();
  65197. }
  65198. this._skeleton.computeAbsoluteTransforms();
  65199. var tmat = Bone._tmpMats[0];
  65200. var vec = Bone._tmpVecs[0];
  65201. if (this._parent) {
  65202. if (mesh && wm) {
  65203. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65204. tmat.multiplyToRef(wm, tmat);
  65205. }
  65206. else {
  65207. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65208. }
  65209. }
  65210. tmat.invert();
  65211. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  65212. lm.m[12] = vec.x;
  65213. lm.m[13] = vec.y;
  65214. lm.m[14] = vec.z;
  65215. }
  65216. this.markAsDirty();
  65217. };
  65218. /**
  65219. * Set the absolute postion of the bone (world space).
  65220. * @param position The position to set the bone.
  65221. * @param mesh The mesh that this bone is attached to.
  65222. */
  65223. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  65224. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  65225. };
  65226. /**
  65227. * Set the scale of the bone on the x, y and z axes.
  65228. * @param x The scale of the bone on the x axis.
  65229. * @param x The scale of the bone on the y axis.
  65230. * @param z The scale of the bone on the z axis.
  65231. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65232. */
  65233. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  65234. if (scaleChildren === void 0) { scaleChildren = false; }
  65235. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  65236. if (!scaleChildren) {
  65237. this._negateScaleChildren.x = 1 / x;
  65238. this._negateScaleChildren.y = 1 / y;
  65239. this._negateScaleChildren.z = 1 / z;
  65240. }
  65241. this._syncScaleVector();
  65242. }
  65243. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  65244. };
  65245. /**
  65246. * Scale the bone on the x, y and z axes.
  65247. * @param x The amount to scale the bone on the x axis.
  65248. * @param x The amount to scale the bone on the y axis.
  65249. * @param z The amount to scale the bone on the z axis.
  65250. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65251. */
  65252. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  65253. if (scaleChildren === void 0) { scaleChildren = false; }
  65254. var locMat = this.getLocalMatrix();
  65255. var origLocMat = Bone._tmpMats[0];
  65256. origLocMat.copyFrom(locMat);
  65257. var origLocMatInv = Bone._tmpMats[1];
  65258. origLocMatInv.copyFrom(origLocMat);
  65259. origLocMatInv.invert();
  65260. var scaleMat = Bone._tmpMats[2];
  65261. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  65262. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  65263. this._scaleVector.x *= x;
  65264. this._scaleVector.y *= y;
  65265. this._scaleVector.z *= z;
  65266. locMat.multiplyToRef(origLocMatInv, locMat);
  65267. locMat.multiplyToRef(scaleMat, locMat);
  65268. locMat.multiplyToRef(origLocMat, locMat);
  65269. var parent = this.getParent();
  65270. if (parent) {
  65271. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  65272. }
  65273. else {
  65274. this.getAbsoluteTransform().copyFrom(locMat);
  65275. }
  65276. var len = this.children.length;
  65277. scaleMat.invert();
  65278. for (var i = 0; i < len; i++) {
  65279. var child = this.children[i];
  65280. var cm = child.getLocalMatrix();
  65281. cm.multiplyToRef(scaleMat, cm);
  65282. var lm = child.getLocalMatrix();
  65283. lm.m[12] *= x;
  65284. lm.m[13] *= y;
  65285. lm.m[14] *= z;
  65286. }
  65287. this.computeAbsoluteTransforms();
  65288. if (scaleChildren) {
  65289. for (var i = 0; i < len; i++) {
  65290. this.children[i].scale(x, y, z, scaleChildren);
  65291. }
  65292. }
  65293. this.markAsDirty();
  65294. };
  65295. /**
  65296. * Set the yaw, pitch, and roll of the bone in local or world space.
  65297. * @param yaw The rotation of the bone on the y axis.
  65298. * @param pitch The rotation of the bone on the x axis.
  65299. * @param roll The rotation of the bone on the z axis.
  65300. * @param space The space that the axes of rotation are in.
  65301. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65302. */
  65303. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  65304. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65305. var rotMat = Bone._tmpMats[0];
  65306. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  65307. var rotMatInv = Bone._tmpMats[1];
  65308. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65309. rotMatInv.multiplyToRef(rotMat, rotMat);
  65310. this._rotateWithMatrix(rotMat, space, mesh);
  65311. };
  65312. /**
  65313. * Rotate the bone on an axis in local or world space.
  65314. * @param axis The axis to rotate the bone on.
  65315. * @param amount The amount to rotate the bone.
  65316. * @param space The space that the axis is in.
  65317. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65318. */
  65319. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  65320. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65321. var rmat = Bone._tmpMats[0];
  65322. rmat.m[12] = 0;
  65323. rmat.m[13] = 0;
  65324. rmat.m[14] = 0;
  65325. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  65326. this._rotateWithMatrix(rmat, space, mesh);
  65327. };
  65328. /**
  65329. * Set the rotation of the bone to a particular axis angle in local or world space.
  65330. * @param axis The axis to rotate the bone on.
  65331. * @param angle The angle that the bone should be rotated to.
  65332. * @param space The space that the axis is in.
  65333. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65334. */
  65335. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  65336. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65337. var rotMat = Bone._tmpMats[0];
  65338. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  65339. var rotMatInv = Bone._tmpMats[1];
  65340. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65341. rotMatInv.multiplyToRef(rotMat, rotMat);
  65342. this._rotateWithMatrix(rotMat, space, mesh);
  65343. };
  65344. /**
  65345. * Set the euler rotation of the bone in local of world space.
  65346. * @param rotation The euler rotation that the bone should be set to.
  65347. * @param space The space that the rotation is in.
  65348. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65349. */
  65350. Bone.prototype.setRotation = function (rotation, space, mesh) {
  65351. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65352. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  65353. };
  65354. /**
  65355. * Set the quaternion rotation of the bone in local of world space.
  65356. * @param quat The quaternion rotation that the bone should be set to.
  65357. * @param space The space that the rotation is in.
  65358. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65359. */
  65360. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  65361. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65362. var rotMatInv = Bone._tmpMats[0];
  65363. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65364. var rotMat = Bone._tmpMats[1];
  65365. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  65366. rotMatInv.multiplyToRef(rotMat, rotMat);
  65367. this._rotateWithMatrix(rotMat, space, mesh);
  65368. };
  65369. /**
  65370. * Set the rotation matrix of the bone in local of world space.
  65371. * @param rotMat The rotation matrix that the bone should be set to.
  65372. * @param space The space that the rotation is in.
  65373. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65374. */
  65375. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  65376. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65377. var rotMatInv = Bone._tmpMats[0];
  65378. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65379. var rotMat2 = Bone._tmpMats[1];
  65380. rotMat2.copyFrom(rotMat);
  65381. rotMatInv.multiplyToRef(rotMat, rotMat2);
  65382. this._rotateWithMatrix(rotMat2, space, mesh);
  65383. };
  65384. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  65385. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65386. var lmat = this.getLocalMatrix();
  65387. var lx = lmat.m[12];
  65388. var ly = lmat.m[13];
  65389. var lz = lmat.m[14];
  65390. var parent = this.getParent();
  65391. var parentScale = Bone._tmpMats[3];
  65392. var parentScaleInv = Bone._tmpMats[4];
  65393. if (parent) {
  65394. if (space == BABYLON.Space.WORLD) {
  65395. if (mesh) {
  65396. parentScale.copyFrom(mesh.getWorldMatrix());
  65397. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  65398. }
  65399. else {
  65400. parentScale.copyFrom(parent.getAbsoluteTransform());
  65401. }
  65402. }
  65403. else {
  65404. parentScale = parent._scaleMatrix;
  65405. }
  65406. parentScaleInv.copyFrom(parentScale);
  65407. parentScaleInv.invert();
  65408. lmat.multiplyToRef(parentScale, lmat);
  65409. lmat.multiplyToRef(rmat, lmat);
  65410. lmat.multiplyToRef(parentScaleInv, lmat);
  65411. }
  65412. else {
  65413. if (space == BABYLON.Space.WORLD && mesh) {
  65414. parentScale.copyFrom(mesh.getWorldMatrix());
  65415. parentScaleInv.copyFrom(parentScale);
  65416. parentScaleInv.invert();
  65417. lmat.multiplyToRef(parentScale, lmat);
  65418. lmat.multiplyToRef(rmat, lmat);
  65419. lmat.multiplyToRef(parentScaleInv, lmat);
  65420. }
  65421. else {
  65422. lmat.multiplyToRef(rmat, lmat);
  65423. }
  65424. }
  65425. lmat.m[12] = lx;
  65426. lmat.m[13] = ly;
  65427. lmat.m[14] = lz;
  65428. this.computeAbsoluteTransforms();
  65429. this.markAsDirty();
  65430. };
  65431. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  65432. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65433. if (space == BABYLON.Space.WORLD) {
  65434. var scaleMatrix = Bone._tmpMats[2];
  65435. scaleMatrix.copyFrom(this._scaleMatrix);
  65436. rotMatInv.copyFrom(this.getAbsoluteTransform());
  65437. if (mesh) {
  65438. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  65439. var meshScale = Bone._tmpMats[3];
  65440. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  65441. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  65442. }
  65443. rotMatInv.invert();
  65444. scaleMatrix.m[0] *= this._scalingDeterminant;
  65445. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65446. }
  65447. else {
  65448. rotMatInv.copyFrom(this.getLocalMatrix());
  65449. rotMatInv.invert();
  65450. var scaleMatrix = Bone._tmpMats[2];
  65451. scaleMatrix.copyFrom(this._scaleMatrix);
  65452. if (this._parent) {
  65453. var pscaleMatrix = Bone._tmpMats[3];
  65454. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  65455. pscaleMatrix.invert();
  65456. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  65457. }
  65458. else {
  65459. scaleMatrix.m[0] *= this._scalingDeterminant;
  65460. }
  65461. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65462. }
  65463. };
  65464. /**
  65465. * Get the scale of the bone
  65466. * @returns the scale of the bone
  65467. */
  65468. Bone.prototype.getScale = function () {
  65469. return this._scaleVector.clone();
  65470. };
  65471. /**
  65472. * Copy the scale of the bone to a vector3.
  65473. * @param result The vector3 to copy the scale to
  65474. */
  65475. Bone.prototype.getScaleToRef = function (result) {
  65476. result.copyFrom(this._scaleVector);
  65477. };
  65478. /**
  65479. * Get the position of the bone in local or world space.
  65480. * @param space The space that the returned position is in.
  65481. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65482. * @returns The position of the bone
  65483. */
  65484. Bone.prototype.getPosition = function (space, mesh) {
  65485. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65486. if (mesh === void 0) { mesh = null; }
  65487. var pos = BABYLON.Vector3.Zero();
  65488. this.getPositionToRef(space, mesh, pos);
  65489. return pos;
  65490. };
  65491. /**
  65492. * Copy the position of the bone to a vector3 in local or world space.
  65493. * @param space The space that the returned position is in.
  65494. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65495. * @param result The vector3 to copy the position to.
  65496. */
  65497. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  65498. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65499. if (space == BABYLON.Space.LOCAL) {
  65500. var lm = this.getLocalMatrix();
  65501. result.x = lm.m[12];
  65502. result.y = lm.m[13];
  65503. result.z = lm.m[14];
  65504. }
  65505. else {
  65506. var wm = null;
  65507. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65508. if (mesh) {
  65509. wm = mesh.getWorldMatrix();
  65510. }
  65511. this._skeleton.computeAbsoluteTransforms();
  65512. var tmat = Bone._tmpMats[0];
  65513. if (mesh && wm) {
  65514. tmat.copyFrom(this.getAbsoluteTransform());
  65515. tmat.multiplyToRef(wm, tmat);
  65516. }
  65517. else {
  65518. tmat = this.getAbsoluteTransform();
  65519. }
  65520. result.x = tmat.m[12];
  65521. result.y = tmat.m[13];
  65522. result.z = tmat.m[14];
  65523. }
  65524. };
  65525. /**
  65526. * Get the absolute position of the bone (world space).
  65527. * @param mesh The mesh that this bone is attached to.
  65528. * @returns The absolute position of the bone
  65529. */
  65530. Bone.prototype.getAbsolutePosition = function (mesh) {
  65531. if (mesh === void 0) { mesh = null; }
  65532. var pos = BABYLON.Vector3.Zero();
  65533. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  65534. return pos;
  65535. };
  65536. /**
  65537. * Copy the absolute position of the bone (world space) to the result param.
  65538. * @param mesh The mesh that this bone is attached to.
  65539. * @param result The vector3 to copy the absolute position to.
  65540. */
  65541. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  65542. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  65543. };
  65544. /**
  65545. * Compute the absolute transforms of this bone and its children.
  65546. */
  65547. Bone.prototype.computeAbsoluteTransforms = function () {
  65548. if (this._parent) {
  65549. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65550. }
  65551. else {
  65552. this._absoluteTransform.copyFrom(this._localMatrix);
  65553. var poseMatrix = this._skeleton.getPoseMatrix();
  65554. if (poseMatrix) {
  65555. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  65556. }
  65557. }
  65558. var children = this.children;
  65559. var len = children.length;
  65560. for (var i = 0; i < len; i++) {
  65561. children[i].computeAbsoluteTransforms();
  65562. }
  65563. };
  65564. Bone.prototype._syncScaleVector = function () {
  65565. var lm = this.getLocalMatrix();
  65566. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  65567. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  65568. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  65569. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  65570. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  65571. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  65572. this._scaleVector.x = xs * Math.sqrt(xsq);
  65573. this._scaleVector.y = ys * Math.sqrt(ysq);
  65574. this._scaleVector.z = zs * Math.sqrt(zsq);
  65575. if (this._parent) {
  65576. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  65577. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  65578. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  65579. }
  65580. 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);
  65581. };
  65582. /**
  65583. * Get the world direction from an axis that is in the local space of the bone.
  65584. * @param localAxis The local direction that is used to compute the world direction.
  65585. * @param mesh The mesh that this bone is attached to.
  65586. * @returns The world direction
  65587. */
  65588. Bone.prototype.getDirection = function (localAxis, mesh) {
  65589. if (mesh === void 0) { mesh = null; }
  65590. var result = BABYLON.Vector3.Zero();
  65591. this.getDirectionToRef(localAxis, mesh, result);
  65592. return result;
  65593. };
  65594. /**
  65595. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  65596. * @param localAxis The local direction that is used to compute the world direction.
  65597. * @param mesh The mesh that this bone is attached to.
  65598. * @param result The vector3 that the world direction will be copied to.
  65599. */
  65600. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  65601. if (mesh === void 0) { mesh = null; }
  65602. var wm = null;
  65603. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65604. if (mesh) {
  65605. wm = mesh.getWorldMatrix();
  65606. }
  65607. this._skeleton.computeAbsoluteTransforms();
  65608. var mat = Bone._tmpMats[0];
  65609. mat.copyFrom(this.getAbsoluteTransform());
  65610. if (mesh && wm) {
  65611. mat.multiplyToRef(wm, mat);
  65612. }
  65613. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  65614. result.normalize();
  65615. };
  65616. /**
  65617. * Get the euler rotation of the bone in local or world space.
  65618. * @param space The space that the rotation should be in.
  65619. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65620. * @returns The euler rotation
  65621. */
  65622. Bone.prototype.getRotation = function (space, mesh) {
  65623. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65624. if (mesh === void 0) { mesh = null; }
  65625. var result = BABYLON.Vector3.Zero();
  65626. this.getRotationToRef(space, mesh, result);
  65627. return result;
  65628. };
  65629. /**
  65630. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  65631. * @param space The space that the rotation should be in.
  65632. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65633. * @param result The vector3 that the rotation should be copied to.
  65634. */
  65635. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  65636. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65637. if (mesh === void 0) { mesh = null; }
  65638. var quat = Bone._tmpQuat;
  65639. this.getRotationQuaternionToRef(space, mesh, quat);
  65640. quat.toEulerAnglesToRef(result);
  65641. };
  65642. /**
  65643. * Get the quaternion rotation of the bone in either local or world space.
  65644. * @param space The space that the rotation should be in.
  65645. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65646. * @returns The quaternion rotation
  65647. */
  65648. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  65649. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65650. if (mesh === void 0) { mesh = null; }
  65651. var result = BABYLON.Quaternion.Identity();
  65652. this.getRotationQuaternionToRef(space, mesh, result);
  65653. return result;
  65654. };
  65655. /**
  65656. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  65657. * @param space The space that the rotation should be in.
  65658. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65659. * @param result The quaternion that the rotation should be copied to.
  65660. */
  65661. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  65662. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65663. if (mesh === void 0) { mesh = null; }
  65664. if (space == BABYLON.Space.LOCAL) {
  65665. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  65666. }
  65667. else {
  65668. var mat = Bone._tmpMats[0];
  65669. var amat = this.getAbsoluteTransform();
  65670. if (mesh) {
  65671. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  65672. }
  65673. else {
  65674. mat.copyFrom(amat);
  65675. }
  65676. mat.m[0] *= this._scalingDeterminant;
  65677. mat.m[1] *= this._scalingDeterminant;
  65678. mat.m[2] *= this._scalingDeterminant;
  65679. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  65680. }
  65681. };
  65682. /**
  65683. * Get the rotation matrix of the bone in local or world space.
  65684. * @param space The space that the rotation should be in.
  65685. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65686. * @returns The rotation matrix
  65687. */
  65688. Bone.prototype.getRotationMatrix = function (space, mesh) {
  65689. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65690. var result = BABYLON.Matrix.Identity();
  65691. this.getRotationMatrixToRef(space, mesh, result);
  65692. return result;
  65693. };
  65694. /**
  65695. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  65696. * @param space The space that the rotation should be in.
  65697. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65698. * @param result The quaternion that the rotation should be copied to.
  65699. */
  65700. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  65701. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65702. if (space == BABYLON.Space.LOCAL) {
  65703. this.getLocalMatrix().getRotationMatrixToRef(result);
  65704. }
  65705. else {
  65706. var mat = Bone._tmpMats[0];
  65707. var amat = this.getAbsoluteTransform();
  65708. if (mesh) {
  65709. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  65710. }
  65711. else {
  65712. mat.copyFrom(amat);
  65713. }
  65714. mat.m[0] *= this._scalingDeterminant;
  65715. mat.m[1] *= this._scalingDeterminant;
  65716. mat.m[2] *= this._scalingDeterminant;
  65717. mat.getRotationMatrixToRef(result);
  65718. }
  65719. };
  65720. /**
  65721. * Get the world position of a point that is in the local space of the bone.
  65722. * @param position The local position
  65723. * @param mesh The mesh that this bone is attached to.
  65724. * @returns The world position
  65725. */
  65726. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  65727. if (mesh === void 0) { mesh = null; }
  65728. var result = BABYLON.Vector3.Zero();
  65729. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  65730. return result;
  65731. };
  65732. /**
  65733. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  65734. * @param position The local position
  65735. * @param mesh The mesh that this bone is attached to.
  65736. * @param result The vector3 that the world position should be copied to.
  65737. */
  65738. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  65739. if (mesh === void 0) { mesh = null; }
  65740. var wm = null;
  65741. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65742. if (mesh) {
  65743. wm = mesh.getWorldMatrix();
  65744. }
  65745. this._skeleton.computeAbsoluteTransforms();
  65746. var tmat = Bone._tmpMats[0];
  65747. if (mesh && wm) {
  65748. tmat.copyFrom(this.getAbsoluteTransform());
  65749. tmat.multiplyToRef(wm, tmat);
  65750. }
  65751. else {
  65752. tmat = this.getAbsoluteTransform();
  65753. }
  65754. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  65755. };
  65756. /**
  65757. * Get the local position of a point that is in world space.
  65758. * @param position The world position
  65759. * @param mesh The mesh that this bone is attached to.
  65760. * @returns The local position
  65761. */
  65762. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  65763. if (mesh === void 0) { mesh = null; }
  65764. var result = BABYLON.Vector3.Zero();
  65765. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  65766. return result;
  65767. };
  65768. /**
  65769. * Get the local position of a point that is in world space and copy it to the result param.
  65770. * @param position The world position
  65771. * @param mesh The mesh that this bone is attached to.
  65772. * @param result The vector3 that the local position should be copied to.
  65773. */
  65774. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  65775. if (mesh === void 0) { mesh = null; }
  65776. var wm = null;
  65777. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65778. if (mesh) {
  65779. wm = mesh.getWorldMatrix();
  65780. }
  65781. this._skeleton.computeAbsoluteTransforms();
  65782. var tmat = Bone._tmpMats[0];
  65783. tmat.copyFrom(this.getAbsoluteTransform());
  65784. if (mesh && wm) {
  65785. tmat.multiplyToRef(wm, tmat);
  65786. }
  65787. tmat.invert();
  65788. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  65789. };
  65790. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65791. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  65792. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  65793. return Bone;
  65794. }(BABYLON.Node));
  65795. BABYLON.Bone = Bone;
  65796. })(BABYLON || (BABYLON = {}));
  65797. //# sourceMappingURL=babylon.bone.js.map
  65798. var BABYLON;
  65799. (function (BABYLON) {
  65800. var BoneIKController = /** @class */ (function () {
  65801. function BoneIKController(mesh, bone, options) {
  65802. this.targetPosition = BABYLON.Vector3.Zero();
  65803. this.poleTargetPosition = BABYLON.Vector3.Zero();
  65804. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  65805. this.poleAngle = 0;
  65806. this.slerpAmount = 1;
  65807. this._bone1Quat = BABYLON.Quaternion.Identity();
  65808. this._bone1Mat = BABYLON.Matrix.Identity();
  65809. this._bone2Ang = Math.PI;
  65810. this._maxAngle = Math.PI;
  65811. this._rightHandedSystem = false;
  65812. this._bendAxis = BABYLON.Vector3.Right();
  65813. this._slerping = false;
  65814. this._adjustRoll = 0;
  65815. this._bone2 = bone;
  65816. this._bone1 = bone.getParent();
  65817. if (!this._bone1) {
  65818. return;
  65819. }
  65820. this.mesh = mesh;
  65821. var bonePos = bone.getPosition();
  65822. if (bone.getAbsoluteTransform().determinant() > 0) {
  65823. this._rightHandedSystem = true;
  65824. this._bendAxis.x = 0;
  65825. this._bendAxis.y = 0;
  65826. this._bendAxis.z = -1;
  65827. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  65828. this._adjustRoll = Math.PI * .5;
  65829. this._bendAxis.z = 1;
  65830. }
  65831. }
  65832. if (this._bone1.length) {
  65833. var boneScale1 = this._bone1.getScale();
  65834. var boneScale2 = this._bone2.getScale();
  65835. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  65836. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  65837. }
  65838. else if (this._bone1.children[0]) {
  65839. mesh.computeWorldMatrix(true);
  65840. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  65841. var pos2 = this._bone2.getAbsolutePosition(mesh);
  65842. var pos3 = this._bone1.getAbsolutePosition(mesh);
  65843. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  65844. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  65845. }
  65846. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  65847. this.maxAngle = Math.PI;
  65848. if (options) {
  65849. if (options.targetMesh) {
  65850. this.targetMesh = options.targetMesh;
  65851. this.targetMesh.computeWorldMatrix(true);
  65852. }
  65853. if (options.poleTargetMesh) {
  65854. this.poleTargetMesh = options.poleTargetMesh;
  65855. this.poleTargetMesh.computeWorldMatrix(true);
  65856. }
  65857. else if (options.poleTargetBone) {
  65858. this.poleTargetBone = options.poleTargetBone;
  65859. }
  65860. else if (this._bone1.getParent()) {
  65861. this.poleTargetBone = this._bone1.getParent();
  65862. }
  65863. if (options.poleTargetLocalOffset) {
  65864. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  65865. }
  65866. if (options.poleAngle) {
  65867. this.poleAngle = options.poleAngle;
  65868. }
  65869. if (options.bendAxis) {
  65870. this._bendAxis.copyFrom(options.bendAxis);
  65871. }
  65872. if (options.maxAngle) {
  65873. this.maxAngle = options.maxAngle;
  65874. }
  65875. if (options.slerpAmount) {
  65876. this.slerpAmount = options.slerpAmount;
  65877. }
  65878. }
  65879. }
  65880. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  65881. get: function () {
  65882. return this._maxAngle;
  65883. },
  65884. set: function (value) {
  65885. this._setMaxAngle(value);
  65886. },
  65887. enumerable: true,
  65888. configurable: true
  65889. });
  65890. BoneIKController.prototype._setMaxAngle = function (ang) {
  65891. if (ang < 0) {
  65892. ang = 0;
  65893. }
  65894. if (ang > Math.PI || ang == undefined) {
  65895. ang = Math.PI;
  65896. }
  65897. this._maxAngle = ang;
  65898. var a = this._bone1Length;
  65899. var b = this._bone2Length;
  65900. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  65901. };
  65902. BoneIKController.prototype.update = function () {
  65903. var bone1 = this._bone1;
  65904. if (!bone1) {
  65905. return;
  65906. }
  65907. var target = this.targetPosition;
  65908. var poleTarget = this.poleTargetPosition;
  65909. var mat1 = BoneIKController._tmpMats[0];
  65910. var mat2 = BoneIKController._tmpMats[1];
  65911. if (this.targetMesh) {
  65912. target.copyFrom(this.targetMesh.getAbsolutePosition());
  65913. }
  65914. if (this.poleTargetBone) {
  65915. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  65916. }
  65917. else if (this.poleTargetMesh) {
  65918. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  65919. }
  65920. var bonePos = BoneIKController._tmpVecs[0];
  65921. var zaxis = BoneIKController._tmpVecs[1];
  65922. var xaxis = BoneIKController._tmpVecs[2];
  65923. var yaxis = BoneIKController._tmpVecs[3];
  65924. var upAxis = BoneIKController._tmpVecs[4];
  65925. var _tmpQuat = BoneIKController._tmpQuat;
  65926. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  65927. poleTarget.subtractToRef(bonePos, upAxis);
  65928. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  65929. upAxis.y = 1;
  65930. }
  65931. else {
  65932. upAxis.normalize();
  65933. }
  65934. target.subtractToRef(bonePos, yaxis);
  65935. yaxis.normalize();
  65936. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  65937. zaxis.normalize();
  65938. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  65939. xaxis.normalize();
  65940. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  65941. var a = this._bone1Length;
  65942. var b = this._bone2Length;
  65943. var c = BABYLON.Vector3.Distance(bonePos, target);
  65944. if (this._maxReach > 0) {
  65945. c = Math.min(this._maxReach, c);
  65946. }
  65947. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  65948. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  65949. if (acosa > 1) {
  65950. acosa = 1;
  65951. }
  65952. if (acosb > 1) {
  65953. acosb = 1;
  65954. }
  65955. if (acosa < -1) {
  65956. acosa = -1;
  65957. }
  65958. if (acosb < -1) {
  65959. acosb = -1;
  65960. }
  65961. var angA = Math.acos(acosa);
  65962. var angB = Math.acos(acosb);
  65963. var angC = -angA - angB;
  65964. if (this._rightHandedSystem) {
  65965. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  65966. mat2.multiplyToRef(mat1, mat1);
  65967. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  65968. mat2.multiplyToRef(mat1, mat1);
  65969. }
  65970. else {
  65971. var _tmpVec = BoneIKController._tmpVecs[5];
  65972. _tmpVec.copyFrom(this._bendAxis);
  65973. _tmpVec.x *= -1;
  65974. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  65975. mat2.multiplyToRef(mat1, mat1);
  65976. }
  65977. if (this.poleAngle) {
  65978. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  65979. mat1.multiplyToRef(mat2, mat1);
  65980. }
  65981. if (this._bone1) {
  65982. if (this.slerpAmount < 1) {
  65983. if (!this._slerping) {
  65984. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  65985. }
  65986. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  65987. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  65988. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  65989. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  65990. this._slerping = true;
  65991. }
  65992. else {
  65993. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  65994. this._bone1Mat.copyFrom(mat1);
  65995. this._slerping = false;
  65996. }
  65997. }
  65998. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  65999. this._bone2Ang = angC;
  66000. };
  66001. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66002. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  66003. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66004. return BoneIKController;
  66005. }());
  66006. BABYLON.BoneIKController = BoneIKController;
  66007. })(BABYLON || (BABYLON = {}));
  66008. //# sourceMappingURL=babylon.boneIKController.js.map
  66009. var BABYLON;
  66010. (function (BABYLON) {
  66011. var BoneLookController = /** @class */ (function () {
  66012. /**
  66013. * Create a BoneLookController
  66014. * @param mesh the mesh that the bone belongs to
  66015. * @param bone the bone that will be looking to the target
  66016. * @param target the target Vector3 to look at
  66017. * @param settings optional settings:
  66018. * - maxYaw: the maximum angle the bone will yaw to
  66019. * - minYaw: the minimum angle the bone will yaw to
  66020. * - maxPitch: the maximum angle the bone will pitch to
  66021. * - minPitch: the minimum angle the bone will yaw to
  66022. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  66023. * - upAxis: the up axis of the coordinate system
  66024. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66025. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  66026. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  66027. * - adjustYaw: used to make an adjustment to the yaw of the bone
  66028. * - adjustPitch: used to make an adjustment to the pitch of the bone
  66029. * - adjustRoll: used to make an adjustment to the roll of the bone
  66030. **/
  66031. function BoneLookController(mesh, bone, target, options) {
  66032. /**
  66033. * The up axis of the coordinate system that is used when the bone is rotated.
  66034. */
  66035. this.upAxis = BABYLON.Vector3.Up();
  66036. /**
  66037. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66038. */
  66039. this.upAxisSpace = BABYLON.Space.LOCAL;
  66040. /**
  66041. * Used to make an adjustment to the yaw of the bone.
  66042. */
  66043. this.adjustYaw = 0;
  66044. /**
  66045. * Used to make an adjustment to the pitch of the bone.
  66046. */
  66047. this.adjustPitch = 0;
  66048. /**
  66049. * Used to make an adjustment to the roll of the bone.
  66050. */
  66051. this.adjustRoll = 0;
  66052. /**
  66053. * 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).
  66054. */
  66055. this.slerpAmount = 1;
  66056. this._boneQuat = BABYLON.Quaternion.Identity();
  66057. this._slerping = false;
  66058. this._firstFrameSkipped = false;
  66059. this._fowardAxis = BABYLON.Vector3.Forward();
  66060. this.mesh = mesh;
  66061. this.bone = bone;
  66062. this.target = target;
  66063. if (options) {
  66064. if (options.adjustYaw) {
  66065. this.adjustYaw = options.adjustYaw;
  66066. }
  66067. if (options.adjustPitch) {
  66068. this.adjustPitch = options.adjustPitch;
  66069. }
  66070. if (options.adjustRoll) {
  66071. this.adjustRoll = options.adjustRoll;
  66072. }
  66073. if (options.maxYaw != null) {
  66074. this.maxYaw = options.maxYaw;
  66075. }
  66076. else {
  66077. this.maxYaw = Math.PI;
  66078. }
  66079. if (options.minYaw != null) {
  66080. this.minYaw = options.minYaw;
  66081. }
  66082. else {
  66083. this.minYaw = -Math.PI;
  66084. }
  66085. if (options.maxPitch != null) {
  66086. this.maxPitch = options.maxPitch;
  66087. }
  66088. else {
  66089. this.maxPitch = Math.PI;
  66090. }
  66091. if (options.minPitch != null) {
  66092. this.minPitch = options.minPitch;
  66093. }
  66094. else {
  66095. this.minPitch = -Math.PI;
  66096. }
  66097. if (options.slerpAmount != null) {
  66098. this.slerpAmount = options.slerpAmount;
  66099. }
  66100. if (options.upAxis != null) {
  66101. this.upAxis = options.upAxis;
  66102. }
  66103. if (options.upAxisSpace != null) {
  66104. this.upAxisSpace = options.upAxisSpace;
  66105. }
  66106. if (options.yawAxis != null || options.pitchAxis != null) {
  66107. var newYawAxis = BABYLON.Axis.Y;
  66108. var newPitchAxis = BABYLON.Axis.X;
  66109. if (options.yawAxis != null) {
  66110. newYawAxis = options.yawAxis.clone();
  66111. newYawAxis.normalize();
  66112. }
  66113. if (options.pitchAxis != null) {
  66114. newPitchAxis = options.pitchAxis.clone();
  66115. newPitchAxis.normalize();
  66116. }
  66117. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  66118. this._transformYawPitch = BABYLON.Matrix.Identity();
  66119. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  66120. this._transformYawPitchInv = this._transformYawPitch.clone();
  66121. this._transformYawPitch.invert();
  66122. }
  66123. }
  66124. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  66125. this.upAxisSpace = BABYLON.Space.LOCAL;
  66126. }
  66127. }
  66128. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  66129. /**
  66130. * Get/set the minimum yaw angle that the bone can look to.
  66131. */
  66132. get: function () {
  66133. return this._minYaw;
  66134. },
  66135. set: function (value) {
  66136. this._minYaw = value;
  66137. this._minYawSin = Math.sin(value);
  66138. this._minYawCos = Math.cos(value);
  66139. if (this._maxYaw != null) {
  66140. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66141. this._yawRange = this._maxYaw - this._minYaw;
  66142. }
  66143. },
  66144. enumerable: true,
  66145. configurable: true
  66146. });
  66147. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  66148. /**
  66149. * Get/set the maximum yaw angle that the bone can look to.
  66150. */
  66151. get: function () {
  66152. return this._maxYaw;
  66153. },
  66154. set: function (value) {
  66155. this._maxYaw = value;
  66156. this._maxYawSin = Math.sin(value);
  66157. this._maxYawCos = Math.cos(value);
  66158. if (this._minYaw != null) {
  66159. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66160. this._yawRange = this._maxYaw - this._minYaw;
  66161. }
  66162. },
  66163. enumerable: true,
  66164. configurable: true
  66165. });
  66166. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  66167. /**
  66168. * Get/set the minimum pitch angle that the bone can look to.
  66169. */
  66170. get: function () {
  66171. return this._minPitch;
  66172. },
  66173. set: function (value) {
  66174. this._minPitch = value;
  66175. this._minPitchTan = Math.tan(value);
  66176. },
  66177. enumerable: true,
  66178. configurable: true
  66179. });
  66180. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  66181. /**
  66182. * Get/set the maximum pitch angle that the bone can look to.
  66183. */
  66184. get: function () {
  66185. return this._maxPitch;
  66186. },
  66187. set: function (value) {
  66188. this._maxPitch = value;
  66189. this._maxPitchTan = Math.tan(value);
  66190. },
  66191. enumerable: true,
  66192. configurable: true
  66193. });
  66194. /**
  66195. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  66196. */
  66197. BoneLookController.prototype.update = function () {
  66198. //skip the first frame when slerping so that the mesh rotation is correct
  66199. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  66200. this._firstFrameSkipped = true;
  66201. return;
  66202. }
  66203. var bone = this.bone;
  66204. var bonePos = BoneLookController._tmpVecs[0];
  66205. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  66206. var target = this.target;
  66207. var _tmpMat1 = BoneLookController._tmpMats[0];
  66208. var _tmpMat2 = BoneLookController._tmpMats[1];
  66209. var mesh = this.mesh;
  66210. var parentBone = bone.getParent();
  66211. var upAxis = BoneLookController._tmpVecs[1];
  66212. upAxis.copyFrom(this.upAxis);
  66213. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  66214. if (this._transformYawPitch) {
  66215. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  66216. }
  66217. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  66218. }
  66219. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  66220. mesh.getDirectionToRef(upAxis, upAxis);
  66221. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  66222. upAxis.normalize();
  66223. }
  66224. }
  66225. var checkYaw = false;
  66226. var checkPitch = false;
  66227. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  66228. checkYaw = true;
  66229. }
  66230. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  66231. checkPitch = true;
  66232. }
  66233. if (checkYaw || checkPitch) {
  66234. var spaceMat = BoneLookController._tmpMats[2];
  66235. var spaceMatInv = BoneLookController._tmpMats[3];
  66236. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  66237. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  66238. }
  66239. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  66240. spaceMat.copyFrom(mesh.getWorldMatrix());
  66241. }
  66242. else {
  66243. var forwardAxis = BoneLookController._tmpVecs[2];
  66244. forwardAxis.copyFrom(this._fowardAxis);
  66245. if (this._transformYawPitch) {
  66246. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  66247. }
  66248. if (parentBone) {
  66249. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  66250. }
  66251. else {
  66252. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  66253. }
  66254. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  66255. rightAxis.normalize();
  66256. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  66257. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  66258. }
  66259. spaceMat.invertToRef(spaceMatInv);
  66260. var xzlen = null;
  66261. if (checkPitch) {
  66262. var localTarget = BoneLookController._tmpVecs[3];
  66263. target.subtractToRef(bonePos, localTarget);
  66264. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66265. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66266. var pitch = Math.atan2(localTarget.y, xzlen);
  66267. var newPitch = pitch;
  66268. if (pitch > this._maxPitch) {
  66269. localTarget.y = this._maxPitchTan * xzlen;
  66270. newPitch = this._maxPitch;
  66271. }
  66272. else if (pitch < this._minPitch) {
  66273. localTarget.y = this._minPitchTan * xzlen;
  66274. newPitch = this._minPitch;
  66275. }
  66276. if (pitch != newPitch) {
  66277. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66278. localTarget.addInPlace(bonePos);
  66279. target = localTarget;
  66280. }
  66281. }
  66282. if (checkYaw) {
  66283. var localTarget = BoneLookController._tmpVecs[4];
  66284. target.subtractToRef(bonePos, localTarget);
  66285. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66286. var yaw = Math.atan2(localTarget.x, localTarget.z);
  66287. var newYaw = yaw;
  66288. if (yaw > this._maxYaw || yaw < this._minYaw) {
  66289. if (xzlen == null) {
  66290. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66291. }
  66292. if (this._yawRange > Math.PI) {
  66293. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  66294. localTarget.z = this._maxYawCos * xzlen;
  66295. localTarget.x = this._maxYawSin * xzlen;
  66296. newYaw = this._maxYaw;
  66297. }
  66298. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  66299. localTarget.z = this._minYawCos * xzlen;
  66300. localTarget.x = this._minYawSin * xzlen;
  66301. newYaw = this._minYaw;
  66302. }
  66303. }
  66304. else {
  66305. if (yaw > this._maxYaw) {
  66306. localTarget.z = this._maxYawCos * xzlen;
  66307. localTarget.x = this._maxYawSin * xzlen;
  66308. newYaw = this._maxYaw;
  66309. }
  66310. else if (yaw < this._minYaw) {
  66311. localTarget.z = this._minYawCos * xzlen;
  66312. localTarget.x = this._minYawSin * xzlen;
  66313. newYaw = this._minYaw;
  66314. }
  66315. }
  66316. }
  66317. if (this._slerping && this._yawRange > Math.PI) {
  66318. //are we going to be crossing into the min/max region?
  66319. var boneFwd = BoneLookController._tmpVecs[8];
  66320. boneFwd.copyFrom(BABYLON.Axis.Z);
  66321. if (this._transformYawPitch) {
  66322. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  66323. }
  66324. var boneRotMat = BoneLookController._tmpMats[4];
  66325. this._boneQuat.toRotationMatrix(boneRotMat);
  66326. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  66327. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  66328. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  66329. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  66330. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  66331. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  66332. if (angBtwTar > angBtwMidYaw) {
  66333. if (xzlen == null) {
  66334. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66335. }
  66336. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  66337. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  66338. if (angBtwMin < angBtwMax) {
  66339. newYaw = boneYaw + Math.PI * .75;
  66340. localTarget.z = Math.cos(newYaw) * xzlen;
  66341. localTarget.x = Math.sin(newYaw) * xzlen;
  66342. }
  66343. else {
  66344. newYaw = boneYaw - Math.PI * .75;
  66345. localTarget.z = Math.cos(newYaw) * xzlen;
  66346. localTarget.x = Math.sin(newYaw) * xzlen;
  66347. }
  66348. }
  66349. }
  66350. if (yaw != newYaw) {
  66351. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66352. localTarget.addInPlace(bonePos);
  66353. target = localTarget;
  66354. }
  66355. }
  66356. }
  66357. var zaxis = BoneLookController._tmpVecs[5];
  66358. var xaxis = BoneLookController._tmpVecs[6];
  66359. var yaxis = BoneLookController._tmpVecs[7];
  66360. var _tmpQuat = BoneLookController._tmpQuat;
  66361. target.subtractToRef(bonePos, zaxis);
  66362. zaxis.normalize();
  66363. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  66364. xaxis.normalize();
  66365. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  66366. yaxis.normalize();
  66367. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  66368. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  66369. return;
  66370. }
  66371. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  66372. return;
  66373. }
  66374. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  66375. return;
  66376. }
  66377. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  66378. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  66379. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  66380. }
  66381. if (this.slerpAmount < 1) {
  66382. if (!this._slerping) {
  66383. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  66384. }
  66385. if (this._transformYawPitch) {
  66386. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66387. }
  66388. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  66389. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  66390. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  66391. this._slerping = true;
  66392. }
  66393. else {
  66394. if (this._transformYawPitch) {
  66395. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66396. }
  66397. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  66398. this._slerping = false;
  66399. }
  66400. };
  66401. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  66402. var angDiff = ang2 - ang1;
  66403. angDiff %= Math.PI * 2;
  66404. if (angDiff > Math.PI) {
  66405. angDiff -= Math.PI * 2;
  66406. }
  66407. else if (angDiff < -Math.PI) {
  66408. angDiff += Math.PI * 2;
  66409. }
  66410. return angDiff;
  66411. };
  66412. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  66413. ang1 %= (2 * Math.PI);
  66414. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66415. ang2 %= (2 * Math.PI);
  66416. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66417. var ab = 0;
  66418. if (ang1 < ang2) {
  66419. ab = ang2 - ang1;
  66420. }
  66421. else {
  66422. ab = ang1 - ang2;
  66423. }
  66424. if (ab > Math.PI) {
  66425. ab = Math.PI * 2 - ab;
  66426. }
  66427. return ab;
  66428. };
  66429. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  66430. ang %= (2 * Math.PI);
  66431. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  66432. ang1 %= (2 * Math.PI);
  66433. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66434. ang2 %= (2 * Math.PI);
  66435. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66436. if (ang1 < ang2) {
  66437. if (ang > ang1 && ang < ang2) {
  66438. return true;
  66439. }
  66440. }
  66441. else {
  66442. if (ang > ang2 && ang < ang1) {
  66443. return true;
  66444. }
  66445. }
  66446. return false;
  66447. };
  66448. 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()];
  66449. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  66450. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66451. return BoneLookController;
  66452. }());
  66453. BABYLON.BoneLookController = BoneLookController;
  66454. })(BABYLON || (BABYLON = {}));
  66455. //# sourceMappingURL=babylon.boneLookController.js.map
  66456. var BABYLON;
  66457. (function (BABYLON) {
  66458. var Skeleton = /** @class */ (function () {
  66459. function Skeleton(name, id, scene) {
  66460. this.name = name;
  66461. this.id = id;
  66462. this.bones = new Array();
  66463. this.needInitialSkinMatrix = false;
  66464. this._isDirty = true;
  66465. this._meshesWithPoseMatrix = new Array();
  66466. this._identity = BABYLON.Matrix.Identity();
  66467. this._ranges = {};
  66468. this._lastAbsoluteTransformsUpdateId = -1;
  66469. // Events
  66470. /**
  66471. * An event triggered before computing the skeleton's matrices
  66472. * @type {BABYLON.Observable}
  66473. */
  66474. this.onBeforeComputeObservable = new BABYLON.Observable();
  66475. this.bones = [];
  66476. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66477. scene.skeletons.push(this);
  66478. //make sure it will recalculate the matrix next time prepare is called.
  66479. this._isDirty = true;
  66480. }
  66481. // Members
  66482. Skeleton.prototype.getTransformMatrices = function (mesh) {
  66483. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  66484. return mesh._bonesTransformMatrices;
  66485. }
  66486. if (!this._transformMatrices) {
  66487. this.prepare();
  66488. }
  66489. return this._transformMatrices;
  66490. };
  66491. Skeleton.prototype.getScene = function () {
  66492. return this._scene;
  66493. };
  66494. // Methods
  66495. /**
  66496. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  66497. */
  66498. Skeleton.prototype.toString = function (fullDetails) {
  66499. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  66500. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  66501. if (fullDetails) {
  66502. ret += ", Ranges: {";
  66503. var first = true;
  66504. for (var name_1 in this._ranges) {
  66505. if (first) {
  66506. ret += ", ";
  66507. first = false;
  66508. }
  66509. ret += name_1;
  66510. }
  66511. ret += "}";
  66512. }
  66513. return ret;
  66514. };
  66515. /**
  66516. * Get bone's index searching by name
  66517. * @param {string} name is bone's name to search for
  66518. * @return {number} Indice of the bone. Returns -1 if not found
  66519. */
  66520. Skeleton.prototype.getBoneIndexByName = function (name) {
  66521. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  66522. if (this.bones[boneIndex].name === name) {
  66523. return boneIndex;
  66524. }
  66525. }
  66526. return -1;
  66527. };
  66528. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  66529. // check name not already in use
  66530. if (!this._ranges[name]) {
  66531. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  66532. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66533. if (this.bones[i].animations[0]) {
  66534. this.bones[i].animations[0].createRange(name, from, to);
  66535. }
  66536. }
  66537. }
  66538. };
  66539. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  66540. if (deleteFrames === void 0) { deleteFrames = true; }
  66541. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66542. if (this.bones[i].animations[0]) {
  66543. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  66544. }
  66545. }
  66546. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  66547. };
  66548. Skeleton.prototype.getAnimationRange = function (name) {
  66549. return this._ranges[name];
  66550. };
  66551. /**
  66552. * Returns as an Array, all AnimationRanges defined on this skeleton
  66553. */
  66554. Skeleton.prototype.getAnimationRanges = function () {
  66555. var animationRanges = [];
  66556. var name;
  66557. var i = 0;
  66558. for (name in this._ranges) {
  66559. animationRanges[i] = this._ranges[name];
  66560. i++;
  66561. }
  66562. return animationRanges;
  66563. };
  66564. /**
  66565. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  66566. */
  66567. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  66568. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66569. if (this._ranges[name] || !source.getAnimationRange(name)) {
  66570. return false;
  66571. }
  66572. var ret = true;
  66573. var frameOffset = this._getHighestAnimationFrame() + 1;
  66574. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  66575. var boneDict = {};
  66576. var sourceBones = source.bones;
  66577. var nBones;
  66578. var i;
  66579. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  66580. boneDict[sourceBones[i].name] = sourceBones[i];
  66581. }
  66582. if (this.bones.length !== sourceBones.length) {
  66583. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  66584. ret = false;
  66585. }
  66586. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  66587. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  66588. var boneName = this.bones[i].name;
  66589. var sourceBone = boneDict[boneName];
  66590. if (sourceBone) {
  66591. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  66592. }
  66593. else {
  66594. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  66595. ret = false;
  66596. }
  66597. }
  66598. // do not call createAnimationRange(), since it also is done to bones, which was already done
  66599. var range = source.getAnimationRange(name);
  66600. if (range) {
  66601. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  66602. }
  66603. return ret;
  66604. };
  66605. Skeleton.prototype.returnToRest = function () {
  66606. for (var index = 0; index < this.bones.length; index++) {
  66607. this.bones[index].returnToRest();
  66608. }
  66609. };
  66610. Skeleton.prototype._getHighestAnimationFrame = function () {
  66611. var ret = 0;
  66612. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66613. if (this.bones[i].animations[0]) {
  66614. var highest = this.bones[i].animations[0].getHighestFrame();
  66615. if (ret < highest) {
  66616. ret = highest;
  66617. }
  66618. }
  66619. }
  66620. return ret;
  66621. };
  66622. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  66623. var range = this.getAnimationRange(name);
  66624. if (!range) {
  66625. return null;
  66626. }
  66627. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  66628. };
  66629. Skeleton.prototype._markAsDirty = function () {
  66630. this._isDirty = true;
  66631. };
  66632. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  66633. this._meshesWithPoseMatrix.push(mesh);
  66634. };
  66635. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  66636. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  66637. if (index > -1) {
  66638. this._meshesWithPoseMatrix.splice(index, 1);
  66639. }
  66640. };
  66641. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  66642. this.onBeforeComputeObservable.notifyObservers(this);
  66643. for (var index = 0; index < this.bones.length; index++) {
  66644. var bone = this.bones[index];
  66645. var parentBone = bone.getParent();
  66646. if (parentBone) {
  66647. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  66648. }
  66649. else {
  66650. if (initialSkinMatrix) {
  66651. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  66652. }
  66653. else {
  66654. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  66655. }
  66656. }
  66657. if (bone._index !== -1) {
  66658. var mappedIndex = bone._index === null ? index : bone._index;
  66659. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  66660. }
  66661. }
  66662. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  66663. };
  66664. Skeleton.prototype.prepare = function () {
  66665. if (!this._isDirty) {
  66666. return;
  66667. }
  66668. if (this.needInitialSkinMatrix) {
  66669. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  66670. var mesh = this._meshesWithPoseMatrix[index];
  66671. var poseMatrix = mesh.getPoseMatrix();
  66672. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  66673. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  66674. }
  66675. if (this._synchronizedWithMesh !== mesh) {
  66676. this._synchronizedWithMesh = mesh;
  66677. // Prepare bones
  66678. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  66679. var bone = this.bones[boneIndex];
  66680. if (!bone.getParent()) {
  66681. var matrix = bone.getBaseMatrix();
  66682. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  66683. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  66684. }
  66685. }
  66686. }
  66687. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  66688. }
  66689. }
  66690. else {
  66691. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  66692. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  66693. }
  66694. this._computeTransformMatrices(this._transformMatrices, null);
  66695. }
  66696. this._isDirty = false;
  66697. this._scene._activeBones.addCount(this.bones.length, false);
  66698. };
  66699. Skeleton.prototype.getAnimatables = function () {
  66700. if (!this._animatables || this._animatables.length !== this.bones.length) {
  66701. this._animatables = [];
  66702. for (var index = 0; index < this.bones.length; index++) {
  66703. this._animatables.push(this.bones[index]);
  66704. }
  66705. }
  66706. return this._animatables;
  66707. };
  66708. Skeleton.prototype.clone = function (name, id) {
  66709. var result = new Skeleton(name, id || name, this._scene);
  66710. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  66711. for (var index = 0; index < this.bones.length; index++) {
  66712. var source = this.bones[index];
  66713. var parentBone = null;
  66714. var parent_1 = source.getParent();
  66715. if (parent_1) {
  66716. var parentIndex = this.bones.indexOf(parent_1);
  66717. parentBone = result.bones[parentIndex];
  66718. }
  66719. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  66720. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  66721. }
  66722. if (this._ranges) {
  66723. result._ranges = {};
  66724. for (var rangeName in this._ranges) {
  66725. var range = this._ranges[rangeName];
  66726. if (range) {
  66727. result._ranges[rangeName] = range.clone();
  66728. }
  66729. }
  66730. }
  66731. this._isDirty = true;
  66732. return result;
  66733. };
  66734. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  66735. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  66736. this.bones.forEach(function (bone) {
  66737. bone.animations.forEach(function (animation) {
  66738. animation.enableBlending = true;
  66739. animation.blendingSpeed = blendingSpeed;
  66740. });
  66741. });
  66742. };
  66743. Skeleton.prototype.dispose = function () {
  66744. this._meshesWithPoseMatrix = [];
  66745. // Animations
  66746. this.getScene().stopAnimation(this);
  66747. // Remove from scene
  66748. this.getScene().removeSkeleton(this);
  66749. };
  66750. Skeleton.prototype.serialize = function () {
  66751. var serializationObject = {};
  66752. serializationObject.name = this.name;
  66753. serializationObject.id = this.id;
  66754. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  66755. serializationObject.bones = [];
  66756. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  66757. for (var index = 0; index < this.bones.length; index++) {
  66758. var bone = this.bones[index];
  66759. var parent_2 = bone.getParent();
  66760. var serializedBone = {
  66761. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  66762. name: bone.name,
  66763. matrix: bone.getBaseMatrix().toArray(),
  66764. rest: bone.getRestPose().toArray()
  66765. };
  66766. serializationObject.bones.push(serializedBone);
  66767. if (bone.length) {
  66768. serializedBone.length = bone.length;
  66769. }
  66770. if (bone.animations && bone.animations.length > 0) {
  66771. serializedBone.animation = bone.animations[0].serialize();
  66772. }
  66773. serializationObject.ranges = [];
  66774. for (var name in this._ranges) {
  66775. var source = this._ranges[name];
  66776. if (!source) {
  66777. continue;
  66778. }
  66779. var range = {};
  66780. range.name = name;
  66781. range.from = source.from;
  66782. range.to = source.to;
  66783. serializationObject.ranges.push(range);
  66784. }
  66785. }
  66786. return serializationObject;
  66787. };
  66788. Skeleton.Parse = function (parsedSkeleton, scene) {
  66789. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  66790. if (parsedSkeleton.dimensionsAtRest) {
  66791. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  66792. }
  66793. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  66794. var index;
  66795. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  66796. var parsedBone = parsedSkeleton.bones[index];
  66797. var parentBone = null;
  66798. if (parsedBone.parentBoneIndex > -1) {
  66799. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  66800. }
  66801. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  66802. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  66803. if (parsedBone.length) {
  66804. bone.length = parsedBone.length;
  66805. }
  66806. if (parsedBone.animation) {
  66807. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  66808. }
  66809. }
  66810. // placed after bones, so createAnimationRange can cascade down
  66811. if (parsedSkeleton.ranges) {
  66812. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  66813. var data = parsedSkeleton.ranges[index];
  66814. skeleton.createAnimationRange(data.name, data.from, data.to);
  66815. }
  66816. }
  66817. return skeleton;
  66818. };
  66819. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  66820. if (forceUpdate === void 0) { forceUpdate = false; }
  66821. var renderId = this._scene.getRenderId();
  66822. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  66823. this.bones[0].computeAbsoluteTransforms();
  66824. this._lastAbsoluteTransformsUpdateId = renderId;
  66825. }
  66826. };
  66827. Skeleton.prototype.getPoseMatrix = function () {
  66828. var poseMatrix = null;
  66829. if (this._meshesWithPoseMatrix.length > 0) {
  66830. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  66831. }
  66832. return poseMatrix;
  66833. };
  66834. Skeleton.prototype.sortBones = function () {
  66835. var bones = new Array();
  66836. var visited = new Array(this.bones.length);
  66837. for (var index = 0; index < this.bones.length; index++) {
  66838. this._sortBones(index, bones, visited);
  66839. }
  66840. this.bones = bones;
  66841. };
  66842. Skeleton.prototype._sortBones = function (index, bones, visited) {
  66843. if (visited[index]) {
  66844. return;
  66845. }
  66846. visited[index] = true;
  66847. var bone = this.bones[index];
  66848. if (bone._index === undefined) {
  66849. bone._index = index;
  66850. }
  66851. var parentBone = bone.getParent();
  66852. if (parentBone) {
  66853. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  66854. }
  66855. bones.push(bone);
  66856. };
  66857. return Skeleton;
  66858. }());
  66859. BABYLON.Skeleton = Skeleton;
  66860. })(BABYLON || (BABYLON = {}));
  66861. //# sourceMappingURL=babylon.skeleton.js.map
  66862. var BABYLON;
  66863. (function (BABYLON) {
  66864. var SphericalPolynomial = /** @class */ (function () {
  66865. function SphericalPolynomial() {
  66866. this.x = BABYLON.Vector3.Zero();
  66867. this.y = BABYLON.Vector3.Zero();
  66868. this.z = BABYLON.Vector3.Zero();
  66869. this.xx = BABYLON.Vector3.Zero();
  66870. this.yy = BABYLON.Vector3.Zero();
  66871. this.zz = BABYLON.Vector3.Zero();
  66872. this.xy = BABYLON.Vector3.Zero();
  66873. this.yz = BABYLON.Vector3.Zero();
  66874. this.zx = BABYLON.Vector3.Zero();
  66875. }
  66876. SphericalPolynomial.prototype.addAmbient = function (color) {
  66877. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  66878. this.xx = this.xx.add(colorVector);
  66879. this.yy = this.yy.add(colorVector);
  66880. this.zz = this.zz.add(colorVector);
  66881. };
  66882. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  66883. var result = new SphericalPolynomial();
  66884. result.x = harmonics.L11.scale(1.02333);
  66885. result.y = harmonics.L1_1.scale(1.02333);
  66886. result.z = harmonics.L10.scale(1.02333);
  66887. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  66888. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  66889. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  66890. result.yz = harmonics.L2_1.scale(0.858086);
  66891. result.zx = harmonics.L21.scale(0.858086);
  66892. result.xy = harmonics.L2_2.scale(0.858086);
  66893. result.scale(1.0 / Math.PI);
  66894. return result;
  66895. };
  66896. SphericalPolynomial.prototype.scale = function (scale) {
  66897. this.x = this.x.scale(scale);
  66898. this.y = this.y.scale(scale);
  66899. this.z = this.z.scale(scale);
  66900. this.xx = this.xx.scale(scale);
  66901. this.yy = this.yy.scale(scale);
  66902. this.zz = this.zz.scale(scale);
  66903. this.yz = this.yz.scale(scale);
  66904. this.zx = this.zx.scale(scale);
  66905. this.xy = this.xy.scale(scale);
  66906. };
  66907. return SphericalPolynomial;
  66908. }());
  66909. BABYLON.SphericalPolynomial = SphericalPolynomial;
  66910. var SphericalHarmonics = /** @class */ (function () {
  66911. function SphericalHarmonics() {
  66912. this.L00 = BABYLON.Vector3.Zero();
  66913. this.L1_1 = BABYLON.Vector3.Zero();
  66914. this.L10 = BABYLON.Vector3.Zero();
  66915. this.L11 = BABYLON.Vector3.Zero();
  66916. this.L2_2 = BABYLON.Vector3.Zero();
  66917. this.L2_1 = BABYLON.Vector3.Zero();
  66918. this.L20 = BABYLON.Vector3.Zero();
  66919. this.L21 = BABYLON.Vector3.Zero();
  66920. this.L22 = BABYLON.Vector3.Zero();
  66921. }
  66922. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  66923. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  66924. var c = colorVector.scale(deltaSolidAngle);
  66925. this.L00 = this.L00.add(c.scale(0.282095));
  66926. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  66927. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  66928. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  66929. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  66930. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  66931. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  66932. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  66933. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  66934. };
  66935. SphericalHarmonics.prototype.scale = function (scale) {
  66936. this.L00 = this.L00.scale(scale);
  66937. this.L1_1 = this.L1_1.scale(scale);
  66938. this.L10 = this.L10.scale(scale);
  66939. this.L11 = this.L11.scale(scale);
  66940. this.L2_2 = this.L2_2.scale(scale);
  66941. this.L2_1 = this.L2_1.scale(scale);
  66942. this.L20 = this.L20.scale(scale);
  66943. this.L21 = this.L21.scale(scale);
  66944. this.L22 = this.L22.scale(scale);
  66945. };
  66946. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  66947. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  66948. //
  66949. // E_lm = A_l * L_lm
  66950. //
  66951. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  66952. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  66953. // the scaling factors are given in equation 9.
  66954. // Constant (Band 0)
  66955. this.L00 = this.L00.scale(3.141593);
  66956. // Linear (Band 1)
  66957. this.L1_1 = this.L1_1.scale(2.094395);
  66958. this.L10 = this.L10.scale(2.094395);
  66959. this.L11 = this.L11.scale(2.094395);
  66960. // Quadratic (Band 2)
  66961. this.L2_2 = this.L2_2.scale(0.785398);
  66962. this.L2_1 = this.L2_1.scale(0.785398);
  66963. this.L20 = this.L20.scale(0.785398);
  66964. this.L21 = this.L21.scale(0.785398);
  66965. this.L22 = this.L22.scale(0.785398);
  66966. };
  66967. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  66968. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  66969. // L = (1/pi) * E * rho
  66970. //
  66971. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  66972. this.scale(1.0 / Math.PI);
  66973. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  66974. // (The pixel shader must apply albedo after texture fetches, etc).
  66975. };
  66976. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  66977. var result = new SphericalHarmonics();
  66978. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  66979. result.L1_1 = polynomial.y.scale(0.977204);
  66980. result.L10 = polynomial.z.scale(0.977204);
  66981. result.L11 = polynomial.x.scale(0.977204);
  66982. result.L2_2 = polynomial.xy.scale(1.16538);
  66983. result.L2_1 = polynomial.yz.scale(1.16538);
  66984. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  66985. result.L21 = polynomial.zx.scale(1.16538);
  66986. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  66987. result.scale(Math.PI);
  66988. return result;
  66989. };
  66990. return SphericalHarmonics;
  66991. }());
  66992. BABYLON.SphericalHarmonics = SphericalHarmonics;
  66993. })(BABYLON || (BABYLON = {}));
  66994. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  66995. var BABYLON;
  66996. (function (BABYLON) {
  66997. var FileFaceOrientation = /** @class */ (function () {
  66998. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  66999. this.name = name;
  67000. this.worldAxisForNormal = worldAxisForNormal;
  67001. this.worldAxisForFileX = worldAxisForFileX;
  67002. this.worldAxisForFileY = worldAxisForFileY;
  67003. }
  67004. return FileFaceOrientation;
  67005. }());
  67006. ;
  67007. /**
  67008. * Helper class dealing with the extraction of spherical polynomial dataArray
  67009. * from a cube map.
  67010. */
  67011. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  67012. function CubeMapToSphericalPolynomialTools() {
  67013. }
  67014. /**
  67015. * Converts a texture to the according Spherical Polynomial data.
  67016. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67017. *
  67018. * @param texture The texture to extract the information from.
  67019. * @return The Spherical Polynomial data.
  67020. */
  67021. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  67022. if (!texture.isCube) {
  67023. // Only supports cube Textures currently.
  67024. return null;
  67025. }
  67026. var size = texture.getSize().width;
  67027. var right = texture.readPixels(0);
  67028. var left = texture.readPixels(1);
  67029. var up;
  67030. var down;
  67031. if (texture.isRenderTarget) {
  67032. up = texture.readPixels(3);
  67033. down = texture.readPixels(2);
  67034. }
  67035. else {
  67036. up = texture.readPixels(2);
  67037. down = texture.readPixels(3);
  67038. }
  67039. var front = texture.readPixels(4);
  67040. var back = texture.readPixels(5);
  67041. var gammaSpace = texture.gammaSpace;
  67042. // Always read as RGBA.
  67043. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  67044. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67045. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67046. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67047. }
  67048. var cubeInfo = {
  67049. size: size,
  67050. right: right,
  67051. left: left,
  67052. up: up,
  67053. down: down,
  67054. front: front,
  67055. back: back,
  67056. format: format,
  67057. type: type,
  67058. gammaSpace: gammaSpace,
  67059. };
  67060. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  67061. };
  67062. /**
  67063. * Converts a cubemap to the according Spherical Polynomial data.
  67064. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67065. *
  67066. * @param cubeInfo The Cube map to extract the information from.
  67067. * @return The Spherical Polynomial data.
  67068. */
  67069. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  67070. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  67071. var totalSolidAngle = 0.0;
  67072. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  67073. var du = 2.0 / cubeInfo.size;
  67074. var dv = du;
  67075. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  67076. var minUV = du * 0.5 - 1.0;
  67077. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67078. var fileFace = this.FileFaces[faceIndex];
  67079. var dataArray = cubeInfo[fileFace.name];
  67080. var v = minUV;
  67081. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  67082. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  67083. // Because SP is still linear, so summation is fine in that basis.
  67084. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  67085. for (var y = 0; y < cubeInfo.size; y++) {
  67086. var u = minUV;
  67087. for (var x = 0; x < cubeInfo.size; x++) {
  67088. // World direction (not normalised)
  67089. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  67090. worldDirection.normalize();
  67091. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  67092. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  67093. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  67094. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  67095. // Handle Integer types.
  67096. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67097. r /= 255;
  67098. g /= 255;
  67099. b /= 255;
  67100. }
  67101. // Handle Gamma space textures.
  67102. if (cubeInfo.gammaSpace) {
  67103. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  67104. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  67105. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  67106. }
  67107. var color = new BABYLON.Color3(r, g, b);
  67108. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  67109. totalSolidAngle += deltaSolidAngle;
  67110. u += du;
  67111. }
  67112. v += dv;
  67113. }
  67114. }
  67115. // Solid angle for entire sphere is 4*pi
  67116. var sphereSolidAngle = 4.0 * Math.PI;
  67117. // Adjust the solid angle to allow for how many faces we processed.
  67118. var facesProcessed = 6.0;
  67119. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  67120. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  67121. // This is needed because the numerical integration over the cube uses a
  67122. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  67123. // and also to compensate for accumulative error due to float precision in the summation.
  67124. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  67125. sphericalHarmonics.scale(correctionFactor);
  67126. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  67127. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  67128. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  67129. };
  67130. CubeMapToSphericalPolynomialTools.FileFaces = [
  67131. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  67132. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  67133. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  67134. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  67135. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  67136. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  67137. ];
  67138. return CubeMapToSphericalPolynomialTools;
  67139. }());
  67140. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  67141. })(BABYLON || (BABYLON = {}));
  67142. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  67143. var BABYLON;
  67144. (function (BABYLON) {
  67145. /**
  67146. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  67147. */
  67148. var PanoramaToCubeMapTools = /** @class */ (function () {
  67149. function PanoramaToCubeMapTools() {
  67150. }
  67151. /**
  67152. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  67153. *
  67154. * @param float32Array The source data.
  67155. * @param inputWidth The width of the input panorama.
  67156. * @param inputhHeight The height of the input panorama.
  67157. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  67158. * @return The cubemap data
  67159. */
  67160. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  67161. if (!float32Array) {
  67162. throw "ConvertPanoramaToCubemap: input cannot be null";
  67163. }
  67164. if (float32Array.length != inputWidth * inputHeight * 3) {
  67165. throw "ConvertPanoramaToCubemap: input size is wrong";
  67166. }
  67167. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  67168. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  67169. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  67170. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  67171. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  67172. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  67173. return {
  67174. front: textureFront,
  67175. back: textureBack,
  67176. left: textureLeft,
  67177. right: textureRight,
  67178. up: textureUp,
  67179. down: textureDown,
  67180. size: size,
  67181. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  67182. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  67183. gammaSpace: false,
  67184. };
  67185. };
  67186. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  67187. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  67188. var textureArray = new Float32Array(buffer);
  67189. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  67190. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  67191. var dy = 1 / texSize;
  67192. var fy = 0;
  67193. for (var y = 0; y < texSize; y++) {
  67194. var xv1 = faceData[0];
  67195. var xv2 = faceData[2];
  67196. for (var x = 0; x < texSize; x++) {
  67197. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  67198. v.normalize();
  67199. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  67200. // 3 channels per pixels
  67201. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  67202. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  67203. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  67204. xv1 = xv1.add(rotDX1);
  67205. xv2 = xv2.add(rotDX2);
  67206. }
  67207. fy += dy;
  67208. }
  67209. return textureArray;
  67210. };
  67211. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  67212. var theta = Math.atan2(vDir.z, vDir.x);
  67213. var phi = Math.acos(vDir.y);
  67214. while (theta < -Math.PI)
  67215. theta += 2 * Math.PI;
  67216. while (theta > Math.PI)
  67217. theta -= 2 * Math.PI;
  67218. var dx = theta / Math.PI;
  67219. var dy = phi / Math.PI;
  67220. // recenter.
  67221. dx = dx * 0.5 + 0.5;
  67222. var px = Math.round(dx * inputWidth);
  67223. if (px < 0)
  67224. px = 0;
  67225. else if (px >= inputWidth)
  67226. px = inputWidth - 1;
  67227. var py = Math.round(dy * inputHeight);
  67228. if (py < 0)
  67229. py = 0;
  67230. else if (py >= inputHeight)
  67231. py = inputHeight - 1;
  67232. var inputY = (inputHeight - py - 1);
  67233. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  67234. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  67235. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  67236. return {
  67237. r: r,
  67238. g: g,
  67239. b: b
  67240. };
  67241. };
  67242. PanoramaToCubeMapTools.FACE_FRONT = [
  67243. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67244. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67245. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67246. new BABYLON.Vector3(1.0, 1.0, -1.0)
  67247. ];
  67248. PanoramaToCubeMapTools.FACE_BACK = [
  67249. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67250. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67251. new BABYLON.Vector3(1.0, 1.0, 1.0),
  67252. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  67253. ];
  67254. PanoramaToCubeMapTools.FACE_RIGHT = [
  67255. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67256. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67257. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67258. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67259. ];
  67260. PanoramaToCubeMapTools.FACE_LEFT = [
  67261. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67262. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67263. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67264. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  67265. ];
  67266. PanoramaToCubeMapTools.FACE_DOWN = [
  67267. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67268. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67269. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67270. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67271. ];
  67272. PanoramaToCubeMapTools.FACE_UP = [
  67273. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67274. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67275. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67276. new BABYLON.Vector3(1.0, -1.0, -1.0)
  67277. ];
  67278. return PanoramaToCubeMapTools;
  67279. }());
  67280. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  67281. })(BABYLON || (BABYLON = {}));
  67282. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  67283. var BABYLON;
  67284. (function (BABYLON) {
  67285. ;
  67286. /**
  67287. * This groups tools to convert HDR texture to native colors array.
  67288. */
  67289. var HDRTools = /** @class */ (function () {
  67290. function HDRTools() {
  67291. }
  67292. HDRTools.Ldexp = function (mantissa, exponent) {
  67293. if (exponent > 1023) {
  67294. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  67295. }
  67296. if (exponent < -1074) {
  67297. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  67298. }
  67299. return mantissa * Math.pow(2, exponent);
  67300. };
  67301. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  67302. if (exponent > 0) {
  67303. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  67304. float32array[index + 0] = red * exponent;
  67305. float32array[index + 1] = green * exponent;
  67306. float32array[index + 2] = blue * exponent;
  67307. }
  67308. else {
  67309. float32array[index + 0] = 0;
  67310. float32array[index + 1] = 0;
  67311. float32array[index + 2] = 0;
  67312. }
  67313. };
  67314. HDRTools.readStringLine = function (uint8array, startIndex) {
  67315. var line = "";
  67316. var character = "";
  67317. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  67318. character = String.fromCharCode(uint8array[i]);
  67319. if (character == "\n") {
  67320. break;
  67321. }
  67322. line += character;
  67323. }
  67324. return line;
  67325. };
  67326. /**
  67327. * Reads header information from an RGBE texture stored in a native array.
  67328. * More information on this format are available here:
  67329. * https://en.wikipedia.org/wiki/RGBE_image_format
  67330. *
  67331. * @param uint8array The binary file stored in native array.
  67332. * @return The header information.
  67333. */
  67334. HDRTools.RGBE_ReadHeader = function (uint8array) {
  67335. var height = 0;
  67336. var width = 0;
  67337. var line = this.readStringLine(uint8array, 0);
  67338. if (line[0] != '#' || line[1] != '?') {
  67339. throw "Bad HDR Format.";
  67340. }
  67341. var endOfHeader = false;
  67342. var findFormat = false;
  67343. var lineIndex = 0;
  67344. do {
  67345. lineIndex += (line.length + 1);
  67346. line = this.readStringLine(uint8array, lineIndex);
  67347. if (line == "FORMAT=32-bit_rle_rgbe") {
  67348. findFormat = true;
  67349. }
  67350. else if (line.length == 0) {
  67351. endOfHeader = true;
  67352. }
  67353. } while (!endOfHeader);
  67354. if (!findFormat) {
  67355. throw "HDR Bad header format, unsupported FORMAT";
  67356. }
  67357. lineIndex += (line.length + 1);
  67358. line = this.readStringLine(uint8array, lineIndex);
  67359. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  67360. var match = sizeRegexp.exec(line);
  67361. // TODO. Support +Y and -X if needed.
  67362. if (!match || match.length < 3) {
  67363. throw "HDR Bad header format, no size";
  67364. }
  67365. width = parseInt(match[2]);
  67366. height = parseInt(match[1]);
  67367. if (width < 8 || width > 0x7fff) {
  67368. throw "HDR Bad header format, unsupported size";
  67369. }
  67370. lineIndex += (line.length + 1);
  67371. return {
  67372. height: height,
  67373. width: width,
  67374. dataPosition: lineIndex
  67375. };
  67376. };
  67377. /**
  67378. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  67379. * This RGBE texture needs to store the information as a panorama.
  67380. *
  67381. * More information on this format are available here:
  67382. * https://en.wikipedia.org/wiki/RGBE_image_format
  67383. *
  67384. * @param buffer The binary file stored in an array buffer.
  67385. * @param size The expected size of the extracted cubemap.
  67386. * @return The Cube Map information.
  67387. */
  67388. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  67389. var uint8array = new Uint8Array(buffer);
  67390. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  67391. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67392. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  67393. return cubeMapData;
  67394. };
  67395. /**
  67396. * Returns the pixels data extracted from an RGBE texture.
  67397. * This pixels will be stored left to right up to down in the R G B order in one array.
  67398. *
  67399. * More information on this format are available here:
  67400. * https://en.wikipedia.org/wiki/RGBE_image_format
  67401. *
  67402. * @param uint8array The binary file stored in an array buffer.
  67403. * @param hdrInfo The header information of the file.
  67404. * @return The pixels data in RGB right to left up to down order.
  67405. */
  67406. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  67407. // Keep for multi format supports.
  67408. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67409. };
  67410. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  67411. var num_scanlines = hdrInfo.height;
  67412. var scanline_width = hdrInfo.width;
  67413. var a, b, c, d, count;
  67414. var dataIndex = hdrInfo.dataPosition;
  67415. var index = 0, endIndex = 0, i = 0;
  67416. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  67417. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  67418. // 3 channels of 4 bytes per pixel in float.
  67419. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  67420. var resultArray = new Float32Array(resultBuffer);
  67421. // read in each successive scanline
  67422. while (num_scanlines > 0) {
  67423. a = uint8array[dataIndex++];
  67424. b = uint8array[dataIndex++];
  67425. c = uint8array[dataIndex++];
  67426. d = uint8array[dataIndex++];
  67427. if (a != 2 || b != 2 || (c & 0x80)) {
  67428. // this file is not run length encoded
  67429. throw "HDR Bad header format, not RLE";
  67430. }
  67431. if (((c << 8) | d) != scanline_width) {
  67432. throw "HDR Bad header format, wrong scan line width";
  67433. }
  67434. index = 0;
  67435. // read each of the four channels for the scanline into the buffer
  67436. for (i = 0; i < 4; i++) {
  67437. endIndex = (i + 1) * scanline_width;
  67438. while (index < endIndex) {
  67439. a = uint8array[dataIndex++];
  67440. b = uint8array[dataIndex++];
  67441. if (a > 128) {
  67442. // a run of the same value
  67443. count = a - 128;
  67444. if ((count == 0) || (count > endIndex - index)) {
  67445. throw "HDR Bad Format, bad scanline data (run)";
  67446. }
  67447. while (count-- > 0) {
  67448. scanLineArray[index++] = b;
  67449. }
  67450. }
  67451. else {
  67452. // a non-run
  67453. count = a;
  67454. if ((count == 0) || (count > endIndex - index)) {
  67455. throw "HDR Bad Format, bad scanline data (non-run)";
  67456. }
  67457. scanLineArray[index++] = b;
  67458. if (--count > 0) {
  67459. for (var j = 0; j < count; j++) {
  67460. scanLineArray[index++] = uint8array[dataIndex++];
  67461. }
  67462. }
  67463. }
  67464. }
  67465. }
  67466. // now convert data from buffer into floats
  67467. for (i = 0; i < scanline_width; i++) {
  67468. a = scanLineArray[i];
  67469. b = scanLineArray[i + scanline_width];
  67470. c = scanLineArray[i + 2 * scanline_width];
  67471. d = scanLineArray[i + 3 * scanline_width];
  67472. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  67473. }
  67474. num_scanlines--;
  67475. }
  67476. return resultArray;
  67477. };
  67478. return HDRTools;
  67479. }());
  67480. BABYLON.HDRTools = HDRTools;
  67481. })(BABYLON || (BABYLON = {}));
  67482. //# sourceMappingURL=babylon.hdr.js.map
  67483. var BABYLON;
  67484. (function (BABYLON) {
  67485. /**
  67486. * This represents a texture coming from an HDR input.
  67487. *
  67488. * The only supported format is currently panorama picture stored in RGBE format.
  67489. * Example of such files can be found on HDRLib: http://hdrlib.com/
  67490. */
  67491. var HDRCubeTexture = /** @class */ (function (_super) {
  67492. __extends(HDRCubeTexture, _super);
  67493. /**
  67494. * Instantiates an HDRTexture from the following parameters.
  67495. *
  67496. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  67497. * @param scene The scene the texture will be used in
  67498. * @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.
  67499. * @param noMipmap Forces to not generate the mipmap if true
  67500. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  67501. * @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)
  67502. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  67503. */
  67504. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  67505. if (noMipmap === void 0) { noMipmap = false; }
  67506. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67507. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67508. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67509. if (onLoad === void 0) { onLoad = null; }
  67510. if (onError === void 0) { onError = null; }
  67511. var _this = _super.call(this, scene) || this;
  67512. _this._useInGammaSpace = false;
  67513. _this._generateHarmonics = true;
  67514. _this._isBABYLONPreprocessed = false;
  67515. _this._onLoad = null;
  67516. _this._onError = null;
  67517. /**
  67518. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  67519. */
  67520. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67521. /**
  67522. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  67523. * This is usefull at run time to apply the good shader.
  67524. */
  67525. _this.isPMREM = false;
  67526. _this._isBlocking = true;
  67527. if (!url) {
  67528. return _this;
  67529. }
  67530. _this.name = url;
  67531. _this.url = url;
  67532. _this.hasAlpha = false;
  67533. _this.isCube = true;
  67534. _this._textureMatrix = BABYLON.Matrix.Identity();
  67535. _this._onLoad = onLoad;
  67536. _this._onError = onError;
  67537. _this.gammaSpace = false;
  67538. var caps = scene.getEngine().getCaps();
  67539. if (size) {
  67540. _this._isBABYLONPreprocessed = false;
  67541. _this._noMipmap = noMipmap;
  67542. _this._size = size;
  67543. _this._useInGammaSpace = useInGammaSpace;
  67544. _this._usePMREMGenerator = usePMREMGenerator &&
  67545. caps.textureLOD &&
  67546. caps.textureFloat &&
  67547. !_this._useInGammaSpace;
  67548. }
  67549. else {
  67550. _this._isBABYLONPreprocessed = true;
  67551. _this._noMipmap = false;
  67552. _this._useInGammaSpace = false;
  67553. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  67554. !_this._useInGammaSpace;
  67555. }
  67556. _this.isPMREM = _this._usePMREMGenerator;
  67557. _this._texture = _this._getFromCache(url, _this._noMipmap);
  67558. if (!_this._texture) {
  67559. if (!scene.useDelayedTextureLoading) {
  67560. _this.loadTexture();
  67561. }
  67562. else {
  67563. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67564. }
  67565. }
  67566. return _this;
  67567. }
  67568. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  67569. /**
  67570. * Gets wether or not the texture is blocking during loading.
  67571. */
  67572. get: function () {
  67573. return this._isBlocking;
  67574. },
  67575. /**
  67576. * Sets wether or not the texture is blocking during loading.
  67577. */
  67578. set: function (value) {
  67579. this._isBlocking = value;
  67580. },
  67581. enumerable: true,
  67582. configurable: true
  67583. });
  67584. /**
  67585. * Occurs when the file is a preprocessed .babylon.hdr file.
  67586. */
  67587. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  67588. var _this = this;
  67589. var mipLevels = 0;
  67590. var floatArrayView = null;
  67591. var scene = this.getScene();
  67592. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  67593. var mips = new Array();
  67594. if (!floatArrayView) {
  67595. return mips;
  67596. }
  67597. var startIndex = 30;
  67598. for (var level = 0; level < mipLevels; level++) {
  67599. mips.push([]);
  67600. // Fill each pixel of the mip level.
  67601. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  67602. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67603. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  67604. mips[level].push(faceData);
  67605. startIndex += faceSize;
  67606. }
  67607. }
  67608. return mips;
  67609. } : null;
  67610. var callback = function (buffer) {
  67611. var scene = _this.getScene();
  67612. if (!scene) {
  67613. return null;
  67614. }
  67615. // Create Native Array Views
  67616. var intArrayView = new Int32Array(buffer);
  67617. floatArrayView = new Float32Array(buffer);
  67618. // Fill header.
  67619. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  67620. _this._size = intArrayView[1]; // CubeMap max mip face size.
  67621. // Update Texture Information.
  67622. if (!_this._texture) {
  67623. return null;
  67624. }
  67625. _this._texture.updateSize(_this._size, _this._size);
  67626. // Fill polynomial information.
  67627. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  67628. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  67629. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  67630. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  67631. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  67632. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  67633. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  67634. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  67635. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  67636. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  67637. _this.sphericalPolynomial = sphericalPolynomial;
  67638. // Fill pixel data.
  67639. mipLevels = intArrayView[29]; // Number of mip levels.
  67640. var startIndex = 30;
  67641. var data = [];
  67642. var faceSize = Math.pow(_this._size, 2) * 3;
  67643. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67644. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  67645. startIndex += faceSize;
  67646. }
  67647. var results = [];
  67648. var byteArray = null;
  67649. // Push each faces.
  67650. for (var k = 0; k < 6; k++) {
  67651. var dataFace = null;
  67652. // To be deprecated.
  67653. if (version === 1) {
  67654. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  67655. dataFace = data[j];
  67656. }
  67657. // If special cases.
  67658. if (!mipmapGenerator && dataFace) {
  67659. if (!scene.getEngine().getCaps().textureFloat) {
  67660. // 3 channels of 1 bytes per pixel in bytes.
  67661. var byteBuffer = new ArrayBuffer(faceSize);
  67662. byteArray = new Uint8Array(byteBuffer);
  67663. }
  67664. for (var i = 0; i < _this._size * _this._size; i++) {
  67665. // Put in gamma space if requested.
  67666. if (_this._useInGammaSpace) {
  67667. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  67668. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  67669. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  67670. }
  67671. // Convert to int texture for fallback.
  67672. if (byteArray) {
  67673. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  67674. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  67675. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  67676. // May use luminance instead if the result is not accurate.
  67677. var max = Math.max(Math.max(r, g), b);
  67678. if (max > 255) {
  67679. var scale = 255 / max;
  67680. r *= scale;
  67681. g *= scale;
  67682. b *= scale;
  67683. }
  67684. byteArray[(i * 3) + 0] = r;
  67685. byteArray[(i * 3) + 1] = g;
  67686. byteArray[(i * 3) + 2] = b;
  67687. }
  67688. }
  67689. }
  67690. // Fill the array accordingly.
  67691. if (byteArray) {
  67692. results.push(byteArray);
  67693. }
  67694. else {
  67695. results.push(dataFace);
  67696. }
  67697. }
  67698. return results;
  67699. };
  67700. if (scene) {
  67701. 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);
  67702. }
  67703. };
  67704. /**
  67705. * Occurs when the file is raw .hdr file.
  67706. */
  67707. HDRCubeTexture.prototype.loadHDRTexture = function () {
  67708. var _this = this;
  67709. var callback = function (buffer) {
  67710. var scene = _this.getScene();
  67711. if (!scene) {
  67712. return null;
  67713. }
  67714. // Extract the raw linear data.
  67715. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  67716. // Generate harmonics if needed.
  67717. if (_this._generateHarmonics) {
  67718. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  67719. _this.sphericalPolynomial = sphericalPolynomial;
  67720. }
  67721. var results = [];
  67722. var byteArray = null;
  67723. // Push each faces.
  67724. for (var j = 0; j < 6; j++) {
  67725. // Create uintarray fallback.
  67726. if (!scene.getEngine().getCaps().textureFloat) {
  67727. // 3 channels of 1 bytes per pixel in bytes.
  67728. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  67729. byteArray = new Uint8Array(byteBuffer);
  67730. }
  67731. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  67732. // If special cases.
  67733. if (_this._useInGammaSpace || byteArray) {
  67734. for (var i = 0; i < _this._size * _this._size; i++) {
  67735. // Put in gamma space if requested.
  67736. if (_this._useInGammaSpace) {
  67737. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  67738. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  67739. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  67740. }
  67741. // Convert to int texture for fallback.
  67742. if (byteArray) {
  67743. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  67744. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  67745. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  67746. // May use luminance instead if the result is not accurate.
  67747. var max = Math.max(Math.max(r, g), b);
  67748. if (max > 255) {
  67749. var scale = 255 / max;
  67750. r *= scale;
  67751. g *= scale;
  67752. b *= scale;
  67753. }
  67754. byteArray[(i * 3) + 0] = r;
  67755. byteArray[(i * 3) + 1] = g;
  67756. byteArray[(i * 3) + 2] = b;
  67757. }
  67758. }
  67759. }
  67760. if (byteArray) {
  67761. results.push(byteArray);
  67762. }
  67763. else {
  67764. results.push(dataFace);
  67765. }
  67766. }
  67767. return results;
  67768. };
  67769. var mipmapGenerator = null;
  67770. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  67771. // if (!this._noMipmap &&
  67772. // this._usePMREMGenerator) {
  67773. // mipmapGenerator = (data: ArrayBufferView[]) => {
  67774. // // Custom setup of the generator matching with the PBR shader values.
  67775. // var generator = new BABYLON.PMREMGenerator(data,
  67776. // this._size,
  67777. // this._size,
  67778. // 0,
  67779. // 3,
  67780. // this.getScene().getEngine().getCaps().textureFloat,
  67781. // 2048,
  67782. // 0.25,
  67783. // false,
  67784. // true);
  67785. // return generator.filterCubeMap();
  67786. // };
  67787. // }
  67788. var scene = this.getScene();
  67789. if (scene) {
  67790. 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);
  67791. }
  67792. };
  67793. /**
  67794. * Starts the loading process of the texture.
  67795. */
  67796. HDRCubeTexture.prototype.loadTexture = function () {
  67797. if (this._isBABYLONPreprocessed) {
  67798. this.loadBabylonTexture();
  67799. }
  67800. else {
  67801. this.loadHDRTexture();
  67802. }
  67803. };
  67804. HDRCubeTexture.prototype.clone = function () {
  67805. var scene = this.getScene();
  67806. if (!scene) {
  67807. return this;
  67808. }
  67809. var size = (this._isBABYLONPreprocessed ? null : this._size);
  67810. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  67811. // Base texture
  67812. newTexture.level = this.level;
  67813. newTexture.wrapU = this.wrapU;
  67814. newTexture.wrapV = this.wrapV;
  67815. newTexture.coordinatesIndex = this.coordinatesIndex;
  67816. newTexture.coordinatesMode = this.coordinatesMode;
  67817. return newTexture;
  67818. };
  67819. // Methods
  67820. HDRCubeTexture.prototype.delayLoad = function () {
  67821. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67822. return;
  67823. }
  67824. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67825. this._texture = this._getFromCache(this.url, this._noMipmap);
  67826. if (!this._texture) {
  67827. this.loadTexture();
  67828. }
  67829. };
  67830. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  67831. return this._textureMatrix;
  67832. };
  67833. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67834. this._textureMatrix = value;
  67835. };
  67836. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67837. var texture = null;
  67838. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  67839. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  67840. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  67841. texture.name = parsedTexture.name;
  67842. texture.hasAlpha = parsedTexture.hasAlpha;
  67843. texture.level = parsedTexture.level;
  67844. texture.coordinatesMode = parsedTexture.coordinatesMode;
  67845. texture.isBlocking = parsedTexture.isBlocking;
  67846. }
  67847. return texture;
  67848. };
  67849. HDRCubeTexture.prototype.serialize = function () {
  67850. if (!this.name) {
  67851. return null;
  67852. }
  67853. var serializationObject = {};
  67854. serializationObject.name = this.name;
  67855. serializationObject.hasAlpha = this.hasAlpha;
  67856. serializationObject.isCube = true;
  67857. serializationObject.level = this.level;
  67858. serializationObject.size = this._size;
  67859. serializationObject.coordinatesMode = this.coordinatesMode;
  67860. serializationObject.useInGammaSpace = this._useInGammaSpace;
  67861. serializationObject.generateHarmonics = this._generateHarmonics;
  67862. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  67863. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  67864. serializationObject.customType = "BABYLON.HDRCubeTexture";
  67865. serializationObject.noMipmap = this._noMipmap;
  67866. serializationObject.isBlocking = this._isBlocking;
  67867. return serializationObject;
  67868. };
  67869. /**
  67870. * Saves as a file the data contained in the texture in a binary format.
  67871. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  67872. * as the spherical used in the lighting.
  67873. * @param url The HDR file url.
  67874. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  67875. * @param onError Method called if any error happens during download.
  67876. * @return The packed binary data.
  67877. */
  67878. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  67879. if (onError === void 0) { onError = null; }
  67880. var callback = function (buffer) {
  67881. var data = new Blob([buffer], { type: 'application/octet-stream' });
  67882. // Returns a URL you can use as a href.
  67883. var objUrl = window.URL.createObjectURL(data);
  67884. // Simulates a link to it and click to dowload.
  67885. var a = document.createElement("a");
  67886. document.body.appendChild(a);
  67887. a.style.display = "none";
  67888. a.href = objUrl;
  67889. a.download = "envmap.babylon.hdr";
  67890. a.click();
  67891. };
  67892. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  67893. };
  67894. /**
  67895. * Serializes the data contained in the texture in a binary format.
  67896. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  67897. * as the spherical used in the lighting.
  67898. * @param url The HDR file url.
  67899. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  67900. * @param onError Method called if any error happens during download.
  67901. * @return The packed binary data.
  67902. */
  67903. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  67904. if (onError === void 0) { onError = null; }
  67905. // Needs the url tho create the texture.
  67906. if (!url) {
  67907. return;
  67908. }
  67909. // Check Power of two size.
  67910. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  67911. return;
  67912. }
  67913. // Coming Back in 3.x.
  67914. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  67915. };
  67916. HDRCubeTexture._facesMapping = [
  67917. "right",
  67918. "left",
  67919. "up",
  67920. "down",
  67921. "front",
  67922. "back"
  67923. ];
  67924. return HDRCubeTexture;
  67925. }(BABYLON.BaseTexture));
  67926. BABYLON.HDRCubeTexture = HDRCubeTexture;
  67927. })(BABYLON || (BABYLON = {}));
  67928. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  67929. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  67930. // Huge respect for a such great lib.
  67931. // Earcut license:
  67932. // Copyright (c) 2016, Mapbox
  67933. //
  67934. // Permission to use, copy, modify, and/or distribute this software for any purpose
  67935. // with or without fee is hereby granted, provided that the above copyright notice
  67936. // and this permission notice appear in all copies.
  67937. //
  67938. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  67939. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  67940. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  67941. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  67942. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  67943. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  67944. // THIS SOFTWARE.
  67945. var Earcut;
  67946. (function (Earcut) {
  67947. /**
  67948. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  67949. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  67950. * @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).
  67951. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  67952. */
  67953. function earcut(data, holeIndices, dim) {
  67954. dim = dim || 2;
  67955. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  67956. if (!outerNode)
  67957. return triangles;
  67958. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  67959. if (hasHoles)
  67960. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  67961. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  67962. if (data.length > 80 * dim) {
  67963. minX = maxX = data[0];
  67964. minY = maxY = data[1];
  67965. for (var i = dim; i < outerLen; i += dim) {
  67966. x = data[i];
  67967. y = data[i + 1];
  67968. if (x < minX)
  67969. minX = x;
  67970. if (y < minY)
  67971. minY = y;
  67972. if (x > maxX)
  67973. maxX = x;
  67974. if (y > maxY)
  67975. maxY = y;
  67976. }
  67977. // minX, minY and size are later used to transform coords into integers for z-order calculation
  67978. size = Math.max(maxX - minX, maxY - minY);
  67979. }
  67980. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  67981. return triangles;
  67982. }
  67983. Earcut.earcut = earcut;
  67984. var Node = /** @class */ (function () {
  67985. function Node(i, x, y) {
  67986. this.i = i;
  67987. this.x = x;
  67988. this.y = y;
  67989. this.prev = null;
  67990. this.next = null;
  67991. this.z = null;
  67992. this.prevZ = null;
  67993. this.nextZ = null;
  67994. this.steiner = false;
  67995. }
  67996. return Node;
  67997. }());
  67998. // create a circular doubly linked list from polygon points in the specified winding order
  67999. function linkedList(data, start, end, dim, clockwise) {
  68000. var i, last = null;
  68001. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  68002. for (i = start; i < end; i += dim)
  68003. last = insertNode(i, data[i], data[i + 1], last);
  68004. }
  68005. else {
  68006. for (i = end - dim; i >= start; i -= dim)
  68007. last = insertNode(i, data[i], data[i + 1], last);
  68008. }
  68009. if (last && equals(last, last.next)) {
  68010. removeNode(last);
  68011. last = last.next;
  68012. }
  68013. return last;
  68014. }
  68015. // eliminate colinear or duplicate points
  68016. function filterPoints(start, end) {
  68017. if (!start)
  68018. return start;
  68019. if (!end)
  68020. end = start;
  68021. var p = start, again;
  68022. do {
  68023. again = false;
  68024. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  68025. removeNode(p);
  68026. p = end = p.prev;
  68027. if (p === p.next)
  68028. return undefined;
  68029. again = true;
  68030. }
  68031. else {
  68032. p = p.next;
  68033. }
  68034. } while (again || p !== end);
  68035. return end;
  68036. }
  68037. // main ear slicing loop which triangulates a polygon (given as a linked list)
  68038. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  68039. if (!ear)
  68040. return;
  68041. // interlink polygon nodes in z-order
  68042. if (!pass && size)
  68043. indexCurve(ear, minX, minY, size);
  68044. var stop = ear, prev, next;
  68045. // iterate through ears, slicing them one by one
  68046. while (ear.prev !== ear.next) {
  68047. prev = ear.prev;
  68048. next = ear.next;
  68049. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  68050. // cut off the triangle
  68051. triangles.push(prev.i / dim);
  68052. triangles.push(ear.i / dim);
  68053. triangles.push(next.i / dim);
  68054. removeNode(ear);
  68055. // skipping the next vertice leads to less sliver triangles
  68056. ear = next.next;
  68057. stop = next.next;
  68058. continue;
  68059. }
  68060. ear = next;
  68061. // if we looped through the whole remaining polygon and can't find any more ears
  68062. if (ear === stop) {
  68063. // try filtering points and slicing again
  68064. if (!pass) {
  68065. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  68066. // if this didn't work, try curing all small self-intersections locally
  68067. }
  68068. else if (pass === 1) {
  68069. ear = cureLocalIntersections(ear, triangles, dim);
  68070. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  68071. // as a last resort, try splitting the remaining polygon into two
  68072. }
  68073. else if (pass === 2) {
  68074. splitEarcut(ear, triangles, dim, minX, minY, size);
  68075. }
  68076. break;
  68077. }
  68078. }
  68079. }
  68080. // check whether a polygon node forms a valid ear with adjacent nodes
  68081. function isEar(ear) {
  68082. var a = ear.prev, b = ear, c = ear.next;
  68083. if (area(a, b, c) >= 0)
  68084. return false; // reflex, can't be an ear
  68085. // now make sure we don't have other points inside the potential ear
  68086. var p = ear.next.next;
  68087. while (p !== ear.prev) {
  68088. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68089. area(p.prev, p, p.next) >= 0)
  68090. return false;
  68091. p = p.next;
  68092. }
  68093. return true;
  68094. }
  68095. function isEarHashed(ear, minX, minY, size) {
  68096. var a = ear.prev, b = ear, c = ear.next;
  68097. if (area(a, b, c) >= 0)
  68098. return false; // reflex, can't be an ear
  68099. // triangle bbox; min & max are calculated like this for speed
  68100. 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);
  68101. // z-order range for the current triangle bbox;
  68102. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  68103. // first look for points inside the triangle in increasing z-order
  68104. var p = ear.nextZ;
  68105. while (p && p.z <= maxZ) {
  68106. if (p !== ear.prev &&
  68107. p !== ear.next &&
  68108. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68109. area(p.prev, p, p.next) >= 0)
  68110. return false;
  68111. p = p.nextZ;
  68112. }
  68113. // then look for points in decreasing z-order
  68114. p = ear.prevZ;
  68115. while (p && p.z >= minZ) {
  68116. if (p !== ear.prev &&
  68117. p !== ear.next &&
  68118. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68119. area(p.prev, p, p.next) >= 0)
  68120. return false;
  68121. p = p.prevZ;
  68122. }
  68123. return true;
  68124. }
  68125. // go through all polygon nodes and cure small local self-intersections
  68126. function cureLocalIntersections(start, triangles, dim) {
  68127. var p = start;
  68128. do {
  68129. var a = p.prev, b = p.next.next;
  68130. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  68131. triangles.push(a.i / dim);
  68132. triangles.push(p.i / dim);
  68133. triangles.push(b.i / dim);
  68134. // remove two nodes involved
  68135. removeNode(p);
  68136. removeNode(p.next);
  68137. p = start = b;
  68138. }
  68139. p = p.next;
  68140. } while (p !== start);
  68141. return p;
  68142. }
  68143. // try splitting polygon into two and triangulate them independently
  68144. function splitEarcut(start, triangles, dim, minX, minY, size) {
  68145. // look for a valid diagonal that divides the polygon into two
  68146. var a = start;
  68147. do {
  68148. var b = a.next.next;
  68149. while (b !== a.prev) {
  68150. if (a.i !== b.i && isValidDiagonal(a, b)) {
  68151. // split the polygon in two by the diagonal
  68152. var c = splitPolygon(a, b);
  68153. // filter colinear points around the cuts
  68154. a = filterPoints(a, a.next);
  68155. c = filterPoints(c, c.next);
  68156. // run earcut on each half
  68157. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  68158. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  68159. return;
  68160. }
  68161. b = b.next;
  68162. }
  68163. a = a.next;
  68164. } while (a !== start);
  68165. }
  68166. // link every hole into the outer loop, producing a single-ring polygon without holes
  68167. function eliminateHoles(data, holeIndices, outerNode, dim) {
  68168. var queue = [], i, len, start, end, list;
  68169. for (i = 0, len = holeIndices.length; i < len; i++) {
  68170. start = holeIndices[i] * dim;
  68171. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68172. list = linkedList(data, start, end, dim, false);
  68173. if (list === list.next)
  68174. list.steiner = true;
  68175. queue.push(getLeftmost(list));
  68176. }
  68177. queue.sort(compareX);
  68178. // process holes from left to right
  68179. for (i = 0; i < queue.length; i++) {
  68180. eliminateHole(queue[i], outerNode);
  68181. outerNode = filterPoints(outerNode, outerNode.next);
  68182. }
  68183. return outerNode;
  68184. }
  68185. function compareX(a, b) {
  68186. return a.x - b.x;
  68187. }
  68188. // find a bridge between vertices that connects hole with an outer ring and and link it
  68189. function eliminateHole(hole, outerNode) {
  68190. outerNode = findHoleBridge(hole, outerNode);
  68191. if (outerNode) {
  68192. var b = splitPolygon(outerNode, hole);
  68193. filterPoints(b, b.next);
  68194. }
  68195. }
  68196. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  68197. function findHoleBridge(hole, outerNode) {
  68198. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  68199. // find a segment intersected by a ray from the hole's leftmost point to the left;
  68200. // segment's endpoint with lesser x will be potential connection point
  68201. do {
  68202. if (hy <= p.y && hy >= p.next.y) {
  68203. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  68204. if (x <= hx && x > qx) {
  68205. qx = x;
  68206. if (x === hx) {
  68207. if (hy === p.y)
  68208. return p;
  68209. if (hy === p.next.y)
  68210. return p.next;
  68211. }
  68212. m = p.x < p.next.x ? p : p.next;
  68213. }
  68214. }
  68215. p = p.next;
  68216. } while (p !== outerNode);
  68217. if (!m)
  68218. return null;
  68219. if (hx === qx)
  68220. return m.prev; // hole touches outer segment; pick lower endpoint
  68221. // look for points inside the triangle of hole point, segment intersection and endpoint;
  68222. // if there are no points found, we have a valid connection;
  68223. // otherwise choose the point of the minimum angle with the ray as connection point
  68224. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  68225. p = m.next;
  68226. while (p !== stop) {
  68227. if (hx >= p.x &&
  68228. p.x >= mx &&
  68229. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  68230. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  68231. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  68232. m = p;
  68233. tanMin = tan;
  68234. }
  68235. }
  68236. p = p.next;
  68237. }
  68238. return m;
  68239. }
  68240. // interlink polygon nodes in z-order
  68241. function indexCurve(start, minX, minY, size) {
  68242. var p = start;
  68243. do {
  68244. if (p.z === null)
  68245. p.z = zOrder(p.x, p.y, minX, minY, size);
  68246. p.prevZ = p.prev;
  68247. p.nextZ = p.next;
  68248. p = p.next;
  68249. } while (p !== start);
  68250. p.prevZ.nextZ = null;
  68251. p.prevZ = null;
  68252. sortLinked(p);
  68253. }
  68254. // Simon Tatham's linked list merge sort algorithm
  68255. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  68256. function sortLinked(list) {
  68257. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  68258. do {
  68259. p = list;
  68260. list = null;
  68261. tail = null;
  68262. numMerges = 0;
  68263. while (p) {
  68264. numMerges++;
  68265. q = p;
  68266. pSize = 0;
  68267. for (i = 0; i < inSize; i++) {
  68268. pSize++;
  68269. q = q.nextZ;
  68270. if (!q)
  68271. break;
  68272. }
  68273. qSize = inSize;
  68274. while (pSize > 0 || (qSize > 0 && q)) {
  68275. if (pSize === 0) {
  68276. e = q;
  68277. q = q.nextZ;
  68278. qSize--;
  68279. }
  68280. else if (qSize === 0 || !q) {
  68281. e = p;
  68282. p = p.nextZ;
  68283. pSize--;
  68284. }
  68285. else if (p.z <= q.z) {
  68286. e = p;
  68287. p = p.nextZ;
  68288. pSize--;
  68289. }
  68290. else {
  68291. e = q;
  68292. q = q.nextZ;
  68293. qSize--;
  68294. }
  68295. if (tail)
  68296. tail.nextZ = e;
  68297. else
  68298. list = e;
  68299. e.prevZ = tail;
  68300. tail = e;
  68301. }
  68302. p = q;
  68303. }
  68304. tail.nextZ = null;
  68305. inSize *= 2;
  68306. } while (numMerges > 1);
  68307. return list;
  68308. }
  68309. // z-order of a point given coords and size of the data bounding box
  68310. function zOrder(x, y, minX, minY, size) {
  68311. // coords are transformed into non-negative 15-bit integer range
  68312. x = 32767 * (x - minX) / size;
  68313. y = 32767 * (y - minY) / size;
  68314. x = (x | (x << 8)) & 0x00FF00FF;
  68315. x = (x | (x << 4)) & 0x0F0F0F0F;
  68316. x = (x | (x << 2)) & 0x33333333;
  68317. x = (x | (x << 1)) & 0x55555555;
  68318. y = (y | (y << 8)) & 0x00FF00FF;
  68319. y = (y | (y << 4)) & 0x0F0F0F0F;
  68320. y = (y | (y << 2)) & 0x33333333;
  68321. y = (y | (y << 1)) & 0x55555555;
  68322. return x | (y << 1);
  68323. }
  68324. // find the leftmost node of a polygon ring
  68325. function getLeftmost(start) {
  68326. var p = start, leftmost = start;
  68327. do {
  68328. if (p.x < leftmost.x)
  68329. leftmost = p;
  68330. p = p.next;
  68331. } while (p !== start);
  68332. return leftmost;
  68333. }
  68334. // check if a point lies within a convex triangle
  68335. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  68336. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  68337. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  68338. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  68339. }
  68340. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  68341. function isValidDiagonal(a, b) {
  68342. return a.next.i !== b.i &&
  68343. a.prev.i !== b.i &&
  68344. !intersectsPolygon(a, b) &&
  68345. locallyInside(a, b) &&
  68346. locallyInside(b, a) &&
  68347. middleInside(a, b);
  68348. }
  68349. // signed area of a triangle
  68350. function area(p, q, r) {
  68351. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  68352. }
  68353. // check if two points are equal
  68354. function equals(p1, p2) {
  68355. return p1.x === p2.x && p1.y === p2.y;
  68356. }
  68357. // check if two segments intersect
  68358. function intersects(p1, q1, p2, q2) {
  68359. if ((equals(p1, q1) && equals(p2, q2)) ||
  68360. (equals(p1, q2) && equals(p2, q1)))
  68361. return true;
  68362. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  68363. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  68364. }
  68365. // check if a polygon diagonal intersects any polygon segments
  68366. function intersectsPolygon(a, b) {
  68367. var p = a;
  68368. do {
  68369. if (p.i !== a.i &&
  68370. p.next.i !== a.i &&
  68371. p.i !== b.i &&
  68372. p.next.i !== b.i &&
  68373. intersects(p, p.next, a, b))
  68374. return true;
  68375. p = p.next;
  68376. } while (p !== a);
  68377. return false;
  68378. }
  68379. // check if a polygon diagonal is locally inside the polygon
  68380. function locallyInside(a, b) {
  68381. return area(a.prev, a, a.next) < 0
  68382. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  68383. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  68384. }
  68385. // check if the middle point of a polygon diagonal is inside the polygon
  68386. function middleInside(a, b) {
  68387. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  68388. do {
  68389. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  68390. inside = !inside;
  68391. p = p.next;
  68392. } while (p !== a);
  68393. return inside;
  68394. }
  68395. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  68396. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  68397. function splitPolygon(a, b) {
  68398. 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;
  68399. a.next = b;
  68400. b.prev = a;
  68401. a2.next = an;
  68402. an.prev = a2;
  68403. b2.next = a2;
  68404. a2.prev = b2;
  68405. bp.next = b2;
  68406. b2.prev = bp;
  68407. return b2;
  68408. }
  68409. // create a node and optionally link it with previous one (in a circular doubly linked list)
  68410. function insertNode(i, x, y, last) {
  68411. var p = new Node(i, x, y);
  68412. if (!last) {
  68413. p.prev = p;
  68414. p.next = p;
  68415. }
  68416. else {
  68417. p.next = last.next;
  68418. p.prev = last;
  68419. last.next.prev = p;
  68420. last.next = p;
  68421. }
  68422. return p;
  68423. }
  68424. function removeNode(p) {
  68425. p.next.prev = p.prev;
  68426. p.prev.next = p.next;
  68427. if (p.prevZ)
  68428. p.prevZ.nextZ = p.nextZ;
  68429. if (p.nextZ)
  68430. p.nextZ.prevZ = p.prevZ;
  68431. }
  68432. /**
  68433. * return a percentage difference between the polygon area and its triangulation area;
  68434. * used to verify correctness of triangulation
  68435. */
  68436. function deviation(data, holeIndices, dim, triangles) {
  68437. var hasHoles = holeIndices && holeIndices.length;
  68438. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  68439. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  68440. if (hasHoles) {
  68441. for (var i = 0, len = holeIndices.length; i < len; i++) {
  68442. var start = holeIndices[i] * dim;
  68443. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68444. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  68445. }
  68446. }
  68447. var trianglesArea = 0;
  68448. for (i = 0; i < triangles.length; i += 3) {
  68449. var a = triangles[i] * dim;
  68450. var b = triangles[i + 1] * dim;
  68451. var c = triangles[i + 2] * dim;
  68452. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  68453. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  68454. }
  68455. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  68456. }
  68457. Earcut.deviation = deviation;
  68458. ;
  68459. function signedArea(data, start, end, dim) {
  68460. var sum = 0;
  68461. for (var i = start, j = end - dim; i < end; i += dim) {
  68462. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  68463. j = i;
  68464. }
  68465. return sum;
  68466. }
  68467. /**
  68468. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  68469. */
  68470. function flatten(data) {
  68471. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  68472. for (var i = 0; i < data.length; i++) {
  68473. for (var j = 0; j < data[i].length; j++) {
  68474. for (var d = 0; d < dim; d++)
  68475. result.vertices.push(data[i][j][d]);
  68476. }
  68477. if (i > 0) {
  68478. holeIndex += data[i - 1].length;
  68479. result.holes.push(holeIndex);
  68480. }
  68481. }
  68482. return result;
  68483. }
  68484. Earcut.flatten = flatten;
  68485. ;
  68486. })(Earcut || (Earcut = {}));
  68487. //# sourceMappingURL=babylon.earcut.js.map
  68488. var BABYLON;
  68489. (function (BABYLON) {
  68490. var IndexedVector2 = /** @class */ (function (_super) {
  68491. __extends(IndexedVector2, _super);
  68492. function IndexedVector2(original, index) {
  68493. var _this = _super.call(this, original.x, original.y) || this;
  68494. _this.index = index;
  68495. return _this;
  68496. }
  68497. return IndexedVector2;
  68498. }(BABYLON.Vector2));
  68499. var PolygonPoints = /** @class */ (function () {
  68500. function PolygonPoints() {
  68501. this.elements = new Array();
  68502. }
  68503. PolygonPoints.prototype.add = function (originalPoints) {
  68504. var _this = this;
  68505. var result = new Array();
  68506. originalPoints.forEach(function (point) {
  68507. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  68508. var newPoint = new IndexedVector2(point, _this.elements.length);
  68509. result.push(newPoint);
  68510. _this.elements.push(newPoint);
  68511. }
  68512. });
  68513. return result;
  68514. };
  68515. PolygonPoints.prototype.computeBounds = function () {
  68516. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68517. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68518. this.elements.forEach(function (point) {
  68519. // x
  68520. if (point.x < lmin.x) {
  68521. lmin.x = point.x;
  68522. }
  68523. else if (point.x > lmax.x) {
  68524. lmax.x = point.x;
  68525. }
  68526. // y
  68527. if (point.y < lmin.y) {
  68528. lmin.y = point.y;
  68529. }
  68530. else if (point.y > lmax.y) {
  68531. lmax.y = point.y;
  68532. }
  68533. });
  68534. return {
  68535. min: lmin,
  68536. max: lmax,
  68537. width: lmax.x - lmin.x,
  68538. height: lmax.y - lmin.y
  68539. };
  68540. };
  68541. return PolygonPoints;
  68542. }());
  68543. var Polygon = /** @class */ (function () {
  68544. function Polygon() {
  68545. }
  68546. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  68547. return [
  68548. new BABYLON.Vector2(xmin, ymin),
  68549. new BABYLON.Vector2(xmax, ymin),
  68550. new BABYLON.Vector2(xmax, ymax),
  68551. new BABYLON.Vector2(xmin, ymax)
  68552. ];
  68553. };
  68554. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  68555. if (cx === void 0) { cx = 0; }
  68556. if (cy === void 0) { cy = 0; }
  68557. if (numberOfSides === void 0) { numberOfSides = 32; }
  68558. var result = new Array();
  68559. var angle = 0;
  68560. var increment = (Math.PI * 2) / numberOfSides;
  68561. for (var i = 0; i < numberOfSides; i++) {
  68562. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  68563. angle -= increment;
  68564. }
  68565. return result;
  68566. };
  68567. Polygon.Parse = function (input) {
  68568. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  68569. var i, result = [];
  68570. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  68571. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  68572. }
  68573. return result;
  68574. };
  68575. Polygon.StartingAt = function (x, y) {
  68576. return BABYLON.Path2.StartingAt(x, y);
  68577. };
  68578. return Polygon;
  68579. }());
  68580. BABYLON.Polygon = Polygon;
  68581. var PolygonMeshBuilder = /** @class */ (function () {
  68582. function PolygonMeshBuilder(name, contours, scene) {
  68583. this._points = new PolygonPoints();
  68584. this._outlinepoints = new PolygonPoints();
  68585. this._holes = new Array();
  68586. this._epoints = new Array();
  68587. this._eholes = new Array();
  68588. this._name = name;
  68589. this._scene = scene;
  68590. var points;
  68591. if (contours instanceof BABYLON.Path2) {
  68592. points = contours.getPoints();
  68593. }
  68594. else {
  68595. points = contours;
  68596. }
  68597. this._addToepoint(points);
  68598. this._points.add(points);
  68599. this._outlinepoints.add(points);
  68600. }
  68601. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  68602. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  68603. var p = points_1[_i];
  68604. this._epoints.push(p.x, p.y);
  68605. }
  68606. };
  68607. PolygonMeshBuilder.prototype.addHole = function (hole) {
  68608. this._points.add(hole);
  68609. var holepoints = new PolygonPoints();
  68610. holepoints.add(hole);
  68611. this._holes.push(holepoints);
  68612. this._eholes.push(this._epoints.length / 2);
  68613. this._addToepoint(hole);
  68614. return this;
  68615. };
  68616. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  68617. var _this = this;
  68618. if (updatable === void 0) { updatable = false; }
  68619. if (depth === void 0) { depth = 0; }
  68620. var result = new BABYLON.Mesh(this._name, this._scene);
  68621. var normals = new Array();
  68622. var positions = new Array();
  68623. var uvs = new Array();
  68624. var bounds = this._points.computeBounds();
  68625. this._points.elements.forEach(function (p) {
  68626. normals.push(0, 1.0, 0);
  68627. positions.push(p.x, 0, p.y);
  68628. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  68629. });
  68630. var indices = new Array();
  68631. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  68632. for (var i = 0; i < res.length; i++) {
  68633. indices.push(res[i]);
  68634. }
  68635. if (depth > 0) {
  68636. var positionscount = (positions.length / 3); //get the current pointcount
  68637. this._points.elements.forEach(function (p) {
  68638. normals.push(0, -1.0, 0);
  68639. positions.push(p.x, -depth, p.y);
  68640. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  68641. });
  68642. var totalCount = indices.length;
  68643. for (var i = 0; i < totalCount; i += 3) {
  68644. var i0 = indices[i + 0];
  68645. var i1 = indices[i + 1];
  68646. var i2 = indices[i + 2];
  68647. indices.push(i2 + positionscount);
  68648. indices.push(i1 + positionscount);
  68649. indices.push(i0 + positionscount);
  68650. }
  68651. //Add the sides
  68652. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  68653. this._holes.forEach(function (hole) {
  68654. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  68655. });
  68656. }
  68657. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  68658. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  68659. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  68660. result.setIndices(indices);
  68661. return result;
  68662. };
  68663. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  68664. var StartIndex = positions.length / 3;
  68665. var ulength = 0;
  68666. for (var i = 0; i < points.elements.length; i++) {
  68667. var p = points.elements[i];
  68668. var p1;
  68669. if ((i + 1) > points.elements.length - 1) {
  68670. p1 = points.elements[0];
  68671. }
  68672. else {
  68673. p1 = points.elements[i + 1];
  68674. }
  68675. positions.push(p.x, 0, p.y);
  68676. positions.push(p.x, -depth, p.y);
  68677. positions.push(p1.x, 0, p1.y);
  68678. positions.push(p1.x, -depth, p1.y);
  68679. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  68680. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  68681. var v3 = v2.subtract(v1);
  68682. var v4 = new BABYLON.Vector3(0, 1, 0);
  68683. var vn = BABYLON.Vector3.Cross(v3, v4);
  68684. vn = vn.normalize();
  68685. uvs.push(ulength / bounds.width, 0);
  68686. uvs.push(ulength / bounds.width, 1);
  68687. ulength += v3.length();
  68688. uvs.push((ulength / bounds.width), 0);
  68689. uvs.push((ulength / bounds.width), 1);
  68690. if (!flip) {
  68691. normals.push(-vn.x, -vn.y, -vn.z);
  68692. normals.push(-vn.x, -vn.y, -vn.z);
  68693. normals.push(-vn.x, -vn.y, -vn.z);
  68694. normals.push(-vn.x, -vn.y, -vn.z);
  68695. indices.push(StartIndex);
  68696. indices.push(StartIndex + 1);
  68697. indices.push(StartIndex + 2);
  68698. indices.push(StartIndex + 1);
  68699. indices.push(StartIndex + 3);
  68700. indices.push(StartIndex + 2);
  68701. }
  68702. else {
  68703. normals.push(vn.x, vn.y, vn.z);
  68704. normals.push(vn.x, vn.y, vn.z);
  68705. normals.push(vn.x, vn.y, vn.z);
  68706. normals.push(vn.x, vn.y, vn.z);
  68707. indices.push(StartIndex);
  68708. indices.push(StartIndex + 2);
  68709. indices.push(StartIndex + 1);
  68710. indices.push(StartIndex + 1);
  68711. indices.push(StartIndex + 2);
  68712. indices.push(StartIndex + 3);
  68713. }
  68714. StartIndex += 4;
  68715. }
  68716. ;
  68717. };
  68718. return PolygonMeshBuilder;
  68719. }());
  68720. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  68721. })(BABYLON || (BABYLON = {}));
  68722. //# sourceMappingURL=babylon.polygonMesh.js.map
  68723. var BABYLON;
  68724. (function (BABYLON) {
  68725. // Unique ID when we import meshes from Babylon to CSG
  68726. var currentCSGMeshId = 0;
  68727. // # class Vertex
  68728. // Represents a vertex of a polygon. Use your own vertex class instead of this
  68729. // one to provide additional features like texture coordinates and vertex
  68730. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  68731. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  68732. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  68733. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  68734. // is not used anywhere else.
  68735. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  68736. var Vertex = /** @class */ (function () {
  68737. function Vertex(pos, normal, uv) {
  68738. this.pos = pos;
  68739. this.normal = normal;
  68740. this.uv = uv;
  68741. }
  68742. Vertex.prototype.clone = function () {
  68743. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  68744. };
  68745. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  68746. // orientation of a polygon is flipped.
  68747. Vertex.prototype.flip = function () {
  68748. this.normal = this.normal.scale(-1);
  68749. };
  68750. // Create a new vertex between this vertex and `other` by linearly
  68751. // interpolating all properties using a parameter of `t`. Subclasses should
  68752. // override this to interpolate additional properties.
  68753. Vertex.prototype.interpolate = function (other, t) {
  68754. 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));
  68755. };
  68756. return Vertex;
  68757. }());
  68758. // # class Plane
  68759. // Represents a plane in 3D space.
  68760. var Plane = /** @class */ (function () {
  68761. function Plane(normal, w) {
  68762. this.normal = normal;
  68763. this.w = w;
  68764. }
  68765. Plane.FromPoints = function (a, b, c) {
  68766. var v0 = c.subtract(a);
  68767. var v1 = b.subtract(a);
  68768. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  68769. return null;
  68770. }
  68771. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  68772. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  68773. };
  68774. Plane.prototype.clone = function () {
  68775. return new Plane(this.normal.clone(), this.w);
  68776. };
  68777. Plane.prototype.flip = function () {
  68778. this.normal.scaleInPlace(-1);
  68779. this.w = -this.w;
  68780. };
  68781. // Split `polygon` by this plane if needed, then put the polygon or polygon
  68782. // fragments in the appropriate lists. Coplanar polygons go into either
  68783. // `coplanarFront` or `coplanarBack` depending on their orientation with
  68784. // respect to this plane. Polygons in front or in back of this plane go into
  68785. // either `front` or `back`.
  68786. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  68787. var COPLANAR = 0;
  68788. var FRONT = 1;
  68789. var BACK = 2;
  68790. var SPANNING = 3;
  68791. // Classify each point as well as the entire polygon into one of the above
  68792. // four classes.
  68793. var polygonType = 0;
  68794. var types = [];
  68795. var i;
  68796. var t;
  68797. for (i = 0; i < polygon.vertices.length; i++) {
  68798. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  68799. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  68800. polygonType |= type;
  68801. types.push(type);
  68802. }
  68803. // Put the polygon in the correct list, splitting it when necessary.
  68804. switch (polygonType) {
  68805. case COPLANAR:
  68806. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  68807. break;
  68808. case FRONT:
  68809. front.push(polygon);
  68810. break;
  68811. case BACK:
  68812. back.push(polygon);
  68813. break;
  68814. case SPANNING:
  68815. var f = [], b = [];
  68816. for (i = 0; i < polygon.vertices.length; i++) {
  68817. var j = (i + 1) % polygon.vertices.length;
  68818. var ti = types[i], tj = types[j];
  68819. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  68820. if (ti !== BACK)
  68821. f.push(vi);
  68822. if (ti !== FRONT)
  68823. b.push(ti !== BACK ? vi.clone() : vi);
  68824. if ((ti | tj) === SPANNING) {
  68825. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  68826. var v = vi.interpolate(vj, t);
  68827. f.push(v);
  68828. b.push(v.clone());
  68829. }
  68830. }
  68831. var poly;
  68832. if (f.length >= 3) {
  68833. poly = new Polygon(f, polygon.shared);
  68834. if (poly.plane)
  68835. front.push(poly);
  68836. }
  68837. if (b.length >= 3) {
  68838. poly = new Polygon(b, polygon.shared);
  68839. if (poly.plane)
  68840. back.push(poly);
  68841. }
  68842. break;
  68843. }
  68844. };
  68845. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  68846. // point is on the plane.
  68847. Plane.EPSILON = 1e-5;
  68848. return Plane;
  68849. }());
  68850. // # class Polygon
  68851. // Represents a convex polygon. The vertices used to initialize a polygon must
  68852. // be coplanar and form a convex loop.
  68853. //
  68854. // Each convex polygon has a `shared` property, which is shared between all
  68855. // polygons that are clones of each other or were split from the same polygon.
  68856. // This can be used to define per-polygon properties (such as surface color).
  68857. var Polygon = /** @class */ (function () {
  68858. function Polygon(vertices, shared) {
  68859. this.vertices = vertices;
  68860. this.shared = shared;
  68861. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  68862. }
  68863. Polygon.prototype.clone = function () {
  68864. var vertices = this.vertices.map(function (v) { return v.clone(); });
  68865. return new Polygon(vertices, this.shared);
  68866. };
  68867. Polygon.prototype.flip = function () {
  68868. this.vertices.reverse().map(function (v) { v.flip(); });
  68869. this.plane.flip();
  68870. };
  68871. return Polygon;
  68872. }());
  68873. // # class Node
  68874. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  68875. // by picking a polygon to split along. That polygon (and all other coplanar
  68876. // polygons) are added directly to that node and the other polygons are added to
  68877. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  68878. // no distinction between internal and leaf nodes.
  68879. var Node = /** @class */ (function () {
  68880. function Node(polygons) {
  68881. this.plane = null;
  68882. this.front = null;
  68883. this.back = null;
  68884. this.polygons = new Array();
  68885. if (polygons) {
  68886. this.build(polygons);
  68887. }
  68888. }
  68889. Node.prototype.clone = function () {
  68890. var node = new Node();
  68891. node.plane = this.plane && this.plane.clone();
  68892. node.front = this.front && this.front.clone();
  68893. node.back = this.back && this.back.clone();
  68894. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  68895. return node;
  68896. };
  68897. // Convert solid space to empty space and empty space to solid space.
  68898. Node.prototype.invert = function () {
  68899. for (var i = 0; i < this.polygons.length; i++) {
  68900. this.polygons[i].flip();
  68901. }
  68902. if (this.plane) {
  68903. this.plane.flip();
  68904. }
  68905. if (this.front) {
  68906. this.front.invert();
  68907. }
  68908. if (this.back) {
  68909. this.back.invert();
  68910. }
  68911. var temp = this.front;
  68912. this.front = this.back;
  68913. this.back = temp;
  68914. };
  68915. // Recursively remove all polygons in `polygons` that are inside this BSP
  68916. // tree.
  68917. Node.prototype.clipPolygons = function (polygons) {
  68918. if (!this.plane)
  68919. return polygons.slice();
  68920. var front = new Array(), back = new Array();
  68921. for (var i = 0; i < polygons.length; i++) {
  68922. this.plane.splitPolygon(polygons[i], front, back, front, back);
  68923. }
  68924. if (this.front) {
  68925. front = this.front.clipPolygons(front);
  68926. }
  68927. if (this.back) {
  68928. back = this.back.clipPolygons(back);
  68929. }
  68930. else {
  68931. back = [];
  68932. }
  68933. return front.concat(back);
  68934. };
  68935. // Remove all polygons in this BSP tree that are inside the other BSP tree
  68936. // `bsp`.
  68937. Node.prototype.clipTo = function (bsp) {
  68938. this.polygons = bsp.clipPolygons(this.polygons);
  68939. if (this.front)
  68940. this.front.clipTo(bsp);
  68941. if (this.back)
  68942. this.back.clipTo(bsp);
  68943. };
  68944. // Return a list of all polygons in this BSP tree.
  68945. Node.prototype.allPolygons = function () {
  68946. var polygons = this.polygons.slice();
  68947. if (this.front)
  68948. polygons = polygons.concat(this.front.allPolygons());
  68949. if (this.back)
  68950. polygons = polygons.concat(this.back.allPolygons());
  68951. return polygons;
  68952. };
  68953. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  68954. // new polygons are filtered down to the bottom of the tree and become new
  68955. // nodes there. Each set of polygons is partitioned using the first polygon
  68956. // (no heuristic is used to pick a good split).
  68957. Node.prototype.build = function (polygons) {
  68958. if (!polygons.length)
  68959. return;
  68960. if (!this.plane)
  68961. this.plane = polygons[0].plane.clone();
  68962. var front = new Array(), back = new Array();
  68963. for (var i = 0; i < polygons.length; i++) {
  68964. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  68965. }
  68966. if (front.length) {
  68967. if (!this.front)
  68968. this.front = new Node();
  68969. this.front.build(front);
  68970. }
  68971. if (back.length) {
  68972. if (!this.back)
  68973. this.back = new Node();
  68974. this.back.build(back);
  68975. }
  68976. };
  68977. return Node;
  68978. }());
  68979. var CSG = /** @class */ (function () {
  68980. function CSG() {
  68981. this.polygons = new Array();
  68982. }
  68983. // Convert BABYLON.Mesh to BABYLON.CSG
  68984. CSG.FromMesh = function (mesh) {
  68985. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  68986. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  68987. if (mesh instanceof BABYLON.Mesh) {
  68988. mesh.computeWorldMatrix(true);
  68989. matrix = mesh.getWorldMatrix();
  68990. meshPosition = mesh.position.clone();
  68991. meshRotation = mesh.rotation.clone();
  68992. if (mesh.rotationQuaternion) {
  68993. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  68994. }
  68995. meshScaling = mesh.scaling.clone();
  68996. }
  68997. else {
  68998. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  68999. }
  69000. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69001. var subMeshes = mesh.subMeshes;
  69002. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  69003. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  69004. vertices = [];
  69005. for (var j = 0; j < 3; j++) {
  69006. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  69007. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  69008. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  69009. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  69010. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  69011. vertex = new Vertex(position, normal, uv);
  69012. vertices.push(vertex);
  69013. }
  69014. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  69015. // To handle the case of degenerated triangle
  69016. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  69017. if (polygon.plane)
  69018. polygons.push(polygon);
  69019. }
  69020. }
  69021. var csg = CSG.FromPolygons(polygons);
  69022. csg.matrix = matrix;
  69023. csg.position = meshPosition;
  69024. csg.rotation = meshRotation;
  69025. csg.scaling = meshScaling;
  69026. csg.rotationQuaternion = meshRotationQuaternion;
  69027. currentCSGMeshId++;
  69028. return csg;
  69029. };
  69030. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  69031. CSG.FromPolygons = function (polygons) {
  69032. var csg = new CSG();
  69033. csg.polygons = polygons;
  69034. return csg;
  69035. };
  69036. CSG.prototype.clone = function () {
  69037. var csg = new CSG();
  69038. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  69039. csg.copyTransformAttributes(this);
  69040. return csg;
  69041. };
  69042. CSG.prototype.union = function (csg) {
  69043. var a = new Node(this.clone().polygons);
  69044. var b = new Node(csg.clone().polygons);
  69045. a.clipTo(b);
  69046. b.clipTo(a);
  69047. b.invert();
  69048. b.clipTo(a);
  69049. b.invert();
  69050. a.build(b.allPolygons());
  69051. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69052. };
  69053. CSG.prototype.unionInPlace = function (csg) {
  69054. var a = new Node(this.polygons);
  69055. var b = new Node(csg.polygons);
  69056. a.clipTo(b);
  69057. b.clipTo(a);
  69058. b.invert();
  69059. b.clipTo(a);
  69060. b.invert();
  69061. a.build(b.allPolygons());
  69062. this.polygons = a.allPolygons();
  69063. };
  69064. CSG.prototype.subtract = function (csg) {
  69065. var a = new Node(this.clone().polygons);
  69066. var b = new Node(csg.clone().polygons);
  69067. a.invert();
  69068. a.clipTo(b);
  69069. b.clipTo(a);
  69070. b.invert();
  69071. b.clipTo(a);
  69072. b.invert();
  69073. a.build(b.allPolygons());
  69074. a.invert();
  69075. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69076. };
  69077. CSG.prototype.subtractInPlace = function (csg) {
  69078. var a = new Node(this.polygons);
  69079. var b = new Node(csg.polygons);
  69080. a.invert();
  69081. a.clipTo(b);
  69082. b.clipTo(a);
  69083. b.invert();
  69084. b.clipTo(a);
  69085. b.invert();
  69086. a.build(b.allPolygons());
  69087. a.invert();
  69088. this.polygons = a.allPolygons();
  69089. };
  69090. CSG.prototype.intersect = function (csg) {
  69091. var a = new Node(this.clone().polygons);
  69092. var b = new Node(csg.clone().polygons);
  69093. a.invert();
  69094. b.clipTo(a);
  69095. b.invert();
  69096. a.clipTo(b);
  69097. b.clipTo(a);
  69098. a.build(b.allPolygons());
  69099. a.invert();
  69100. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69101. };
  69102. CSG.prototype.intersectInPlace = function (csg) {
  69103. var a = new Node(this.polygons);
  69104. var b = new Node(csg.polygons);
  69105. a.invert();
  69106. b.clipTo(a);
  69107. b.invert();
  69108. a.clipTo(b);
  69109. b.clipTo(a);
  69110. a.build(b.allPolygons());
  69111. a.invert();
  69112. this.polygons = a.allPolygons();
  69113. };
  69114. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  69115. // not modified.
  69116. CSG.prototype.inverse = function () {
  69117. var csg = this.clone();
  69118. csg.inverseInPlace();
  69119. return csg;
  69120. };
  69121. CSG.prototype.inverseInPlace = function () {
  69122. this.polygons.map(function (p) { p.flip(); });
  69123. };
  69124. // This is used to keep meshes transformations so they can be restored
  69125. // when we build back a Babylon Mesh
  69126. // NB : All CSG operations are performed in world coordinates
  69127. CSG.prototype.copyTransformAttributes = function (csg) {
  69128. this.matrix = csg.matrix;
  69129. this.position = csg.position;
  69130. this.rotation = csg.rotation;
  69131. this.scaling = csg.scaling;
  69132. this.rotationQuaternion = csg.rotationQuaternion;
  69133. return this;
  69134. };
  69135. // Build Raw mesh from CSG
  69136. // Coordinates here are in world space
  69137. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  69138. var matrix = this.matrix.clone();
  69139. matrix.invert();
  69140. 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;
  69141. if (keepSubMeshes) {
  69142. // Sort Polygons, since subMeshes are indices range
  69143. polygons.sort(function (a, b) {
  69144. if (a.shared.meshId === b.shared.meshId) {
  69145. return a.shared.subMeshId - b.shared.subMeshId;
  69146. }
  69147. else {
  69148. return a.shared.meshId - b.shared.meshId;
  69149. }
  69150. });
  69151. }
  69152. for (var i = 0, il = polygons.length; i < il; i++) {
  69153. polygon = polygons[i];
  69154. // Building SubMeshes
  69155. if (!subMesh_dict[polygon.shared.meshId]) {
  69156. subMesh_dict[polygon.shared.meshId] = {};
  69157. }
  69158. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  69159. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  69160. indexStart: +Infinity,
  69161. indexEnd: -Infinity,
  69162. materialIndex: polygon.shared.materialIndex
  69163. };
  69164. }
  69165. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  69166. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  69167. polygonIndices[0] = 0;
  69168. polygonIndices[1] = j - 1;
  69169. polygonIndices[2] = j;
  69170. for (var k = 0; k < 3; k++) {
  69171. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  69172. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  69173. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  69174. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  69175. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  69176. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  69177. // Check if 2 points can be merged
  69178. if (!(typeof vertex_idx !== 'undefined' &&
  69179. normals[vertex_idx * 3] === localNormal.x &&
  69180. normals[vertex_idx * 3 + 1] === localNormal.y &&
  69181. normals[vertex_idx * 3 + 2] === localNormal.z &&
  69182. uvs[vertex_idx * 2] === uv.x &&
  69183. uvs[vertex_idx * 2 + 1] === uv.y)) {
  69184. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  69185. uvs.push(uv.x, uv.y);
  69186. normals.push(normal.x, normal.y, normal.z);
  69187. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  69188. }
  69189. indices.push(vertex_idx);
  69190. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  69191. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  69192. currentIndex++;
  69193. }
  69194. }
  69195. }
  69196. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  69197. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  69198. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  69199. mesh.setIndices(indices, null);
  69200. if (keepSubMeshes) {
  69201. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  69202. var materialIndexOffset = 0, materialMaxIndex;
  69203. mesh.subMeshes = new Array();
  69204. for (var m in subMesh_dict) {
  69205. materialMaxIndex = -1;
  69206. for (var sm in subMesh_dict[m]) {
  69207. subMesh_obj = subMesh_dict[m][sm];
  69208. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  69209. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  69210. }
  69211. materialIndexOffset += ++materialMaxIndex;
  69212. }
  69213. }
  69214. return mesh;
  69215. };
  69216. // Build Mesh from CSG taking material and transforms into account
  69217. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  69218. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  69219. mesh.material = material;
  69220. mesh.position.copyFrom(this.position);
  69221. mesh.rotation.copyFrom(this.rotation);
  69222. if (this.rotationQuaternion) {
  69223. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  69224. }
  69225. mesh.scaling.copyFrom(this.scaling);
  69226. mesh.computeWorldMatrix(true);
  69227. return mesh;
  69228. };
  69229. return CSG;
  69230. }());
  69231. BABYLON.CSG = CSG;
  69232. })(BABYLON || (BABYLON = {}));
  69233. //# sourceMappingURL=babylon.csg.js.map
  69234. var BABYLON;
  69235. (function (BABYLON) {
  69236. var LensFlare = /** @class */ (function () {
  69237. function LensFlare(size, position, color, imgUrl, system) {
  69238. this.size = size;
  69239. this.position = position;
  69240. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  69241. this.color = color || new BABYLON.Color3(1, 1, 1);
  69242. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  69243. this._system = system;
  69244. system.lensFlares.push(this);
  69245. }
  69246. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  69247. return new LensFlare(size, position, color, imgUrl, system);
  69248. };
  69249. LensFlare.prototype.dispose = function () {
  69250. if (this.texture) {
  69251. this.texture.dispose();
  69252. }
  69253. // Remove from scene
  69254. var index = this._system.lensFlares.indexOf(this);
  69255. this._system.lensFlares.splice(index, 1);
  69256. };
  69257. ;
  69258. return LensFlare;
  69259. }());
  69260. BABYLON.LensFlare = LensFlare;
  69261. })(BABYLON || (BABYLON = {}));
  69262. //# sourceMappingURL=babylon.lensFlare.js.map
  69263. var BABYLON;
  69264. (function (BABYLON) {
  69265. var LensFlareSystem = /** @class */ (function () {
  69266. function LensFlareSystem(name, emitter, scene) {
  69267. this.name = name;
  69268. this.lensFlares = new Array();
  69269. this.borderLimit = 300;
  69270. this.viewportBorder = 0;
  69271. this.layerMask = 0x0FFFFFFF;
  69272. this._vertexBuffers = {};
  69273. this._isEnabled = true;
  69274. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69275. this._emitter = emitter;
  69276. this.id = name;
  69277. scene.lensFlareSystems.push(this);
  69278. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  69279. var engine = scene.getEngine();
  69280. // VBO
  69281. var vertices = [];
  69282. vertices.push(1, 1);
  69283. vertices.push(-1, 1);
  69284. vertices.push(-1, -1);
  69285. vertices.push(1, -1);
  69286. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69287. // Indices
  69288. var indices = [];
  69289. indices.push(0);
  69290. indices.push(1);
  69291. indices.push(2);
  69292. indices.push(0);
  69293. indices.push(2);
  69294. indices.push(3);
  69295. this._indexBuffer = engine.createIndexBuffer(indices);
  69296. // Effects
  69297. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  69298. }
  69299. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  69300. get: function () {
  69301. return this._isEnabled;
  69302. },
  69303. set: function (value) {
  69304. this._isEnabled = value;
  69305. },
  69306. enumerable: true,
  69307. configurable: true
  69308. });
  69309. LensFlareSystem.prototype.getScene = function () {
  69310. return this._scene;
  69311. };
  69312. LensFlareSystem.prototype.getEmitter = function () {
  69313. return this._emitter;
  69314. };
  69315. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  69316. this._emitter = newEmitter;
  69317. };
  69318. LensFlareSystem.prototype.getEmitterPosition = function () {
  69319. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  69320. };
  69321. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  69322. var position = this.getEmitterPosition();
  69323. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  69324. this._positionX = position.x;
  69325. this._positionY = position.y;
  69326. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  69327. if (this.viewportBorder > 0) {
  69328. globalViewport.x -= this.viewportBorder;
  69329. globalViewport.y -= this.viewportBorder;
  69330. globalViewport.width += this.viewportBorder * 2;
  69331. globalViewport.height += this.viewportBorder * 2;
  69332. position.x += this.viewportBorder;
  69333. position.y += this.viewportBorder;
  69334. this._positionX += this.viewportBorder;
  69335. this._positionY += this.viewportBorder;
  69336. }
  69337. if (position.z > 0) {
  69338. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  69339. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  69340. return true;
  69341. }
  69342. return true;
  69343. }
  69344. return false;
  69345. };
  69346. LensFlareSystem.prototype._isVisible = function () {
  69347. if (!this._isEnabled || !this._scene.activeCamera) {
  69348. return false;
  69349. }
  69350. var emitterPosition = this.getEmitterPosition();
  69351. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  69352. var distance = direction.length();
  69353. direction.normalize();
  69354. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  69355. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  69356. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  69357. };
  69358. LensFlareSystem.prototype.render = function () {
  69359. if (!this._effect.isReady() || !this._scene.activeCamera)
  69360. return false;
  69361. var engine = this._scene.getEngine();
  69362. var viewport = this._scene.activeCamera.viewport;
  69363. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  69364. // Position
  69365. if (!this.computeEffectivePosition(globalViewport)) {
  69366. return false;
  69367. }
  69368. // Visibility
  69369. if (!this._isVisible()) {
  69370. return false;
  69371. }
  69372. // Intensity
  69373. var awayX;
  69374. var awayY;
  69375. if (this._positionX < this.borderLimit + globalViewport.x) {
  69376. awayX = this.borderLimit + globalViewport.x - this._positionX;
  69377. }
  69378. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  69379. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  69380. }
  69381. else {
  69382. awayX = 0;
  69383. }
  69384. if (this._positionY < this.borderLimit + globalViewport.y) {
  69385. awayY = this.borderLimit + globalViewport.y - this._positionY;
  69386. }
  69387. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  69388. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  69389. }
  69390. else {
  69391. awayY = 0;
  69392. }
  69393. var away = (awayX > awayY) ? awayX : awayY;
  69394. away -= this.viewportBorder;
  69395. if (away > this.borderLimit) {
  69396. away = this.borderLimit;
  69397. }
  69398. var intensity = 1.0 - (away / this.borderLimit);
  69399. if (intensity < 0) {
  69400. return false;
  69401. }
  69402. if (intensity > 1.0) {
  69403. intensity = 1.0;
  69404. }
  69405. if (this.viewportBorder > 0) {
  69406. globalViewport.x += this.viewportBorder;
  69407. globalViewport.y += this.viewportBorder;
  69408. globalViewport.width -= this.viewportBorder * 2;
  69409. globalViewport.height -= this.viewportBorder * 2;
  69410. this._positionX -= this.viewportBorder;
  69411. this._positionY -= this.viewportBorder;
  69412. }
  69413. // Position
  69414. var centerX = globalViewport.x + globalViewport.width / 2;
  69415. var centerY = globalViewport.y + globalViewport.height / 2;
  69416. var distX = centerX - this._positionX;
  69417. var distY = centerY - this._positionY;
  69418. // Effects
  69419. engine.enableEffect(this._effect);
  69420. engine.setState(false);
  69421. engine.setDepthBuffer(false);
  69422. // VBOs
  69423. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69424. // Flares
  69425. for (var index = 0; index < this.lensFlares.length; index++) {
  69426. var flare = this.lensFlares[index];
  69427. engine.setAlphaMode(flare.alphaMode);
  69428. var x = centerX - (distX * flare.position);
  69429. var y = centerY - (distY * flare.position);
  69430. var cw = flare.size;
  69431. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  69432. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  69433. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  69434. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  69435. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  69436. // Texture
  69437. this._effect.setTexture("textureSampler", flare.texture);
  69438. // Color
  69439. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  69440. // Draw order
  69441. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69442. }
  69443. engine.setDepthBuffer(true);
  69444. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69445. return true;
  69446. };
  69447. LensFlareSystem.prototype.dispose = function () {
  69448. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69449. if (vertexBuffer) {
  69450. vertexBuffer.dispose();
  69451. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69452. }
  69453. if (this._indexBuffer) {
  69454. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69455. this._indexBuffer = null;
  69456. }
  69457. while (this.lensFlares.length) {
  69458. this.lensFlares[0].dispose();
  69459. }
  69460. // Remove from scene
  69461. var index = this._scene.lensFlareSystems.indexOf(this);
  69462. this._scene.lensFlareSystems.splice(index, 1);
  69463. };
  69464. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  69465. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  69466. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  69467. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  69468. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  69469. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  69470. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  69471. var parsedFlare = parsedLensFlareSystem.flares[index];
  69472. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  69473. }
  69474. return lensFlareSystem;
  69475. };
  69476. LensFlareSystem.prototype.serialize = function () {
  69477. var serializationObject = {};
  69478. serializationObject.id = this.id;
  69479. serializationObject.name = this.name;
  69480. serializationObject.emitterId = this.getEmitter().id;
  69481. serializationObject.borderLimit = this.borderLimit;
  69482. serializationObject.flares = [];
  69483. for (var index = 0; index < this.lensFlares.length; index++) {
  69484. var flare = this.lensFlares[index];
  69485. serializationObject.flares.push({
  69486. size: flare.size,
  69487. position: flare.position,
  69488. color: flare.color.asArray(),
  69489. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  69490. });
  69491. }
  69492. return serializationObject;
  69493. };
  69494. return LensFlareSystem;
  69495. }());
  69496. BABYLON.LensFlareSystem = LensFlareSystem;
  69497. })(BABYLON || (BABYLON = {}));
  69498. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  69499. var BABYLON;
  69500. (function (BABYLON) {
  69501. /**
  69502. * This is a holder class for the physics joint created by the physics plugin.
  69503. * It holds a set of functions to control the underlying joint.
  69504. */
  69505. var PhysicsJoint = /** @class */ (function () {
  69506. function PhysicsJoint(type, jointData) {
  69507. this.type = type;
  69508. this.jointData = jointData;
  69509. jointData.nativeParams = jointData.nativeParams || {};
  69510. }
  69511. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  69512. get: function () {
  69513. return this._physicsJoint;
  69514. },
  69515. set: function (newJoint) {
  69516. if (this._physicsJoint) {
  69517. //remove from the wolrd
  69518. }
  69519. this._physicsJoint = newJoint;
  69520. },
  69521. enumerable: true,
  69522. configurable: true
  69523. });
  69524. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  69525. set: function (physicsPlugin) {
  69526. this._physicsPlugin = physicsPlugin;
  69527. },
  69528. enumerable: true,
  69529. configurable: true
  69530. });
  69531. /**
  69532. * Execute a function that is physics-plugin specific.
  69533. * @param {Function} func the function that will be executed.
  69534. * It accepts two parameters: the physics world and the physics joint.
  69535. */
  69536. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  69537. func(this._physicsPlugin.world, this._physicsJoint);
  69538. };
  69539. //TODO check if the native joints are the same
  69540. //Joint Types
  69541. PhysicsJoint.DistanceJoint = 0;
  69542. PhysicsJoint.HingeJoint = 1;
  69543. PhysicsJoint.BallAndSocketJoint = 2;
  69544. PhysicsJoint.WheelJoint = 3;
  69545. PhysicsJoint.SliderJoint = 4;
  69546. //OIMO
  69547. PhysicsJoint.PrismaticJoint = 5;
  69548. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  69549. PhysicsJoint.UniversalJoint = 6;
  69550. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  69551. //Cannon
  69552. //Similar to a Ball-Joint. Different in params
  69553. PhysicsJoint.PointToPointJoint = 8;
  69554. //Cannon only at the moment
  69555. PhysicsJoint.SpringJoint = 9;
  69556. PhysicsJoint.LockJoint = 10;
  69557. return PhysicsJoint;
  69558. }());
  69559. BABYLON.PhysicsJoint = PhysicsJoint;
  69560. /**
  69561. * A class representing a physics distance joint.
  69562. */
  69563. var DistanceJoint = /** @class */ (function (_super) {
  69564. __extends(DistanceJoint, _super);
  69565. function DistanceJoint(jointData) {
  69566. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  69567. }
  69568. /**
  69569. * Update the predefined distance.
  69570. */
  69571. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  69572. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  69573. };
  69574. return DistanceJoint;
  69575. }(PhysicsJoint));
  69576. BABYLON.DistanceJoint = DistanceJoint;
  69577. var MotorEnabledJoint = /** @class */ (function (_super) {
  69578. __extends(MotorEnabledJoint, _super);
  69579. function MotorEnabledJoint(type, jointData) {
  69580. return _super.call(this, type, jointData) || this;
  69581. }
  69582. /**
  69583. * Set the motor values.
  69584. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69585. * @param {number} force the force to apply
  69586. * @param {number} maxForce max force for this motor.
  69587. */
  69588. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  69589. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69590. };
  69591. /**
  69592. * Set the motor's limits.
  69593. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69594. */
  69595. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  69596. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  69597. };
  69598. return MotorEnabledJoint;
  69599. }(PhysicsJoint));
  69600. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  69601. /**
  69602. * This class represents a single hinge physics joint
  69603. */
  69604. var HingeJoint = /** @class */ (function (_super) {
  69605. __extends(HingeJoint, _super);
  69606. function HingeJoint(jointData) {
  69607. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  69608. }
  69609. /**
  69610. * Set the motor values.
  69611. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69612. * @param {number} force the force to apply
  69613. * @param {number} maxForce max force for this motor.
  69614. */
  69615. HingeJoint.prototype.setMotor = function (force, maxForce) {
  69616. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69617. };
  69618. /**
  69619. * Set the motor's limits.
  69620. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69621. */
  69622. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  69623. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  69624. };
  69625. return HingeJoint;
  69626. }(MotorEnabledJoint));
  69627. BABYLON.HingeJoint = HingeJoint;
  69628. /**
  69629. * This class represents a dual hinge physics joint (same as wheel joint)
  69630. */
  69631. var Hinge2Joint = /** @class */ (function (_super) {
  69632. __extends(Hinge2Joint, _super);
  69633. function Hinge2Joint(jointData) {
  69634. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  69635. }
  69636. /**
  69637. * Set the motor values.
  69638. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69639. * @param {number} force the force to apply
  69640. * @param {number} maxForce max force for this motor.
  69641. * @param {motorIndex} the motor's index, 0 or 1.
  69642. */
  69643. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  69644. if (motorIndex === void 0) { motorIndex = 0; }
  69645. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  69646. };
  69647. /**
  69648. * Set the motor limits.
  69649. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69650. * @param {number} upperLimit the upper limit
  69651. * @param {number} lowerLimit lower limit
  69652. * @param {motorIndex} the motor's index, 0 or 1.
  69653. */
  69654. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  69655. if (motorIndex === void 0) { motorIndex = 0; }
  69656. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  69657. };
  69658. return Hinge2Joint;
  69659. }(MotorEnabledJoint));
  69660. BABYLON.Hinge2Joint = Hinge2Joint;
  69661. })(BABYLON || (BABYLON = {}));
  69662. //# sourceMappingURL=babylon.physicsJoint.js.map
  69663. var BABYLON;
  69664. (function (BABYLON) {
  69665. var PhysicsImpostor = /** @class */ (function () {
  69666. function PhysicsImpostor(object, type, _options, _scene) {
  69667. if (_options === void 0) { _options = { mass: 0 }; }
  69668. var _this = this;
  69669. this.object = object;
  69670. this.type = type;
  69671. this._options = _options;
  69672. this._scene = _scene;
  69673. this._bodyUpdateRequired = false;
  69674. this._onBeforePhysicsStepCallbacks = new Array();
  69675. this._onAfterPhysicsStepCallbacks = new Array();
  69676. this._onPhysicsCollideCallbacks = [];
  69677. this._deltaPosition = BABYLON.Vector3.Zero();
  69678. this._isDisposed = false;
  69679. //temp variables for parent rotation calculations
  69680. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  69681. this._tmpQuat = new BABYLON.Quaternion();
  69682. this._tmpQuat2 = new BABYLON.Quaternion();
  69683. /**
  69684. * this function is executed by the physics engine.
  69685. */
  69686. this.beforeStep = function () {
  69687. if (!_this._physicsEngine) {
  69688. return;
  69689. }
  69690. _this.object.translate(_this._deltaPosition, -1);
  69691. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  69692. _this.object.computeWorldMatrix(false);
  69693. if (_this.object.parent && _this.object.rotationQuaternion) {
  69694. _this.getParentsRotation();
  69695. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  69696. }
  69697. else {
  69698. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  69699. }
  69700. if (!_this._options.disableBidirectionalTransformation) {
  69701. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  69702. }
  69703. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  69704. func(_this);
  69705. });
  69706. };
  69707. /**
  69708. * this function is executed by the physics engine.
  69709. */
  69710. this.afterStep = function () {
  69711. if (!_this._physicsEngine) {
  69712. return;
  69713. }
  69714. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  69715. func(_this);
  69716. });
  69717. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  69718. // object has now its world rotation. needs to be converted to local.
  69719. if (_this.object.parent && _this.object.rotationQuaternion) {
  69720. _this.getParentsRotation();
  69721. _this._tmpQuat.conjugateInPlace();
  69722. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  69723. }
  69724. // take the position set and make it the absolute position of this object.
  69725. _this.object.setAbsolutePosition(_this.object.position);
  69726. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  69727. _this.object.translate(_this._deltaPosition, 1);
  69728. };
  69729. /**
  69730. * Legacy collision detection event support
  69731. */
  69732. this.onCollideEvent = null;
  69733. //event and body object due to cannon's event-based architecture.
  69734. this.onCollide = function (e) {
  69735. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  69736. return;
  69737. }
  69738. if (!_this._physicsEngine) {
  69739. return;
  69740. }
  69741. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  69742. if (otherImpostor) {
  69743. // Legacy collision detection event support
  69744. if (_this.onCollideEvent) {
  69745. _this.onCollideEvent(_this, otherImpostor);
  69746. }
  69747. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  69748. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  69749. }).forEach(function (obj) {
  69750. obj.callback(_this, otherImpostor);
  69751. });
  69752. }
  69753. };
  69754. //sanity check!
  69755. if (!this.object) {
  69756. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  69757. return;
  69758. }
  69759. //legacy support for old syntax.
  69760. if (!this._scene && object.getScene) {
  69761. this._scene = object.getScene();
  69762. }
  69763. if (!this._scene) {
  69764. return;
  69765. }
  69766. this._physicsEngine = this._scene.getPhysicsEngine();
  69767. if (!this._physicsEngine) {
  69768. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  69769. }
  69770. else {
  69771. //set the object's quaternion, if not set
  69772. if (!this.object.rotationQuaternion) {
  69773. if (this.object.rotation) {
  69774. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  69775. }
  69776. else {
  69777. this.object.rotationQuaternion = new BABYLON.Quaternion();
  69778. }
  69779. }
  69780. //default options params
  69781. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  69782. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  69783. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  69784. this._joints = [];
  69785. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  69786. if (!this.object.parent || this._options.ignoreParent) {
  69787. this._init();
  69788. }
  69789. else if (this.object.parent.physicsImpostor) {
  69790. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  69791. }
  69792. }
  69793. }
  69794. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  69795. get: function () {
  69796. return this._isDisposed;
  69797. },
  69798. enumerable: true,
  69799. configurable: true
  69800. });
  69801. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  69802. get: function () {
  69803. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  69804. },
  69805. set: function (value) {
  69806. this.setMass(value);
  69807. },
  69808. enumerable: true,
  69809. configurable: true
  69810. });
  69811. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  69812. get: function () {
  69813. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  69814. },
  69815. set: function (value) {
  69816. if (!this._physicsEngine) {
  69817. return;
  69818. }
  69819. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  69820. },
  69821. enumerable: true,
  69822. configurable: true
  69823. });
  69824. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  69825. get: function () {
  69826. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  69827. },
  69828. set: function (value) {
  69829. if (!this._physicsEngine) {
  69830. return;
  69831. }
  69832. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  69833. },
  69834. enumerable: true,
  69835. configurable: true
  69836. });
  69837. /**
  69838. * This function will completly initialize this impostor.
  69839. * It will create a new body - but only if this mesh has no parent.
  69840. * If it has, this impostor will not be used other than to define the impostor
  69841. * of the child mesh.
  69842. */
  69843. PhysicsImpostor.prototype._init = function () {
  69844. if (!this._physicsEngine) {
  69845. return;
  69846. }
  69847. this._physicsEngine.removeImpostor(this);
  69848. this.physicsBody = null;
  69849. this._parent = this._parent || this._getPhysicsParent();
  69850. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  69851. this._physicsEngine.addImpostor(this);
  69852. }
  69853. };
  69854. PhysicsImpostor.prototype._getPhysicsParent = function () {
  69855. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  69856. var parentMesh = this.object.parent;
  69857. return parentMesh.physicsImpostor;
  69858. }
  69859. return null;
  69860. };
  69861. /**
  69862. * Should a new body be generated.
  69863. */
  69864. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  69865. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  69866. };
  69867. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  69868. this.forceUpdate();
  69869. };
  69870. /**
  69871. * Force a regeneration of this or the parent's impostor's body.
  69872. * Use under cautious - This will remove all joints already implemented.
  69873. */
  69874. PhysicsImpostor.prototype.forceUpdate = function () {
  69875. this._init();
  69876. if (this.parent && !this._options.ignoreParent) {
  69877. this.parent.forceUpdate();
  69878. }
  69879. };
  69880. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  69881. /*public get mesh(): AbstractMesh {
  69882. return this._mesh;
  69883. }*/
  69884. /**
  69885. * Gets the body that holds this impostor. Either its own, or its parent.
  69886. */
  69887. get: function () {
  69888. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  69889. },
  69890. /**
  69891. * Set the physics body. Used mainly by the physics engine/plugin
  69892. */
  69893. set: function (physicsBody) {
  69894. if (this._physicsBody && this._physicsEngine) {
  69895. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  69896. }
  69897. this._physicsBody = physicsBody;
  69898. this.resetUpdateFlags();
  69899. },
  69900. enumerable: true,
  69901. configurable: true
  69902. });
  69903. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  69904. get: function () {
  69905. return !this._options.ignoreParent && this._parent ? this._parent : null;
  69906. },
  69907. set: function (value) {
  69908. this._parent = value;
  69909. },
  69910. enumerable: true,
  69911. configurable: true
  69912. });
  69913. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  69914. this._bodyUpdateRequired = false;
  69915. };
  69916. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  69917. if (this.object.getBoundingInfo) {
  69918. var q = this.object.rotationQuaternion;
  69919. //reset rotation
  69920. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  69921. //calculate the world matrix with no rotation
  69922. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  69923. var boundingInfo = this.object.getBoundingInfo();
  69924. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  69925. //bring back the rotation
  69926. this.object.rotationQuaternion = q;
  69927. //calculate the world matrix with the new rotation
  69928. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  69929. return size;
  69930. }
  69931. else {
  69932. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  69933. }
  69934. };
  69935. PhysicsImpostor.prototype.getObjectCenter = function () {
  69936. if (this.object.getBoundingInfo) {
  69937. var boundingInfo = this.object.getBoundingInfo();
  69938. return boundingInfo.boundingBox.centerWorld;
  69939. }
  69940. else {
  69941. return this.object.position;
  69942. }
  69943. };
  69944. /**
  69945. * Get a specific parametes from the options parameter.
  69946. */
  69947. PhysicsImpostor.prototype.getParam = function (paramName) {
  69948. return this._options[paramName];
  69949. };
  69950. /**
  69951. * Sets a specific parameter in the options given to the physics plugin
  69952. */
  69953. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  69954. this._options[paramName] = value;
  69955. this._bodyUpdateRequired = true;
  69956. };
  69957. /**
  69958. * Specifically change the body's mass option. Won't recreate the physics body object
  69959. */
  69960. PhysicsImpostor.prototype.setMass = function (mass) {
  69961. if (this.getParam("mass") !== mass) {
  69962. this.setParam("mass", mass);
  69963. }
  69964. if (this._physicsEngine) {
  69965. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  69966. }
  69967. };
  69968. PhysicsImpostor.prototype.getLinearVelocity = function () {
  69969. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  69970. };
  69971. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  69972. if (this._physicsEngine) {
  69973. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  69974. }
  69975. };
  69976. PhysicsImpostor.prototype.getAngularVelocity = function () {
  69977. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  69978. };
  69979. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  69980. if (this._physicsEngine) {
  69981. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  69982. }
  69983. };
  69984. /**
  69985. * Execute a function with the physics plugin native code.
  69986. * Provide a function the will have two variables - the world object and the physics body object.
  69987. */
  69988. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  69989. if (this._physicsEngine) {
  69990. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  69991. }
  69992. };
  69993. /**
  69994. * Register a function that will be executed before the physics world is stepping forward.
  69995. */
  69996. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  69997. this._onBeforePhysicsStepCallbacks.push(func);
  69998. };
  69999. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  70000. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  70001. if (index > -1) {
  70002. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  70003. }
  70004. else {
  70005. BABYLON.Tools.Warn("Function to remove was not found");
  70006. }
  70007. };
  70008. /**
  70009. * Register a function that will be executed after the physics step
  70010. */
  70011. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  70012. this._onAfterPhysicsStepCallbacks.push(func);
  70013. };
  70014. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  70015. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  70016. if (index > -1) {
  70017. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  70018. }
  70019. else {
  70020. BABYLON.Tools.Warn("Function to remove was not found");
  70021. }
  70022. };
  70023. /**
  70024. * register a function that will be executed when this impostor collides against a different body.
  70025. */
  70026. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  70027. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70028. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  70029. };
  70030. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  70031. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70032. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  70033. if (index > -1) {
  70034. this._onPhysicsCollideCallbacks.splice(index, 1);
  70035. }
  70036. else {
  70037. BABYLON.Tools.Warn("Function to remove was not found");
  70038. }
  70039. };
  70040. PhysicsImpostor.prototype.getParentsRotation = function () {
  70041. var parent = this.object.parent;
  70042. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  70043. while (parent) {
  70044. if (parent.rotationQuaternion) {
  70045. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  70046. }
  70047. else {
  70048. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  70049. }
  70050. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  70051. parent = parent.parent;
  70052. }
  70053. return this._tmpQuat;
  70054. };
  70055. /**
  70056. * Apply a force
  70057. */
  70058. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  70059. if (this._physicsEngine) {
  70060. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  70061. }
  70062. return this;
  70063. };
  70064. /**
  70065. * Apply an impulse
  70066. */
  70067. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  70068. if (this._physicsEngine) {
  70069. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  70070. }
  70071. return this;
  70072. };
  70073. /**
  70074. * A help function to create a joint.
  70075. */
  70076. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  70077. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  70078. this.addJoint(otherImpostor, joint);
  70079. return this;
  70080. };
  70081. /**
  70082. * Add a joint to this impostor with a different impostor.
  70083. */
  70084. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  70085. this._joints.push({
  70086. otherImpostor: otherImpostor,
  70087. joint: joint
  70088. });
  70089. if (this._physicsEngine) {
  70090. this._physicsEngine.addJoint(this, otherImpostor, joint);
  70091. }
  70092. return this;
  70093. };
  70094. /**
  70095. * Will keep this body still, in a sleep mode.
  70096. */
  70097. PhysicsImpostor.prototype.sleep = function () {
  70098. if (this._physicsEngine) {
  70099. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  70100. }
  70101. return this;
  70102. };
  70103. /**
  70104. * Wake the body up.
  70105. */
  70106. PhysicsImpostor.prototype.wakeUp = function () {
  70107. if (this._physicsEngine) {
  70108. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  70109. }
  70110. return this;
  70111. };
  70112. PhysicsImpostor.prototype.clone = function (newObject) {
  70113. if (!newObject)
  70114. return null;
  70115. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  70116. };
  70117. PhysicsImpostor.prototype.dispose = function () {
  70118. var _this = this;
  70119. //no dispose if no physics engine is available.
  70120. if (!this._physicsEngine) {
  70121. return;
  70122. }
  70123. this._joints.forEach(function (j) {
  70124. if (_this._physicsEngine) {
  70125. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  70126. }
  70127. });
  70128. //dispose the physics body
  70129. this._physicsEngine.removeImpostor(this);
  70130. if (this.parent) {
  70131. this.parent.forceUpdate();
  70132. }
  70133. else {
  70134. /*this._object.getChildMeshes().forEach(function(mesh) {
  70135. if (mesh.physicsImpostor) {
  70136. if (disposeChildren) {
  70137. mesh.physicsImpostor.dispose();
  70138. mesh.physicsImpostor = null;
  70139. }
  70140. }
  70141. })*/
  70142. }
  70143. this._isDisposed = true;
  70144. };
  70145. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  70146. this._deltaPosition.copyFrom(position);
  70147. };
  70148. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  70149. if (!this._deltaRotation) {
  70150. this._deltaRotation = new BABYLON.Quaternion();
  70151. }
  70152. this._deltaRotation.copyFrom(rotation);
  70153. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  70154. };
  70155. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  70156. if (this._physicsEngine) {
  70157. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  70158. }
  70159. return this;
  70160. };
  70161. PhysicsImpostor.prototype.getRadius = function () {
  70162. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  70163. };
  70164. /**
  70165. * Sync a bone with this impostor
  70166. * @param bone The bone to sync to the impostor.
  70167. * @param boneMesh The mesh that the bone is influencing.
  70168. * @param jointPivot The pivot of the joint / bone in local space.
  70169. * @param distToJoint Optional distance from the impostor to the joint.
  70170. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70171. */
  70172. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  70173. var tempVec = PhysicsImpostor._tmpVecs[0];
  70174. var mesh = this.object;
  70175. if (mesh.rotationQuaternion) {
  70176. if (adjustRotation) {
  70177. var tempQuat = PhysicsImpostor._tmpQuat;
  70178. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  70179. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  70180. }
  70181. else {
  70182. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  70183. }
  70184. }
  70185. tempVec.x = 0;
  70186. tempVec.y = 0;
  70187. tempVec.z = 0;
  70188. if (jointPivot) {
  70189. tempVec.x = jointPivot.x;
  70190. tempVec.y = jointPivot.y;
  70191. tempVec.z = jointPivot.z;
  70192. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  70193. if (distToJoint === undefined || distToJoint === null) {
  70194. distToJoint = jointPivot.length();
  70195. }
  70196. tempVec.x *= distToJoint;
  70197. tempVec.y *= distToJoint;
  70198. tempVec.z *= distToJoint;
  70199. }
  70200. if (bone.getParent()) {
  70201. tempVec.addInPlace(mesh.getAbsolutePosition());
  70202. bone.setAbsolutePosition(tempVec, boneMesh);
  70203. }
  70204. else {
  70205. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  70206. boneMesh.position.x -= tempVec.x;
  70207. boneMesh.position.y -= tempVec.y;
  70208. boneMesh.position.z -= tempVec.z;
  70209. }
  70210. };
  70211. /**
  70212. * Sync impostor to a bone
  70213. * @param bone The bone that the impostor will be synced to.
  70214. * @param boneMesh The mesh that the bone is influencing.
  70215. * @param jointPivot The pivot of the joint / bone in local space.
  70216. * @param distToJoint Optional distance from the impostor to the joint.
  70217. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70218. * @param boneAxis Optional vector3 axis the bone is aligned with
  70219. */
  70220. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  70221. var mesh = this.object;
  70222. if (mesh.rotationQuaternion) {
  70223. if (adjustRotation) {
  70224. var tempQuat = PhysicsImpostor._tmpQuat;
  70225. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  70226. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  70227. }
  70228. else {
  70229. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  70230. }
  70231. }
  70232. var pos = PhysicsImpostor._tmpVecs[0];
  70233. var boneDir = PhysicsImpostor._tmpVecs[1];
  70234. if (!boneAxis) {
  70235. boneAxis = PhysicsImpostor._tmpVecs[2];
  70236. boneAxis.x = 0;
  70237. boneAxis.y = 1;
  70238. boneAxis.z = 0;
  70239. }
  70240. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  70241. bone.getAbsolutePositionToRef(boneMesh, pos);
  70242. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  70243. distToJoint = jointPivot.length();
  70244. }
  70245. if (distToJoint !== undefined && distToJoint !== null) {
  70246. pos.x += boneDir.x * distToJoint;
  70247. pos.y += boneDir.y * distToJoint;
  70248. pos.z += boneDir.z * distToJoint;
  70249. }
  70250. mesh.setAbsolutePosition(pos);
  70251. };
  70252. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  70253. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  70254. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70255. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  70256. //Impostor types
  70257. PhysicsImpostor.NoImpostor = 0;
  70258. PhysicsImpostor.SphereImpostor = 1;
  70259. PhysicsImpostor.BoxImpostor = 2;
  70260. PhysicsImpostor.PlaneImpostor = 3;
  70261. PhysicsImpostor.MeshImpostor = 4;
  70262. PhysicsImpostor.CylinderImpostor = 7;
  70263. PhysicsImpostor.ParticleImpostor = 8;
  70264. PhysicsImpostor.HeightmapImpostor = 9;
  70265. return PhysicsImpostor;
  70266. }());
  70267. BABYLON.PhysicsImpostor = PhysicsImpostor;
  70268. })(BABYLON || (BABYLON = {}));
  70269. //# sourceMappingURL=babylon.physicsImpostor.js.map
  70270. var BABYLON;
  70271. (function (BABYLON) {
  70272. var PhysicsEngine = /** @class */ (function () {
  70273. function PhysicsEngine(gravity, _physicsPlugin) {
  70274. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  70275. this._physicsPlugin = _physicsPlugin;
  70276. //new methods and parameters
  70277. this._impostors = [];
  70278. this._joints = [];
  70279. if (!this._physicsPlugin.isSupported()) {
  70280. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  70281. + "Please make sure it is included.");
  70282. }
  70283. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  70284. this.setGravity(gravity);
  70285. this.setTimeStep();
  70286. }
  70287. PhysicsEngine.prototype.setGravity = function (gravity) {
  70288. this.gravity = gravity;
  70289. this._physicsPlugin.setGravity(this.gravity);
  70290. };
  70291. /**
  70292. * Set the time step of the physics engine.
  70293. * default is 1/60.
  70294. * To slow it down, enter 1/600 for example.
  70295. * To speed it up, 1/30
  70296. * @param {number} newTimeStep the new timestep to apply to this world.
  70297. */
  70298. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  70299. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  70300. this._physicsPlugin.setTimeStep(newTimeStep);
  70301. };
  70302. /**
  70303. * Get the time step of the physics engine.
  70304. */
  70305. PhysicsEngine.prototype.getTimeStep = function () {
  70306. return this._physicsPlugin.getTimeStep();
  70307. };
  70308. PhysicsEngine.prototype.dispose = function () {
  70309. this._impostors.forEach(function (impostor) {
  70310. impostor.dispose();
  70311. });
  70312. this._physicsPlugin.dispose();
  70313. };
  70314. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  70315. return this._physicsPlugin.name;
  70316. };
  70317. /**
  70318. * Adding a new impostor for the impostor tracking.
  70319. * This will be done by the impostor itself.
  70320. * @param {PhysicsImpostor} impostor the impostor to add
  70321. */
  70322. PhysicsEngine.prototype.addImpostor = function (impostor) {
  70323. impostor.uniqueId = this._impostors.push(impostor);
  70324. //if no parent, generate the body
  70325. if (!impostor.parent) {
  70326. this._physicsPlugin.generatePhysicsBody(impostor);
  70327. }
  70328. };
  70329. /**
  70330. * Remove an impostor from the engine.
  70331. * This impostor and its mesh will not longer be updated by the physics engine.
  70332. * @param {PhysicsImpostor} impostor the impostor to remove
  70333. */
  70334. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  70335. var index = this._impostors.indexOf(impostor);
  70336. if (index > -1) {
  70337. var removed = this._impostors.splice(index, 1);
  70338. //Is it needed?
  70339. if (removed.length) {
  70340. //this will also remove it from the world.
  70341. removed[0].physicsBody = null;
  70342. }
  70343. }
  70344. };
  70345. /**
  70346. * Add a joint to the physics engine
  70347. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  70348. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  70349. * @param {PhysicsJoint} the joint that will connect both impostors.
  70350. */
  70351. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  70352. var impostorJoint = {
  70353. mainImpostor: mainImpostor,
  70354. connectedImpostor: connectedImpostor,
  70355. joint: joint
  70356. };
  70357. joint.physicsPlugin = this._physicsPlugin;
  70358. this._joints.push(impostorJoint);
  70359. this._physicsPlugin.generateJoint(impostorJoint);
  70360. };
  70361. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  70362. var matchingJoints = this._joints.filter(function (impostorJoint) {
  70363. return (impostorJoint.connectedImpostor === connectedImpostor
  70364. && impostorJoint.joint === joint
  70365. && impostorJoint.mainImpostor === mainImpostor);
  70366. });
  70367. if (matchingJoints.length) {
  70368. this._physicsPlugin.removeJoint(matchingJoints[0]);
  70369. //TODO remove it from the list as well
  70370. }
  70371. };
  70372. /**
  70373. * Called by the scene. no need to call it.
  70374. */
  70375. PhysicsEngine.prototype._step = function (delta) {
  70376. var _this = this;
  70377. //check if any mesh has no body / requires an update
  70378. this._impostors.forEach(function (impostor) {
  70379. if (impostor.isBodyInitRequired()) {
  70380. _this._physicsPlugin.generatePhysicsBody(impostor);
  70381. }
  70382. });
  70383. if (delta > 0.1) {
  70384. delta = 0.1;
  70385. }
  70386. else if (delta <= 0) {
  70387. delta = 1.0 / 60.0;
  70388. }
  70389. this._physicsPlugin.executeStep(delta, this._impostors);
  70390. };
  70391. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  70392. return this._physicsPlugin;
  70393. };
  70394. PhysicsEngine.prototype.getImpostors = function () {
  70395. return this._impostors;
  70396. };
  70397. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  70398. for (var i = 0; i < this._impostors.length; ++i) {
  70399. if (this._impostors[i].object === object) {
  70400. return this._impostors[i];
  70401. }
  70402. }
  70403. return null;
  70404. };
  70405. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  70406. for (var i = 0; i < this._impostors.length; ++i) {
  70407. if (this._impostors[i].physicsBody === body) {
  70408. return this._impostors[i];
  70409. }
  70410. }
  70411. return null;
  70412. };
  70413. // Statics
  70414. PhysicsEngine.Epsilon = 0.001;
  70415. return PhysicsEngine;
  70416. }());
  70417. BABYLON.PhysicsEngine = PhysicsEngine;
  70418. })(BABYLON || (BABYLON = {}));
  70419. //# sourceMappingURL=babylon.physicsEngine.js.map
  70420. var BABYLON;
  70421. (function (BABYLON) {
  70422. var PhysicsHelper = /** @class */ (function () {
  70423. function PhysicsHelper(scene) {
  70424. this._scene = scene;
  70425. this._physicsEngine = this._scene.getPhysicsEngine();
  70426. if (!this._physicsEngine) {
  70427. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  70428. }
  70429. }
  70430. /**
  70431. * @param {Vector3} origin the origin of the explosion
  70432. * @param {number} radius the explosion radius
  70433. * @param {number} strength the explosion strength
  70434. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70435. */
  70436. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  70437. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70438. if (!this._physicsEngine) {
  70439. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  70440. return null;
  70441. }
  70442. var impostors = this._physicsEngine.getImpostors();
  70443. if (impostors.length === 0) {
  70444. return null;
  70445. }
  70446. var event = new PhysicsRadialExplosionEvent(this._scene);
  70447. impostors.forEach(function (impostor) {
  70448. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70449. if (!impostorForceAndContactPoint) {
  70450. return;
  70451. }
  70452. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70453. });
  70454. event.dispose(false);
  70455. return event;
  70456. };
  70457. /**
  70458. * @param {Vector3} origin the origin of the explosion
  70459. * @param {number} radius the explosion radius
  70460. * @param {number} strength the explosion strength
  70461. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70462. */
  70463. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  70464. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70465. if (!this._physicsEngine) {
  70466. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70467. return null;
  70468. }
  70469. var impostors = this._physicsEngine.getImpostors();
  70470. if (impostors.length === 0) {
  70471. return null;
  70472. }
  70473. var event = new PhysicsRadialExplosionEvent(this._scene);
  70474. impostors.forEach(function (impostor) {
  70475. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70476. if (!impostorForceAndContactPoint) {
  70477. return;
  70478. }
  70479. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70480. });
  70481. event.dispose(false);
  70482. return event;
  70483. };
  70484. /**
  70485. * @param {Vector3} origin the origin of the explosion
  70486. * @param {number} radius the explosion radius
  70487. * @param {number} strength the explosion strength
  70488. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70489. */
  70490. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  70491. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70492. if (!this._physicsEngine) {
  70493. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70494. return null;
  70495. }
  70496. var impostors = this._physicsEngine.getImpostors();
  70497. if (impostors.length === 0) {
  70498. return null;
  70499. }
  70500. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  70501. event.dispose(false);
  70502. return event;
  70503. };
  70504. /**
  70505. * @param {Vector3} origin the origin of the updraft
  70506. * @param {number} radius the radius of the updraft
  70507. * @param {number} strength the strength of the updraft
  70508. * @param {number} height the height of the updraft
  70509. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  70510. */
  70511. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  70512. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  70513. if (!this._physicsEngine) {
  70514. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70515. return null;
  70516. }
  70517. if (this._physicsEngine.getImpostors().length === 0) {
  70518. return null;
  70519. }
  70520. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  70521. event.dispose(false);
  70522. return event;
  70523. };
  70524. /**
  70525. * @param {Vector3} origin the of the vortex
  70526. * @param {number} radius the radius of the vortex
  70527. * @param {number} strength the strength of the vortex
  70528. * @param {number} height the height of the vortex
  70529. */
  70530. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  70531. if (!this._physicsEngine) {
  70532. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70533. return null;
  70534. }
  70535. if (this._physicsEngine.getImpostors().length === 0) {
  70536. return null;
  70537. }
  70538. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  70539. event.dispose(false);
  70540. return event;
  70541. };
  70542. return PhysicsHelper;
  70543. }());
  70544. BABYLON.PhysicsHelper = PhysicsHelper;
  70545. /***** Radial explosion *****/
  70546. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  70547. function PhysicsRadialExplosionEvent(scene) {
  70548. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  70549. this._rays = [];
  70550. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  70551. this._scene = scene;
  70552. }
  70553. /**
  70554. * Returns the data related to the radial explosion event (sphere & rays).
  70555. * @returns {PhysicsRadialExplosionEventData}
  70556. */
  70557. PhysicsRadialExplosionEvent.prototype.getData = function () {
  70558. this._dataFetched = true;
  70559. return {
  70560. sphere: this._sphere,
  70561. rays: this._rays,
  70562. };
  70563. };
  70564. /**
  70565. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  70566. * @param impostor
  70567. * @param {Vector3} origin the origin of the explosion
  70568. * @param {number} radius the explosion radius
  70569. * @param {number} strength the explosion strength
  70570. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  70571. * @returns {Nullable<PhysicsForceAndContactPoint>}
  70572. */
  70573. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  70574. if (impostor.mass === 0) {
  70575. return null;
  70576. }
  70577. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  70578. return null;
  70579. }
  70580. if (impostor.object.getClassName() !== 'Mesh') {
  70581. return null;
  70582. }
  70583. var impostorObject = impostor.object;
  70584. var impostorObjectCenter = impostor.getObjectCenter();
  70585. var direction = impostorObjectCenter.subtract(origin);
  70586. var ray = new BABYLON.Ray(origin, direction, radius);
  70587. this._rays.push(ray);
  70588. var hit = ray.intersectsMesh(impostorObject);
  70589. var contactPoint = hit.pickedPoint;
  70590. if (!contactPoint) {
  70591. return null;
  70592. }
  70593. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  70594. if (distanceFromOrigin > radius) {
  70595. return null;
  70596. }
  70597. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  70598. ? strength
  70599. : strength * (1 - (distanceFromOrigin / radius));
  70600. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  70601. return { force: force, contactPoint: contactPoint };
  70602. };
  70603. /**
  70604. * Disposes the sphere.
  70605. * @param {bolean} force
  70606. */
  70607. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  70608. var _this = this;
  70609. if (force === void 0) { force = true; }
  70610. if (force) {
  70611. this._sphere.dispose();
  70612. }
  70613. else {
  70614. setTimeout(function () {
  70615. if (!_this._dataFetched) {
  70616. _this._sphere.dispose();
  70617. }
  70618. }, 0);
  70619. }
  70620. };
  70621. /*** Helpers ***/
  70622. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  70623. if (!this._sphere) {
  70624. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  70625. this._sphere.isVisible = false;
  70626. }
  70627. };
  70628. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  70629. var impostorObject = impostor.object;
  70630. this._prepareSphere();
  70631. this._sphere.position = origin;
  70632. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  70633. this._sphere._updateBoundingInfo();
  70634. this._sphere.computeWorldMatrix(true);
  70635. return this._sphere.intersectsMesh(impostorObject, true);
  70636. };
  70637. return PhysicsRadialExplosionEvent;
  70638. }());
  70639. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  70640. /***** Gravitational Field *****/
  70641. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  70642. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  70643. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70644. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70645. this._physicsHelper = physicsHelper;
  70646. this._scene = scene;
  70647. this._origin = origin;
  70648. this._radius = radius;
  70649. this._strength = strength;
  70650. this._falloff = falloff;
  70651. this._tickCallback = this._tick.bind(this);
  70652. }
  70653. /**
  70654. * Returns the data related to the gravitational field event (sphere).
  70655. * @returns {PhysicsGravitationalFieldEventData}
  70656. */
  70657. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  70658. this._dataFetched = true;
  70659. return {
  70660. sphere: this._sphere,
  70661. };
  70662. };
  70663. /**
  70664. * Enables the gravitational field.
  70665. */
  70666. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  70667. this._tickCallback.call(this);
  70668. this._scene.registerBeforeRender(this._tickCallback);
  70669. };
  70670. /**
  70671. * Disables the gravitational field.
  70672. */
  70673. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  70674. this._scene.unregisterBeforeRender(this._tickCallback);
  70675. };
  70676. /**
  70677. * Disposes the sphere.
  70678. * @param {bolean} force
  70679. */
  70680. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  70681. var _this = this;
  70682. if (force === void 0) { force = true; }
  70683. if (force) {
  70684. this._sphere.dispose();
  70685. }
  70686. else {
  70687. setTimeout(function () {
  70688. if (!_this._dataFetched) {
  70689. _this._sphere.dispose();
  70690. }
  70691. }, 0);
  70692. }
  70693. };
  70694. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  70695. // Since the params won't change, we fetch the event only once
  70696. if (this._sphere) {
  70697. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  70698. }
  70699. else {
  70700. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  70701. if (radialExplosionEvent) {
  70702. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  70703. }
  70704. }
  70705. };
  70706. return PhysicsGravitationalFieldEvent;
  70707. }());
  70708. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  70709. /***** Updraft *****/
  70710. var PhysicsUpdraftEvent = /** @class */ (function () {
  70711. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  70712. this._scene = _scene;
  70713. this._origin = _origin;
  70714. this._radius = _radius;
  70715. this._strength = _strength;
  70716. this._height = _height;
  70717. this._updraftMode = _updraftMode;
  70718. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  70719. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  70720. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  70721. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70722. this._physicsEngine = this._scene.getPhysicsEngine();
  70723. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  70724. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  70725. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  70726. this._originDirection = this._origin.subtract(this._originTop).normalize();
  70727. }
  70728. this._tickCallback = this._tick.bind(this);
  70729. }
  70730. /**
  70731. * Returns the data related to the updraft event (cylinder).
  70732. * @returns {PhysicsUpdraftEventData}
  70733. */
  70734. PhysicsUpdraftEvent.prototype.getData = function () {
  70735. this._dataFetched = true;
  70736. return {
  70737. cylinder: this._cylinder,
  70738. };
  70739. };
  70740. /**
  70741. * Enables the updraft.
  70742. */
  70743. PhysicsUpdraftEvent.prototype.enable = function () {
  70744. this._tickCallback.call(this);
  70745. this._scene.registerBeforeRender(this._tickCallback);
  70746. };
  70747. /**
  70748. * Disables the cortex.
  70749. */
  70750. PhysicsUpdraftEvent.prototype.disable = function () {
  70751. this._scene.unregisterBeforeRender(this._tickCallback);
  70752. };
  70753. /**
  70754. * Disposes the sphere.
  70755. * @param {bolean} force
  70756. */
  70757. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  70758. var _this = this;
  70759. if (force === void 0) { force = true; }
  70760. if (force) {
  70761. this._cylinder.dispose();
  70762. }
  70763. else {
  70764. setTimeout(function () {
  70765. if (!_this._dataFetched) {
  70766. _this._cylinder.dispose();
  70767. }
  70768. }, 0);
  70769. }
  70770. };
  70771. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  70772. if (impostor.mass === 0) {
  70773. return null;
  70774. }
  70775. if (!this._intersectsWithCylinder(impostor)) {
  70776. return null;
  70777. }
  70778. var impostorObjectCenter = impostor.getObjectCenter();
  70779. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  70780. var direction = this._originDirection;
  70781. }
  70782. else {
  70783. var direction = impostorObjectCenter.subtract(this._originTop);
  70784. }
  70785. var multiplier = this._strength * -1;
  70786. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  70787. return { force: force, contactPoint: impostorObjectCenter };
  70788. };
  70789. PhysicsUpdraftEvent.prototype._tick = function () {
  70790. var _this = this;
  70791. this._physicsEngine.getImpostors().forEach(function (impostor) {
  70792. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  70793. if (!impostorForceAndContactPoint) {
  70794. return;
  70795. }
  70796. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70797. });
  70798. };
  70799. /*** Helpers ***/
  70800. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  70801. if (!this._cylinder) {
  70802. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  70803. height: this._height,
  70804. diameter: this._radius * 2,
  70805. }, this._scene);
  70806. this._cylinder.isVisible = false;
  70807. }
  70808. };
  70809. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  70810. var impostorObject = impostor.object;
  70811. this._prepareCylinder();
  70812. this._cylinder.position = this._cylinderPosition;
  70813. return this._cylinder.intersectsMesh(impostorObject, true);
  70814. };
  70815. return PhysicsUpdraftEvent;
  70816. }());
  70817. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  70818. /***** Vortex *****/
  70819. var PhysicsVortexEvent = /** @class */ (function () {
  70820. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  70821. this._scene = _scene;
  70822. this._origin = _origin;
  70823. this._radius = _radius;
  70824. this._strength = _strength;
  70825. this._height = _height;
  70826. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  70827. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  70828. this._updraftMultiplier = 0.02;
  70829. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  70830. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70831. this._physicsEngine = this._scene.getPhysicsEngine();
  70832. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  70833. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  70834. this._tickCallback = this._tick.bind(this);
  70835. }
  70836. /**
  70837. * Returns the data related to the vortex event (cylinder).
  70838. * @returns {PhysicsVortexEventData}
  70839. */
  70840. PhysicsVortexEvent.prototype.getData = function () {
  70841. this._dataFetched = true;
  70842. return {
  70843. cylinder: this._cylinder,
  70844. };
  70845. };
  70846. /**
  70847. * Enables the vortex.
  70848. */
  70849. PhysicsVortexEvent.prototype.enable = function () {
  70850. this._tickCallback.call(this);
  70851. this._scene.registerBeforeRender(this._tickCallback);
  70852. };
  70853. /**
  70854. * Disables the cortex.
  70855. */
  70856. PhysicsVortexEvent.prototype.disable = function () {
  70857. this._scene.unregisterBeforeRender(this._tickCallback);
  70858. };
  70859. /**
  70860. * Disposes the sphere.
  70861. * @param {bolean} force
  70862. */
  70863. PhysicsVortexEvent.prototype.dispose = function (force) {
  70864. var _this = this;
  70865. if (force === void 0) { force = true; }
  70866. if (force) {
  70867. this._cylinder.dispose();
  70868. }
  70869. else {
  70870. setTimeout(function () {
  70871. if (!_this._dataFetched) {
  70872. _this._cylinder.dispose();
  70873. }
  70874. }, 0);
  70875. }
  70876. };
  70877. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  70878. if (impostor.mass === 0) {
  70879. return null;
  70880. }
  70881. if (!this._intersectsWithCylinder(impostor)) {
  70882. return null;
  70883. }
  70884. if (impostor.object.getClassName() !== 'Mesh') {
  70885. return null;
  70886. }
  70887. var impostorObject = impostor.object;
  70888. var impostorObjectCenter = impostor.getObjectCenter();
  70889. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  70890. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  70891. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  70892. var hit = ray.intersectsMesh(impostorObject);
  70893. var contactPoint = hit.pickedPoint;
  70894. if (!contactPoint) {
  70895. return null;
  70896. }
  70897. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  70898. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  70899. var directionToOrigin = contactPoint.normalize();
  70900. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  70901. directionToOrigin = directionToOrigin.negate();
  70902. }
  70903. // TODO: find a more physically based solution
  70904. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  70905. var forceX = directionToOrigin.x * this._strength / 8;
  70906. var forceY = directionToOrigin.y * this._updraftMultiplier;
  70907. var forceZ = directionToOrigin.z * this._strength / 8;
  70908. }
  70909. else {
  70910. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  70911. var forceY = this._originTop.y * this._updraftMultiplier;
  70912. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  70913. }
  70914. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  70915. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  70916. return { force: force, contactPoint: impostorObjectCenter };
  70917. };
  70918. PhysicsVortexEvent.prototype._tick = function () {
  70919. var _this = this;
  70920. this._physicsEngine.getImpostors().forEach(function (impostor) {
  70921. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  70922. if (!impostorForceAndContactPoint) {
  70923. return;
  70924. }
  70925. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70926. });
  70927. };
  70928. /*** Helpers ***/
  70929. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  70930. if (!this._cylinder) {
  70931. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  70932. height: this._height,
  70933. diameter: this._radius * 2,
  70934. }, this._scene);
  70935. this._cylinder.isVisible = false;
  70936. }
  70937. };
  70938. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  70939. var impostorObject = impostor.object;
  70940. this._prepareCylinder();
  70941. this._cylinder.position = this._cylinderPosition;
  70942. return this._cylinder.intersectsMesh(impostorObject, true);
  70943. };
  70944. return PhysicsVortexEvent;
  70945. }());
  70946. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  70947. /***** Enums *****/
  70948. /**
  70949. * The strenght of the force in correspondence to the distance of the affected object
  70950. */
  70951. var PhysicsRadialImpulseFalloff;
  70952. (function (PhysicsRadialImpulseFalloff) {
  70953. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  70954. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  70955. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  70956. /**
  70957. * The strenght of the force in correspondence to the distance of the affected object
  70958. */
  70959. var PhysicsUpdraftMode;
  70960. (function (PhysicsUpdraftMode) {
  70961. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  70962. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  70963. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  70964. })(BABYLON || (BABYLON = {}));
  70965. //# sourceMappingURL=babylon.physicsHelper.js.map
  70966. var BABYLON;
  70967. (function (BABYLON) {
  70968. var CannonJSPlugin = /** @class */ (function () {
  70969. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  70970. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  70971. if (iterations === void 0) { iterations = 10; }
  70972. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  70973. this.name = "CannonJSPlugin";
  70974. this._physicsMaterials = new Array();
  70975. this._fixedTimeStep = 1 / 60;
  70976. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  70977. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  70978. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  70979. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  70980. this._tmpPosition = BABYLON.Vector3.Zero();
  70981. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  70982. this._tmpUnityRotation = new BABYLON.Quaternion();
  70983. if (!this.isSupported()) {
  70984. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  70985. return;
  70986. }
  70987. this._extendNamespace();
  70988. this.world = new this.BJSCANNON.World();
  70989. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  70990. this.world.solver.iterations = iterations;
  70991. }
  70992. CannonJSPlugin.prototype.setGravity = function (gravity) {
  70993. this.world.gravity.copy(gravity);
  70994. };
  70995. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  70996. this._fixedTimeStep = timeStep;
  70997. };
  70998. CannonJSPlugin.prototype.getTimeStep = function () {
  70999. return this._fixedTimeStep;
  71000. };
  71001. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  71002. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  71003. };
  71004. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71005. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71006. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71007. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  71008. };
  71009. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71010. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71011. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71012. impostor.physicsBody.applyForce(impulse, worldPoint);
  71013. };
  71014. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71015. //parent-child relationship. Does this impostor has a parent impostor?
  71016. if (impostor.parent) {
  71017. if (impostor.physicsBody) {
  71018. this.removePhysicsBody(impostor);
  71019. //TODO is that needed?
  71020. impostor.forceUpdate();
  71021. }
  71022. return;
  71023. }
  71024. //should a new body be created for this impostor?
  71025. if (impostor.isBodyInitRequired()) {
  71026. var shape = this._createShape(impostor);
  71027. //unregister events, if body is being changed
  71028. var oldBody = impostor.physicsBody;
  71029. if (oldBody) {
  71030. this.removePhysicsBody(impostor);
  71031. }
  71032. //create the body and material
  71033. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  71034. var bodyCreationObject = {
  71035. mass: impostor.getParam("mass"),
  71036. material: material
  71037. };
  71038. // A simple extend, in case native options were used.
  71039. var nativeOptions = impostor.getParam("nativeOptions");
  71040. for (var key in nativeOptions) {
  71041. if (nativeOptions.hasOwnProperty(key)) {
  71042. bodyCreationObject[key] = nativeOptions[key];
  71043. }
  71044. }
  71045. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  71046. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  71047. this.world.addEventListener("preStep", impostor.beforeStep);
  71048. this.world.addEventListener("postStep", impostor.afterStep);
  71049. impostor.physicsBody.addShape(shape);
  71050. this.world.add(impostor.physicsBody);
  71051. //try to keep the body moving in the right direction by taking old properties.
  71052. //Should be tested!
  71053. if (oldBody) {
  71054. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  71055. impostor.physicsBody[param].copy(oldBody[param]);
  71056. });
  71057. }
  71058. this._processChildMeshes(impostor);
  71059. }
  71060. //now update the body's transformation
  71061. this._updatePhysicsBodyTransformation(impostor);
  71062. };
  71063. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  71064. var _this = this;
  71065. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  71066. var currentRotation = mainImpostor.object.rotationQuaternion;
  71067. if (meshChildren.length) {
  71068. var processMesh = function (localPosition, mesh) {
  71069. if (!currentRotation || !mesh.rotationQuaternion) {
  71070. return;
  71071. }
  71072. var childImpostor = mesh.getPhysicsImpostor();
  71073. if (childImpostor) {
  71074. var parent = childImpostor.parent;
  71075. if (parent !== mainImpostor) {
  71076. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  71077. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  71078. if (childImpostor.physicsBody) {
  71079. _this.removePhysicsBody(childImpostor);
  71080. childImpostor.physicsBody = null;
  71081. }
  71082. childImpostor.parent = mainImpostor;
  71083. childImpostor.resetUpdateFlags();
  71084. 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));
  71085. //Add the mass of the children.
  71086. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  71087. }
  71088. }
  71089. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  71090. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  71091. };
  71092. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  71093. }
  71094. };
  71095. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  71096. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  71097. this.world.removeEventListener("preStep", impostor.beforeStep);
  71098. this.world.removeEventListener("postStep", impostor.afterStep);
  71099. this.world.remove(impostor.physicsBody);
  71100. };
  71101. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  71102. var mainBody = impostorJoint.mainImpostor.physicsBody;
  71103. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  71104. if (!mainBody || !connectedBody) {
  71105. return;
  71106. }
  71107. var constraint;
  71108. var jointData = impostorJoint.joint.jointData;
  71109. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  71110. var constraintData = {
  71111. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  71112. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  71113. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  71114. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  71115. maxForce: jointData.nativeParams.maxForce,
  71116. collideConnected: !!jointData.collision
  71117. };
  71118. switch (impostorJoint.joint.type) {
  71119. case BABYLON.PhysicsJoint.HingeJoint:
  71120. case BABYLON.PhysicsJoint.Hinge2Joint:
  71121. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  71122. break;
  71123. case BABYLON.PhysicsJoint.DistanceJoint:
  71124. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  71125. break;
  71126. case BABYLON.PhysicsJoint.SpringJoint:
  71127. var springData = jointData;
  71128. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  71129. restLength: springData.length,
  71130. stiffness: springData.stiffness,
  71131. damping: springData.damping,
  71132. localAnchorA: constraintData.pivotA,
  71133. localAnchorB: constraintData.pivotB
  71134. });
  71135. break;
  71136. case BABYLON.PhysicsJoint.LockJoint:
  71137. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  71138. break;
  71139. case BABYLON.PhysicsJoint.PointToPointJoint:
  71140. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71141. default:
  71142. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  71143. break;
  71144. }
  71145. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  71146. constraint.collideConnected = !!jointData.collision;
  71147. impostorJoint.joint.physicsJoint = constraint;
  71148. //don't add spring as constraint, as it is not one.
  71149. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  71150. this.world.addConstraint(constraint);
  71151. }
  71152. else {
  71153. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  71154. constraint.applyForce();
  71155. });
  71156. }
  71157. };
  71158. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71159. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  71160. };
  71161. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  71162. var index;
  71163. var mat;
  71164. for (index = 0; index < this._physicsMaterials.length; index++) {
  71165. mat = this._physicsMaterials[index];
  71166. if (mat.friction === friction && mat.restitution === restitution) {
  71167. return mat;
  71168. }
  71169. }
  71170. var currentMat = new this.BJSCANNON.Material(name);
  71171. currentMat.friction = friction;
  71172. currentMat.restitution = restitution;
  71173. this._physicsMaterials.push(currentMat);
  71174. return currentMat;
  71175. };
  71176. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  71177. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  71178. };
  71179. CannonJSPlugin.prototype._createShape = function (impostor) {
  71180. var object = impostor.object;
  71181. var returnValue;
  71182. var extendSize = impostor.getObjectExtendSize();
  71183. switch (impostor.type) {
  71184. case BABYLON.PhysicsImpostor.SphereImpostor:
  71185. var radiusX = extendSize.x;
  71186. var radiusY = extendSize.y;
  71187. var radiusZ = extendSize.z;
  71188. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  71189. break;
  71190. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  71191. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71192. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  71193. break;
  71194. case BABYLON.PhysicsImpostor.BoxImpostor:
  71195. var box = extendSize.scale(0.5);
  71196. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  71197. break;
  71198. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71199. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  71200. returnValue = new this.BJSCANNON.Plane();
  71201. break;
  71202. case BABYLON.PhysicsImpostor.MeshImpostor:
  71203. // should transform the vertex data to world coordinates!!
  71204. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  71205. var rawFaces = object.getIndices ? object.getIndices() : [];
  71206. if (!rawVerts)
  71207. return;
  71208. // get only scale! so the object could transform correctly.
  71209. var oldPosition = object.position.clone();
  71210. var oldRotation = object.rotation && object.rotation.clone();
  71211. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  71212. object.position.copyFromFloats(0, 0, 0);
  71213. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71214. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71215. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71216. var transform = object.computeWorldMatrix(true);
  71217. // convert rawVerts to object space
  71218. var temp = new Array();
  71219. var index;
  71220. for (index = 0; index < rawVerts.length; index += 3) {
  71221. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  71222. }
  71223. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  71224. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  71225. //now set back the transformation!
  71226. object.position.copyFrom(oldPosition);
  71227. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  71228. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  71229. break;
  71230. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  71231. var oldPosition2 = object.position.clone();
  71232. var oldRotation2 = object.rotation && object.rotation.clone();
  71233. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  71234. object.position.copyFromFloats(0, 0, 0);
  71235. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71236. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71237. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71238. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  71239. returnValue = this._createHeightmap(object);
  71240. object.position.copyFrom(oldPosition2);
  71241. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  71242. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  71243. object.computeWorldMatrix(true);
  71244. break;
  71245. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71246. returnValue = new this.BJSCANNON.Particle();
  71247. break;
  71248. }
  71249. return returnValue;
  71250. };
  71251. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  71252. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71253. var transform = object.computeWorldMatrix(true);
  71254. // convert rawVerts to object space
  71255. var temp = new Array();
  71256. var index;
  71257. for (index = 0; index < pos.length; index += 3) {
  71258. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  71259. }
  71260. pos = temp;
  71261. var matrix = new Array();
  71262. //For now pointDepth will not be used and will be automatically calculated.
  71263. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  71264. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  71265. var boundingInfo = object.getBoundingInfo();
  71266. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  71267. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  71268. var elementSize = dim * 2 / arraySize;
  71269. for (var i = 0; i < pos.length; i = i + 3) {
  71270. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  71271. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  71272. var y = -pos[i + 2] + minY;
  71273. if (!matrix[x]) {
  71274. matrix[x] = [];
  71275. }
  71276. if (!matrix[x][z]) {
  71277. matrix[x][z] = y;
  71278. }
  71279. matrix[x][z] = Math.max(y, matrix[x][z]);
  71280. }
  71281. for (var x = 0; x <= arraySize; ++x) {
  71282. if (!matrix[x]) {
  71283. var loc = 1;
  71284. while (!matrix[(x + loc) % arraySize]) {
  71285. loc++;
  71286. }
  71287. matrix[x] = matrix[(x + loc) % arraySize].slice();
  71288. //console.log("missing x", x);
  71289. }
  71290. for (var z = 0; z <= arraySize; ++z) {
  71291. if (!matrix[x][z]) {
  71292. var loc = 1;
  71293. var newValue;
  71294. while (newValue === undefined) {
  71295. newValue = matrix[x][(z + loc++) % arraySize];
  71296. }
  71297. matrix[x][z] = newValue;
  71298. }
  71299. }
  71300. }
  71301. var shape = new this.BJSCANNON.Heightfield(matrix, {
  71302. elementSize: elementSize
  71303. });
  71304. //For future reference, needed for body transformation
  71305. shape.minY = minY;
  71306. return shape;
  71307. };
  71308. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  71309. var object = impostor.object;
  71310. //make sure it is updated...
  71311. object.computeWorldMatrix && object.computeWorldMatrix(true);
  71312. // The delta between the mesh position and the mesh bounding box center
  71313. var bInfo = object.getBoundingInfo();
  71314. if (!bInfo)
  71315. return;
  71316. var center = impostor.getObjectCenter();
  71317. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  71318. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  71319. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  71320. this._tmpPosition.copyFrom(center);
  71321. var quaternion = object.rotationQuaternion;
  71322. if (!quaternion) {
  71323. return;
  71324. }
  71325. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  71326. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  71327. //-90 DEG in X, precalculated
  71328. quaternion = quaternion.multiply(this._minus90X);
  71329. //Invert! (Precalculated, 90 deg in X)
  71330. //No need to clone. this will never change.
  71331. impostor.setDeltaRotation(this._plus90X);
  71332. }
  71333. //If it is a heightfield, if should be centered.
  71334. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  71335. var mesh = object;
  71336. var boundingInfo = mesh.getBoundingInfo();
  71337. //calculate the correct body position:
  71338. var rotationQuaternion = mesh.rotationQuaternion;
  71339. mesh.rotationQuaternion = this._tmpUnityRotation;
  71340. mesh.computeWorldMatrix(true);
  71341. //get original center with no rotation
  71342. var c = center.clone();
  71343. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  71344. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  71345. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  71346. mesh.setPivotMatrix(p);
  71347. mesh.computeWorldMatrix(true);
  71348. //calculate the translation
  71349. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  71350. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  71351. //add it inverted to the delta
  71352. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  71353. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  71354. //rotation is back
  71355. mesh.rotationQuaternion = rotationQuaternion;
  71356. mesh.setPivotMatrix(oldPivot);
  71357. mesh.computeWorldMatrix(true);
  71358. }
  71359. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  71360. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  71361. //this._tmpPosition.copyFrom(object.position);
  71362. }
  71363. impostor.setDeltaPosition(this._tmpDeltaPosition);
  71364. //Now update the impostor object
  71365. impostor.physicsBody.position.copy(this._tmpPosition);
  71366. impostor.physicsBody.quaternion.copy(quaternion);
  71367. };
  71368. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71369. impostor.object.position.copyFrom(impostor.physicsBody.position);
  71370. if (impostor.object.rotationQuaternion) {
  71371. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  71372. }
  71373. };
  71374. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71375. impostor.physicsBody.position.copy(newPosition);
  71376. impostor.physicsBody.quaternion.copy(newRotation);
  71377. };
  71378. CannonJSPlugin.prototype.isSupported = function () {
  71379. return this.BJSCANNON !== undefined;
  71380. };
  71381. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71382. impostor.physicsBody.velocity.copy(velocity);
  71383. };
  71384. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71385. impostor.physicsBody.angularVelocity.copy(velocity);
  71386. };
  71387. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71388. var v = impostor.physicsBody.velocity;
  71389. if (!v) {
  71390. return null;
  71391. }
  71392. return new BABYLON.Vector3(v.x, v.y, v.z);
  71393. };
  71394. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71395. var v = impostor.physicsBody.angularVelocity;
  71396. if (!v) {
  71397. return null;
  71398. }
  71399. return new BABYLON.Vector3(v.x, v.y, v.z);
  71400. };
  71401. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71402. impostor.physicsBody.mass = mass;
  71403. impostor.physicsBody.updateMassProperties();
  71404. };
  71405. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  71406. return impostor.physicsBody.mass;
  71407. };
  71408. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  71409. return impostor.physicsBody.material.friction;
  71410. };
  71411. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71412. impostor.physicsBody.material.friction = friction;
  71413. };
  71414. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71415. return impostor.physicsBody.material.restitution;
  71416. };
  71417. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71418. impostor.physicsBody.material.restitution = restitution;
  71419. };
  71420. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  71421. impostor.physicsBody.sleep();
  71422. };
  71423. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  71424. impostor.physicsBody.wakeUp();
  71425. };
  71426. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71427. joint.physicsJoint.distance = maxDistance;
  71428. };
  71429. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71430. // if (!motorIndex) {
  71431. // joint.physicsJoint.enableMotor();
  71432. // }
  71433. // }
  71434. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71435. // if (!motorIndex) {
  71436. // joint.physicsJoint.disableMotor();
  71437. // }
  71438. // }
  71439. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71440. if (!motorIndex) {
  71441. joint.physicsJoint.enableMotor();
  71442. joint.physicsJoint.setMotorSpeed(speed);
  71443. if (maxForce) {
  71444. this.setLimit(joint, maxForce);
  71445. }
  71446. }
  71447. };
  71448. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  71449. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  71450. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  71451. };
  71452. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71453. var body = impostor.physicsBody;
  71454. mesh.position.x = body.position.x;
  71455. mesh.position.y = body.position.y;
  71456. mesh.position.z = body.position.z;
  71457. if (mesh.rotationQuaternion) {
  71458. mesh.rotationQuaternion.x = body.quaternion.x;
  71459. mesh.rotationQuaternion.y = body.quaternion.y;
  71460. mesh.rotationQuaternion.z = body.quaternion.z;
  71461. mesh.rotationQuaternion.w = body.quaternion.w;
  71462. }
  71463. };
  71464. CannonJSPlugin.prototype.getRadius = function (impostor) {
  71465. var shape = impostor.physicsBody.shapes[0];
  71466. return shape.boundingSphereRadius;
  71467. };
  71468. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71469. var shape = impostor.physicsBody.shapes[0];
  71470. result.x = shape.halfExtents.x * 2;
  71471. result.y = shape.halfExtents.y * 2;
  71472. result.z = shape.halfExtents.z * 2;
  71473. };
  71474. CannonJSPlugin.prototype.dispose = function () {
  71475. };
  71476. CannonJSPlugin.prototype._extendNamespace = function () {
  71477. //this will force cannon to execute at least one step when using interpolation
  71478. var step_tmp1 = new this.BJSCANNON.Vec3();
  71479. var Engine = this.BJSCANNON;
  71480. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  71481. maxSubSteps = maxSubSteps || 10;
  71482. timeSinceLastCalled = timeSinceLastCalled || 0;
  71483. if (timeSinceLastCalled === 0) {
  71484. this.internalStep(dt);
  71485. this.time += dt;
  71486. }
  71487. else {
  71488. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  71489. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  71490. var t0 = performance.now();
  71491. for (var i = 0; i !== internalSteps; i++) {
  71492. this.internalStep(dt);
  71493. if (performance.now() - t0 > dt * 1000) {
  71494. break;
  71495. }
  71496. }
  71497. this.time += timeSinceLastCalled;
  71498. var h = this.time % dt;
  71499. var h_div_dt = h / dt;
  71500. var interpvelo = step_tmp1;
  71501. var bodies = this.bodies;
  71502. for (var j = 0; j !== bodies.length; j++) {
  71503. var b = bodies[j];
  71504. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  71505. b.position.vsub(b.previousPosition, interpvelo);
  71506. interpvelo.scale(h_div_dt, interpvelo);
  71507. b.position.vadd(interpvelo, b.interpolatedPosition);
  71508. }
  71509. else {
  71510. b.interpolatedPosition.copy(b.position);
  71511. b.interpolatedQuaternion.copy(b.quaternion);
  71512. }
  71513. }
  71514. }
  71515. };
  71516. };
  71517. return CannonJSPlugin;
  71518. }());
  71519. BABYLON.CannonJSPlugin = CannonJSPlugin;
  71520. })(BABYLON || (BABYLON = {}));
  71521. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  71522. var BABYLON;
  71523. (function (BABYLON) {
  71524. var OimoJSPlugin = /** @class */ (function () {
  71525. function OimoJSPlugin(iterations) {
  71526. this.name = "OimoJSPlugin";
  71527. this._tmpImpostorsArray = [];
  71528. this._tmpPositionVector = BABYLON.Vector3.Zero();
  71529. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  71530. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  71531. this.world.worldscale(1);
  71532. this.world.clear();
  71533. //making sure no stats are calculated
  71534. this.world.isNoStat = true;
  71535. }
  71536. OimoJSPlugin.prototype.setGravity = function (gravity) {
  71537. this.world.gravity.copy(gravity);
  71538. };
  71539. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  71540. this.world.timeStep = timeStep;
  71541. };
  71542. OimoJSPlugin.prototype.getTimeStep = function () {
  71543. return this.world.timeStep;
  71544. };
  71545. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  71546. var _this = this;
  71547. impostors.forEach(function (impostor) {
  71548. impostor.beforeStep();
  71549. });
  71550. this.world.step();
  71551. impostors.forEach(function (impostor) {
  71552. impostor.afterStep();
  71553. //update the ordered impostors array
  71554. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  71555. });
  71556. //check for collisions
  71557. var contact = this.world.contacts;
  71558. while (contact !== null) {
  71559. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  71560. contact = contact.next;
  71561. continue;
  71562. }
  71563. //is this body colliding with any other? get the impostor
  71564. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  71565. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  71566. if (!mainImpostor || !collidingImpostor) {
  71567. contact = contact.next;
  71568. continue;
  71569. }
  71570. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  71571. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  71572. contact = contact.next;
  71573. }
  71574. };
  71575. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71576. var mass = impostor.physicsBody.massInfo.mass;
  71577. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  71578. };
  71579. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71580. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  71581. this.applyImpulse(impostor, force, contactPoint);
  71582. };
  71583. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71584. var _this = this;
  71585. //parent-child relationship. Does this impostor has a parent impostor?
  71586. if (impostor.parent) {
  71587. if (impostor.physicsBody) {
  71588. this.removePhysicsBody(impostor);
  71589. //TODO is that needed?
  71590. impostor.forceUpdate();
  71591. }
  71592. return;
  71593. }
  71594. if (impostor.isBodyInitRequired()) {
  71595. var bodyConfig = {
  71596. name: impostor.uniqueId,
  71597. //Oimo must have mass, also for static objects.
  71598. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  71599. size: [],
  71600. type: [],
  71601. pos: [],
  71602. rot: [],
  71603. move: impostor.getParam("mass") !== 0,
  71604. //Supporting older versions of Oimo
  71605. world: this.world
  71606. };
  71607. var impostors = [impostor];
  71608. var addToArray = function (parent) {
  71609. if (!parent.getChildMeshes)
  71610. return;
  71611. parent.getChildMeshes().forEach(function (m) {
  71612. if (m.physicsImpostor) {
  71613. impostors.push(m.physicsImpostor);
  71614. //m.physicsImpostor._init();
  71615. }
  71616. });
  71617. };
  71618. addToArray(impostor.object);
  71619. var checkWithEpsilon_1 = function (value) {
  71620. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  71621. };
  71622. impostors.forEach(function (i) {
  71623. if (!impostor.object.rotationQuaternion) {
  71624. return;
  71625. }
  71626. //get the correct bounding box
  71627. var oldQuaternion = i.object.rotationQuaternion;
  71628. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  71629. x: impostor.object.rotationQuaternion.x,
  71630. y: impostor.object.rotationQuaternion.y,
  71631. z: impostor.object.rotationQuaternion.z,
  71632. s: impostor.object.rotationQuaternion.w
  71633. });
  71634. var extendSize = i.getObjectExtendSize();
  71635. if (i === impostor) {
  71636. var center = impostor.getObjectCenter();
  71637. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  71638. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  71639. //Can also use Array.prototype.push.apply
  71640. bodyConfig.pos.push(center.x);
  71641. bodyConfig.pos.push(center.y);
  71642. bodyConfig.pos.push(center.z);
  71643. //tmp solution
  71644. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71645. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71646. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71647. }
  71648. else {
  71649. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  71650. bodyConfig.pos.push(localPosition.x);
  71651. bodyConfig.pos.push(localPosition.y);
  71652. bodyConfig.pos.push(localPosition.z);
  71653. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  71654. bodyConfig.rot.push(0);
  71655. bodyConfig.rot.push(0);
  71656. bodyConfig.rot.push(0);
  71657. }
  71658. // register mesh
  71659. switch (i.type) {
  71660. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71661. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  71662. case BABYLON.PhysicsImpostor.SphereImpostor:
  71663. var radiusX = extendSize.x;
  71664. var radiusY = extendSize.y;
  71665. var radiusZ = extendSize.z;
  71666. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  71667. bodyConfig.type.push('sphere');
  71668. //due to the way oimo works with compounds, add 3 times
  71669. bodyConfig.size.push(size);
  71670. bodyConfig.size.push(size);
  71671. bodyConfig.size.push(size);
  71672. break;
  71673. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71674. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  71675. var sizeY = checkWithEpsilon_1(extendSize.y);
  71676. bodyConfig.type.push('cylinder');
  71677. bodyConfig.size.push(sizeX);
  71678. bodyConfig.size.push(sizeY);
  71679. //due to the way oimo works with compounds, add one more value.
  71680. bodyConfig.size.push(sizeY);
  71681. break;
  71682. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71683. case BABYLON.PhysicsImpostor.BoxImpostor:
  71684. default:
  71685. var sizeX = checkWithEpsilon_1(extendSize.x);
  71686. var sizeY = checkWithEpsilon_1(extendSize.y);
  71687. var sizeZ = checkWithEpsilon_1(extendSize.z);
  71688. bodyConfig.type.push('box');
  71689. bodyConfig.size.push(sizeX);
  71690. bodyConfig.size.push(sizeY);
  71691. bodyConfig.size.push(sizeZ);
  71692. break;
  71693. }
  71694. //actually not needed, but hey...
  71695. i.object.rotationQuaternion = oldQuaternion;
  71696. });
  71697. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  71698. }
  71699. else {
  71700. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  71701. }
  71702. impostor.setDeltaPosition(this._tmpPositionVector);
  71703. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  71704. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  71705. };
  71706. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  71707. //impostor.physicsBody.dispose();
  71708. //Same as : (older oimo versions)
  71709. this.world.removeRigidBody(impostor.physicsBody);
  71710. };
  71711. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  71712. var mainBody = impostorJoint.mainImpostor.physicsBody;
  71713. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  71714. if (!mainBody || !connectedBody) {
  71715. return;
  71716. }
  71717. var jointData = impostorJoint.joint.jointData;
  71718. var options = jointData.nativeParams || {};
  71719. var type;
  71720. var nativeJointData = {
  71721. body1: mainBody,
  71722. body2: connectedBody,
  71723. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  71724. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  71725. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  71726. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  71727. min: options.min,
  71728. max: options.max,
  71729. collision: options.collision || jointData.collision,
  71730. spring: options.spring,
  71731. //supporting older version of Oimo
  71732. world: this.world
  71733. };
  71734. switch (impostorJoint.joint.type) {
  71735. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71736. type = "jointBall";
  71737. break;
  71738. case BABYLON.PhysicsJoint.SpringJoint:
  71739. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  71740. var springData = jointData;
  71741. nativeJointData.min = springData.length || nativeJointData.min;
  71742. //Max should also be set, just make sure it is at least min
  71743. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  71744. case BABYLON.PhysicsJoint.DistanceJoint:
  71745. type = "jointDistance";
  71746. nativeJointData.max = jointData.maxDistance;
  71747. break;
  71748. case BABYLON.PhysicsJoint.PrismaticJoint:
  71749. type = "jointPrisme";
  71750. break;
  71751. case BABYLON.PhysicsJoint.SliderJoint:
  71752. type = "jointSlide";
  71753. break;
  71754. case BABYLON.PhysicsJoint.WheelJoint:
  71755. type = "jointWheel";
  71756. break;
  71757. case BABYLON.PhysicsJoint.HingeJoint:
  71758. default:
  71759. type = "jointHinge";
  71760. break;
  71761. }
  71762. nativeJointData.type = type;
  71763. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  71764. };
  71765. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71766. //Bug in Oimo prevents us from disposing a joint in the playground
  71767. //joint.joint.physicsJoint.dispose();
  71768. //So we will bruteforce it!
  71769. try {
  71770. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  71771. }
  71772. catch (e) {
  71773. BABYLON.Tools.Warn(e);
  71774. }
  71775. };
  71776. OimoJSPlugin.prototype.isSupported = function () {
  71777. return this.BJSOIMO !== undefined;
  71778. };
  71779. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71780. if (!impostor.physicsBody.sleeping) {
  71781. //TODO check that
  71782. if (impostor.physicsBody.shapes.next) {
  71783. var parentShape = this._getLastShape(impostor.physicsBody);
  71784. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  71785. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  71786. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  71787. }
  71788. else {
  71789. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  71790. }
  71791. if (impostor.object.rotationQuaternion) {
  71792. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  71793. impostor.object.rotationQuaternion.normalize();
  71794. }
  71795. }
  71796. };
  71797. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71798. var body = impostor.physicsBody;
  71799. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  71800. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  71801. body.syncShapes();
  71802. body.awake();
  71803. };
  71804. OimoJSPlugin.prototype._getLastShape = function (body) {
  71805. var lastShape = body.shapes;
  71806. while (lastShape.next) {
  71807. lastShape = lastShape.next;
  71808. }
  71809. return lastShape;
  71810. };
  71811. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71812. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  71813. };
  71814. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71815. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  71816. };
  71817. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71818. var v = impostor.physicsBody.linearVelocity;
  71819. if (!v) {
  71820. return null;
  71821. }
  71822. return new BABYLON.Vector3(v.x, v.y, v.z);
  71823. };
  71824. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71825. var v = impostor.physicsBody.angularVelocity;
  71826. if (!v) {
  71827. return null;
  71828. }
  71829. return new BABYLON.Vector3(v.x, v.y, v.z);
  71830. };
  71831. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71832. var staticBody = mass === 0;
  71833. //this will actually set the body's density and not its mass.
  71834. //But this is how oimo treats the mass variable.
  71835. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  71836. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  71837. };
  71838. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  71839. return impostor.physicsBody.shapes.density;
  71840. };
  71841. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  71842. return impostor.physicsBody.shapes.friction;
  71843. };
  71844. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71845. impostor.physicsBody.shapes.friction = friction;
  71846. };
  71847. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71848. return impostor.physicsBody.shapes.restitution;
  71849. };
  71850. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71851. impostor.physicsBody.shapes.restitution = restitution;
  71852. };
  71853. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  71854. impostor.physicsBody.sleep();
  71855. };
  71856. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  71857. impostor.physicsBody.awake();
  71858. };
  71859. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71860. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  71861. if (minDistance !== void 0) {
  71862. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  71863. }
  71864. };
  71865. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71866. //TODO separate rotational and transational motors.
  71867. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  71868. if (motor) {
  71869. motor.setMotor(speed, maxForce);
  71870. }
  71871. };
  71872. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  71873. //TODO separate rotational and transational motors.
  71874. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  71875. if (motor) {
  71876. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  71877. }
  71878. };
  71879. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71880. var body = impostor.physicsBody;
  71881. mesh.position.x = body.position.x;
  71882. mesh.position.y = body.position.y;
  71883. mesh.position.z = body.position.z;
  71884. if (mesh.rotationQuaternion) {
  71885. mesh.rotationQuaternion.x = body.orientation.x;
  71886. mesh.rotationQuaternion.y = body.orientation.y;
  71887. mesh.rotationQuaternion.z = body.orientation.z;
  71888. mesh.rotationQuaternion.w = body.orientation.s;
  71889. }
  71890. };
  71891. OimoJSPlugin.prototype.getRadius = function (impostor) {
  71892. return impostor.physicsBody.shapes.radius;
  71893. };
  71894. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71895. var shape = impostor.physicsBody.shapes;
  71896. result.x = shape.halfWidth * 2;
  71897. result.y = shape.halfHeight * 2;
  71898. result.z = shape.halfDepth * 2;
  71899. };
  71900. OimoJSPlugin.prototype.dispose = function () {
  71901. this.world.clear();
  71902. };
  71903. return OimoJSPlugin;
  71904. }());
  71905. BABYLON.OimoJSPlugin = OimoJSPlugin;
  71906. })(BABYLON || (BABYLON = {}));
  71907. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  71908. var BABYLON;
  71909. (function (BABYLON) {
  71910. /*
  71911. * Based on jsTGALoader - Javascript loader for TGA file
  71912. * By Vincent Thibault
  71913. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  71914. */
  71915. var TGATools = /** @class */ (function () {
  71916. function TGATools() {
  71917. }
  71918. TGATools.GetTGAHeader = function (data) {
  71919. var offset = 0;
  71920. var header = {
  71921. id_length: data[offset++],
  71922. colormap_type: data[offset++],
  71923. image_type: data[offset++],
  71924. colormap_index: data[offset++] | data[offset++] << 8,
  71925. colormap_length: data[offset++] | data[offset++] << 8,
  71926. colormap_size: data[offset++],
  71927. origin: [
  71928. data[offset++] | data[offset++] << 8,
  71929. data[offset++] | data[offset++] << 8
  71930. ],
  71931. width: data[offset++] | data[offset++] << 8,
  71932. height: data[offset++] | data[offset++] << 8,
  71933. pixel_size: data[offset++],
  71934. flags: data[offset++]
  71935. };
  71936. return header;
  71937. };
  71938. TGATools.UploadContent = function (gl, data) {
  71939. // Not enough data to contain header ?
  71940. if (data.length < 19) {
  71941. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  71942. return;
  71943. }
  71944. // Read Header
  71945. var offset = 18;
  71946. var header = TGATools.GetTGAHeader(data);
  71947. // Assume it's a valid Targa file.
  71948. if (header.id_length + offset > data.length) {
  71949. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  71950. return;
  71951. }
  71952. // Skip not needed data
  71953. offset += header.id_length;
  71954. var use_rle = false;
  71955. var use_pal = false;
  71956. var use_grey = false;
  71957. // Get some informations.
  71958. switch (header.image_type) {
  71959. case TGATools._TYPE_RLE_INDEXED:
  71960. use_rle = true;
  71961. case TGATools._TYPE_INDEXED:
  71962. use_pal = true;
  71963. break;
  71964. case TGATools._TYPE_RLE_RGB:
  71965. use_rle = true;
  71966. case TGATools._TYPE_RGB:
  71967. // use_rgb = true;
  71968. break;
  71969. case TGATools._TYPE_RLE_GREY:
  71970. use_rle = true;
  71971. case TGATools._TYPE_GREY:
  71972. use_grey = true;
  71973. break;
  71974. }
  71975. var pixel_data;
  71976. // var numAlphaBits = header.flags & 0xf;
  71977. var pixel_size = header.pixel_size >> 3;
  71978. var pixel_total = header.width * header.height * pixel_size;
  71979. // Read palettes
  71980. var palettes;
  71981. if (use_pal) {
  71982. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  71983. }
  71984. // Read LRE
  71985. if (use_rle) {
  71986. pixel_data = new Uint8Array(pixel_total);
  71987. var c, count, i;
  71988. var localOffset = 0;
  71989. var pixels = new Uint8Array(pixel_size);
  71990. while (offset < pixel_total && localOffset < pixel_total) {
  71991. c = data[offset++];
  71992. count = (c & 0x7f) + 1;
  71993. // RLE pixels
  71994. if (c & 0x80) {
  71995. // Bind pixel tmp array
  71996. for (i = 0; i < pixel_size; ++i) {
  71997. pixels[i] = data[offset++];
  71998. }
  71999. // Copy pixel array
  72000. for (i = 0; i < count; ++i) {
  72001. pixel_data.set(pixels, localOffset + i * pixel_size);
  72002. }
  72003. localOffset += pixel_size * count;
  72004. }
  72005. else {
  72006. count *= pixel_size;
  72007. for (i = 0; i < count; ++i) {
  72008. pixel_data[localOffset + i] = data[offset++];
  72009. }
  72010. localOffset += count;
  72011. }
  72012. }
  72013. }
  72014. else {
  72015. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  72016. }
  72017. // Load to texture
  72018. var x_start, y_start, x_step, y_step, y_end, x_end;
  72019. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  72020. default:
  72021. case TGATools._ORIGIN_UL:
  72022. x_start = 0;
  72023. x_step = 1;
  72024. x_end = header.width;
  72025. y_start = 0;
  72026. y_step = 1;
  72027. y_end = header.height;
  72028. break;
  72029. case TGATools._ORIGIN_BL:
  72030. x_start = 0;
  72031. x_step = 1;
  72032. x_end = header.width;
  72033. y_start = header.height - 1;
  72034. y_step = -1;
  72035. y_end = -1;
  72036. break;
  72037. case TGATools._ORIGIN_UR:
  72038. x_start = header.width - 1;
  72039. x_step = -1;
  72040. x_end = -1;
  72041. y_start = 0;
  72042. y_step = 1;
  72043. y_end = header.height;
  72044. break;
  72045. case TGATools._ORIGIN_BR:
  72046. x_start = header.width - 1;
  72047. x_step = -1;
  72048. x_end = -1;
  72049. y_start = header.height - 1;
  72050. y_step = -1;
  72051. y_end = -1;
  72052. break;
  72053. }
  72054. // Load the specify method
  72055. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  72056. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  72057. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  72058. };
  72059. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72060. var image = pixel_data, colormap = palettes;
  72061. var width = header.width, height = header.height;
  72062. var color, i = 0, x, y;
  72063. var imageData = new Uint8Array(width * height * 4);
  72064. for (y = y_start; y !== y_end; y += y_step) {
  72065. for (x = x_start; x !== x_end; x += x_step, i++) {
  72066. color = image[i];
  72067. imageData[(x + width * y) * 4 + 3] = 255;
  72068. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  72069. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  72070. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  72071. }
  72072. }
  72073. return imageData;
  72074. };
  72075. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72076. var image = pixel_data;
  72077. var width = header.width, height = header.height;
  72078. var color, i = 0, x, y;
  72079. var imageData = new Uint8Array(width * height * 4);
  72080. for (y = y_start; y !== y_end; y += y_step) {
  72081. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72082. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  72083. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  72084. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  72085. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  72086. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  72087. }
  72088. }
  72089. return imageData;
  72090. };
  72091. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72092. var image = pixel_data;
  72093. var width = header.width, height = header.height;
  72094. var i = 0, x, y;
  72095. var imageData = new Uint8Array(width * height * 4);
  72096. for (y = y_start; y !== y_end; y += y_step) {
  72097. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  72098. imageData[(x + width * y) * 4 + 3] = 255;
  72099. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72100. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72101. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72102. }
  72103. }
  72104. return imageData;
  72105. };
  72106. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72107. var image = pixel_data;
  72108. var width = header.width, height = header.height;
  72109. var i = 0, x, y;
  72110. var imageData = new Uint8Array(width * height * 4);
  72111. for (y = y_start; y !== y_end; y += y_step) {
  72112. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  72113. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72114. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72115. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72116. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  72117. }
  72118. }
  72119. return imageData;
  72120. };
  72121. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72122. var image = pixel_data;
  72123. var width = header.width, height = header.height;
  72124. var color, i = 0, x, y;
  72125. var imageData = new Uint8Array(width * height * 4);
  72126. for (y = y_start; y !== y_end; y += y_step) {
  72127. for (x = x_start; x !== x_end; x += x_step, i++) {
  72128. color = image[i];
  72129. imageData[(x + width * y) * 4 + 0] = color;
  72130. imageData[(x + width * y) * 4 + 1] = color;
  72131. imageData[(x + width * y) * 4 + 2] = color;
  72132. imageData[(x + width * y) * 4 + 3] = 255;
  72133. }
  72134. }
  72135. return imageData;
  72136. };
  72137. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72138. var image = pixel_data;
  72139. var width = header.width, height = header.height;
  72140. var i = 0, x, y;
  72141. var imageData = new Uint8Array(width * height * 4);
  72142. for (y = y_start; y !== y_end; y += y_step) {
  72143. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72144. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  72145. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  72146. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72147. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  72148. }
  72149. }
  72150. return imageData;
  72151. };
  72152. //private static _TYPE_NO_DATA = 0;
  72153. TGATools._TYPE_INDEXED = 1;
  72154. TGATools._TYPE_RGB = 2;
  72155. TGATools._TYPE_GREY = 3;
  72156. TGATools._TYPE_RLE_INDEXED = 9;
  72157. TGATools._TYPE_RLE_RGB = 10;
  72158. TGATools._TYPE_RLE_GREY = 11;
  72159. TGATools._ORIGIN_MASK = 0x30;
  72160. TGATools._ORIGIN_SHIFT = 0x04;
  72161. TGATools._ORIGIN_BL = 0x00;
  72162. TGATools._ORIGIN_BR = 0x01;
  72163. TGATools._ORIGIN_UL = 0x02;
  72164. TGATools._ORIGIN_UR = 0x03;
  72165. return TGATools;
  72166. }());
  72167. BABYLON.TGATools = TGATools;
  72168. })(BABYLON || (BABYLON = {}));
  72169. //# sourceMappingURL=babylon.tga.js.map
  72170. var BABYLON;
  72171. (function (BABYLON) {
  72172. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  72173. // All values and structures referenced from:
  72174. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72175. var DDS_MAGIC = 0x20534444;
  72176. var
  72177. //DDSD_CAPS = 0x1,
  72178. //DDSD_HEIGHT = 0x2,
  72179. //DDSD_WIDTH = 0x4,
  72180. //DDSD_PITCH = 0x8,
  72181. //DDSD_PIXELFORMAT = 0x1000,
  72182. DDSD_MIPMAPCOUNT = 0x20000;
  72183. //DDSD_LINEARSIZE = 0x80000,
  72184. //DDSD_DEPTH = 0x800000;
  72185. // var DDSCAPS_COMPLEX = 0x8,
  72186. // DDSCAPS_MIPMAP = 0x400000,
  72187. // DDSCAPS_TEXTURE = 0x1000;
  72188. var DDSCAPS2_CUBEMAP = 0x200;
  72189. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  72190. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  72191. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  72192. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  72193. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  72194. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  72195. // DDSCAPS2_VOLUME = 0x200000;
  72196. var
  72197. //DDPF_ALPHAPIXELS = 0x1,
  72198. //DDPF_ALPHA = 0x2,
  72199. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  72200. //DDPF_YUV = 0x200,
  72201. DDPF_LUMINANCE = 0x20000;
  72202. function FourCCToInt32(value) {
  72203. return value.charCodeAt(0) +
  72204. (value.charCodeAt(1) << 8) +
  72205. (value.charCodeAt(2) << 16) +
  72206. (value.charCodeAt(3) << 24);
  72207. }
  72208. function Int32ToFourCC(value) {
  72209. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  72210. }
  72211. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  72212. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  72213. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  72214. var FOURCC_DX10 = FourCCToInt32("DX10");
  72215. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  72216. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  72217. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  72218. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  72219. var headerLengthInt = 31; // The header length in 32 bit ints
  72220. // Offsets into the header array
  72221. var off_magic = 0;
  72222. var off_size = 1;
  72223. var off_flags = 2;
  72224. var off_height = 3;
  72225. var off_width = 4;
  72226. var off_mipmapCount = 7;
  72227. var off_pfFlags = 20;
  72228. var off_pfFourCC = 21;
  72229. var off_RGBbpp = 22;
  72230. var off_RMask = 23;
  72231. var off_GMask = 24;
  72232. var off_BMask = 25;
  72233. var off_AMask = 26;
  72234. // var off_caps1 = 27;
  72235. var off_caps2 = 28;
  72236. // var off_caps3 = 29;
  72237. // var off_caps4 = 30;
  72238. var off_dxgiFormat = 32;
  72239. ;
  72240. var DDSTools = /** @class */ (function () {
  72241. function DDSTools() {
  72242. }
  72243. DDSTools.GetDDSInfo = function (arrayBuffer) {
  72244. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72245. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  72246. var mipmapCount = 1;
  72247. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  72248. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72249. }
  72250. var fourCC = header[off_pfFourCC];
  72251. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  72252. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72253. switch (fourCC) {
  72254. case FOURCC_D3DFMT_R16G16B16A16F:
  72255. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72256. break;
  72257. case FOURCC_D3DFMT_R32G32B32A32F:
  72258. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72259. break;
  72260. case FOURCC_DX10:
  72261. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  72262. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72263. break;
  72264. }
  72265. }
  72266. return {
  72267. width: header[off_width],
  72268. height: header[off_height],
  72269. mipmapCount: mipmapCount,
  72270. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  72271. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  72272. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  72273. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  72274. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  72275. dxgiFormat: dxgiFormat,
  72276. textureType: textureType
  72277. };
  72278. };
  72279. DDSTools._ToHalfFloat = function (value) {
  72280. if (!DDSTools._FloatView) {
  72281. DDSTools._FloatView = new Float32Array(1);
  72282. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  72283. }
  72284. DDSTools._FloatView[0] = value;
  72285. var x = DDSTools._Int32View[0];
  72286. var bits = (x >> 16) & 0x8000; /* Get the sign */
  72287. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  72288. var e = (x >> 23) & 0xff; /* Using int is faster here */
  72289. /* If zero, or denormal, or exponent underflows too much for a denormal
  72290. * half, return signed zero. */
  72291. if (e < 103) {
  72292. return bits;
  72293. }
  72294. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  72295. if (e > 142) {
  72296. bits |= 0x7c00;
  72297. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  72298. * not Inf, so make sure we set one mantissa bit too. */
  72299. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  72300. return bits;
  72301. }
  72302. /* If exponent underflows but not too much, return a denormal */
  72303. if (e < 113) {
  72304. m |= 0x0800;
  72305. /* Extra rounding may overflow and set mantissa to 0 and exponent
  72306. * to 1, which is OK. */
  72307. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  72308. return bits;
  72309. }
  72310. bits |= ((e - 112) << 10) | (m >> 1);
  72311. bits += m & 1;
  72312. return bits;
  72313. };
  72314. DDSTools._FromHalfFloat = function (value) {
  72315. var s = (value & 0x8000) >> 15;
  72316. var e = (value & 0x7C00) >> 10;
  72317. var f = value & 0x03FF;
  72318. if (e === 0) {
  72319. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  72320. }
  72321. else if (e == 0x1F) {
  72322. return f ? NaN : ((s ? -1 : 1) * Infinity);
  72323. }
  72324. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  72325. };
  72326. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72327. var destArray = new Float32Array(dataLength);
  72328. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72329. var index = 0;
  72330. for (var y = 0; y < height; y++) {
  72331. for (var x = 0; x < width; x++) {
  72332. var srcPos = (x + y * width) * 4;
  72333. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  72334. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  72335. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  72336. if (DDSTools.StoreLODInAlphaChannel) {
  72337. destArray[index + 3] = lod;
  72338. }
  72339. else {
  72340. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  72341. }
  72342. index += 4;
  72343. }
  72344. }
  72345. return destArray;
  72346. };
  72347. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72348. if (DDSTools.StoreLODInAlphaChannel) {
  72349. var destArray = new Uint16Array(dataLength);
  72350. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72351. var index = 0;
  72352. for (var y = 0; y < height; y++) {
  72353. for (var x = 0; x < width; x++) {
  72354. var srcPos = (x + y * width) * 4;
  72355. destArray[index] = srcData[srcPos];
  72356. destArray[index + 1] = srcData[srcPos + 1];
  72357. destArray[index + 2] = srcData[srcPos + 2];
  72358. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  72359. index += 4;
  72360. }
  72361. }
  72362. return destArray;
  72363. }
  72364. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  72365. };
  72366. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72367. if (DDSTools.StoreLODInAlphaChannel) {
  72368. var destArray = new Float32Array(dataLength);
  72369. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72370. var index = 0;
  72371. for (var y = 0; y < height; y++) {
  72372. for (var x = 0; x < width; x++) {
  72373. var srcPos = (x + y * width) * 4;
  72374. destArray[index] = srcData[srcPos];
  72375. destArray[index + 1] = srcData[srcPos + 1];
  72376. destArray[index + 2] = srcData[srcPos + 2];
  72377. destArray[index + 3] = lod;
  72378. index += 4;
  72379. }
  72380. }
  72381. return destArray;
  72382. }
  72383. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  72384. };
  72385. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72386. var destArray = new Uint8Array(dataLength);
  72387. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72388. var index = 0;
  72389. for (var y = 0; y < height; y++) {
  72390. for (var x = 0; x < width; x++) {
  72391. var srcPos = (x + y * width) * 4;
  72392. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  72393. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  72394. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  72395. if (DDSTools.StoreLODInAlphaChannel) {
  72396. destArray[index + 3] = lod;
  72397. }
  72398. else {
  72399. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  72400. }
  72401. index += 4;
  72402. }
  72403. }
  72404. return destArray;
  72405. };
  72406. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72407. var destArray = new Uint8Array(dataLength);
  72408. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72409. var index = 0;
  72410. for (var y = 0; y < height; y++) {
  72411. for (var x = 0; x < width; x++) {
  72412. var srcPos = (x + y * width) * 4;
  72413. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  72414. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  72415. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  72416. if (DDSTools.StoreLODInAlphaChannel) {
  72417. destArray[index + 3] = lod;
  72418. }
  72419. else {
  72420. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  72421. }
  72422. index += 4;
  72423. }
  72424. }
  72425. return destArray;
  72426. };
  72427. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  72428. var byteArray = new Uint8Array(dataLength);
  72429. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72430. var index = 0;
  72431. for (var y = 0; y < height; y++) {
  72432. for (var x = 0; x < width; x++) {
  72433. var srcPos = (x + y * width) * 4;
  72434. byteArray[index] = srcData[srcPos + rOffset];
  72435. byteArray[index + 1] = srcData[srcPos + gOffset];
  72436. byteArray[index + 2] = srcData[srcPos + bOffset];
  72437. byteArray[index + 3] = srcData[srcPos + aOffset];
  72438. index += 4;
  72439. }
  72440. }
  72441. return byteArray;
  72442. };
  72443. DDSTools._ExtractLongWordOrder = function (value) {
  72444. if (value === 0 || value === 255 || value === -16777216) {
  72445. return 0;
  72446. }
  72447. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  72448. };
  72449. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  72450. var byteArray = new Uint8Array(dataLength);
  72451. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72452. var index = 0;
  72453. for (var y = 0; y < height; y++) {
  72454. for (var x = 0; x < width; x++) {
  72455. var srcPos = (x + y * width) * 3;
  72456. byteArray[index] = srcData[srcPos + rOffset];
  72457. byteArray[index + 1] = srcData[srcPos + gOffset];
  72458. byteArray[index + 2] = srcData[srcPos + bOffset];
  72459. index += 3;
  72460. }
  72461. }
  72462. return byteArray;
  72463. };
  72464. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  72465. var byteArray = new Uint8Array(dataLength);
  72466. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72467. var index = 0;
  72468. for (var y = 0; y < height; y++) {
  72469. for (var x = 0; x < width; x++) {
  72470. var srcPos = (x + y * width);
  72471. byteArray[index] = srcData[srcPos];
  72472. index++;
  72473. }
  72474. }
  72475. return byteArray;
  72476. };
  72477. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  72478. if (lodIndex === void 0) { lodIndex = -1; }
  72479. var ext = engine.getCaps().s3tc;
  72480. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72481. var fourCC, width, height, dataLength = 0, dataOffset;
  72482. var byteArray, mipmapCount, mip;
  72483. var internalFormat = 0;
  72484. var format = 0;
  72485. var blockBytes = 1;
  72486. if (header[off_magic] !== DDS_MAGIC) {
  72487. BABYLON.Tools.Error("Invalid magic number in DDS header");
  72488. return;
  72489. }
  72490. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  72491. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  72492. return;
  72493. }
  72494. if (info.isCompressed && !ext) {
  72495. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  72496. return;
  72497. }
  72498. var bpp = header[off_RGBbpp];
  72499. dataOffset = header[off_size] + 4;
  72500. var computeFormats = false;
  72501. if (info.isFourCC) {
  72502. fourCC = header[off_pfFourCC];
  72503. switch (fourCC) {
  72504. case FOURCC_DXT1:
  72505. blockBytes = 8;
  72506. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  72507. break;
  72508. case FOURCC_DXT3:
  72509. blockBytes = 16;
  72510. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  72511. break;
  72512. case FOURCC_DXT5:
  72513. blockBytes = 16;
  72514. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  72515. break;
  72516. case FOURCC_D3DFMT_R16G16B16A16F:
  72517. computeFormats = true;
  72518. break;
  72519. case FOURCC_D3DFMT_R32G32B32A32F:
  72520. computeFormats = true;
  72521. break;
  72522. case FOURCC_DX10:
  72523. // There is an additionnal header so dataOffset need to be changed
  72524. dataOffset += 5 * 4; // 5 uints
  72525. var supported = false;
  72526. switch (info.dxgiFormat) {
  72527. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  72528. computeFormats = true;
  72529. supported = true;
  72530. break;
  72531. case DXGI_FORMAT_B8G8R8X8_UNORM:
  72532. info.isRGB = true;
  72533. info.isFourCC = false;
  72534. bpp = 32;
  72535. supported = true;
  72536. break;
  72537. }
  72538. if (supported) {
  72539. break;
  72540. }
  72541. default:
  72542. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  72543. return;
  72544. }
  72545. }
  72546. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  72547. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  72548. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  72549. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  72550. if (computeFormats) {
  72551. format = engine._getWebGLTextureType(info.textureType);
  72552. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72553. }
  72554. mipmapCount = 1;
  72555. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  72556. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72557. }
  72558. for (var face = 0; face < faces; face++) {
  72559. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  72560. width = header[off_width];
  72561. height = header[off_height];
  72562. for (mip = 0; mip < mipmapCount; ++mip) {
  72563. if (lodIndex === -1 || lodIndex === mip) {
  72564. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  72565. var i = (lodIndex === -1) ? mip : 0;
  72566. if (!info.isCompressed && info.isFourCC) {
  72567. dataLength = width * height * 4;
  72568. var floatArray = null;
  72569. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  72570. if (bpp === 128) {
  72571. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72572. }
  72573. else if (bpp === 64) {
  72574. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72575. }
  72576. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72577. format = engine._getWebGLTextureType(info.textureType);
  72578. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72579. }
  72580. else {
  72581. if (bpp === 128) {
  72582. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72583. }
  72584. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  72585. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72586. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72587. format = engine._getWebGLTextureType(info.textureType);
  72588. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72589. }
  72590. else {
  72591. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72592. }
  72593. }
  72594. if (floatArray) {
  72595. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  72596. }
  72597. }
  72598. else if (info.isRGB) {
  72599. if (bpp === 24) {
  72600. dataLength = width * height * 3;
  72601. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  72602. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  72603. }
  72604. else {
  72605. dataLength = width * height * 4;
  72606. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  72607. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  72608. }
  72609. }
  72610. else if (info.isLuminance) {
  72611. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  72612. var unpaddedRowSize = width;
  72613. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  72614. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  72615. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  72616. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  72617. }
  72618. else {
  72619. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  72620. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  72621. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  72622. }
  72623. }
  72624. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  72625. width *= 0.5;
  72626. height *= 0.5;
  72627. width = Math.max(1.0, width);
  72628. height = Math.max(1.0, height);
  72629. }
  72630. if (currentFace !== undefined) {
  72631. // Loading a single face
  72632. break;
  72633. }
  72634. }
  72635. };
  72636. DDSTools.StoreLODInAlphaChannel = false;
  72637. return DDSTools;
  72638. }());
  72639. BABYLON.DDSTools = DDSTools;
  72640. })(BABYLON || (BABYLON = {}));
  72641. //# sourceMappingURL=babylon.dds.js.map
  72642. var BABYLON;
  72643. (function (BABYLON) {
  72644. /**
  72645. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  72646. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  72647. */
  72648. var KhronosTextureContainer = /** @class */ (function () {
  72649. /**
  72650. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  72651. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  72652. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  72653. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  72654. */
  72655. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  72656. this.arrayBuffer = arrayBuffer;
  72657. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  72658. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  72659. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  72660. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  72661. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  72662. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  72663. BABYLON.Tools.Error("texture missing KTX identifier");
  72664. return;
  72665. }
  72666. // load the reset of the header in native 32 bit int
  72667. var header = new Int32Array(this.arrayBuffer, 12, 13);
  72668. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  72669. var oppositeEndianess = header[0] === 0x01020304;
  72670. // read all the header elements in order they exist in the file, without modification (sans endainness)
  72671. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  72672. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  72673. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  72674. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  72675. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  72676. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  72677. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  72678. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  72679. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  72680. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  72681. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  72682. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  72683. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  72684. if (this.glType !== 0) {
  72685. BABYLON.Tools.Error("only compressed formats currently supported");
  72686. return;
  72687. }
  72688. else {
  72689. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  72690. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  72691. }
  72692. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  72693. BABYLON.Tools.Error("only 2D textures currently supported");
  72694. return;
  72695. }
  72696. if (this.numberOfArrayElements !== 0) {
  72697. BABYLON.Tools.Error("texture arrays not currently supported");
  72698. return;
  72699. }
  72700. if (this.numberOfFaces !== facesExpected) {
  72701. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  72702. return;
  72703. }
  72704. // we now have a completely validated file, so could use existence of loadType as success
  72705. // would need to make this more elaborate & adjust checks above to support more than one load type
  72706. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  72707. }
  72708. // not as fast hardware based, but will probably never need to use
  72709. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  72710. return ((val & 0xFF) << 24)
  72711. | ((val & 0xFF00) << 8)
  72712. | ((val >> 8) & 0xFF00)
  72713. | ((val >> 24) & 0xFF);
  72714. };
  72715. /**
  72716. * It is assumed that the texture has already been created & is currently bound
  72717. */
  72718. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  72719. switch (this.loadType) {
  72720. case KhronosTextureContainer.COMPRESSED_2D:
  72721. this._upload2DCompressedLevels(gl, loadMipmaps);
  72722. break;
  72723. case KhronosTextureContainer.TEX_2D:
  72724. case KhronosTextureContainer.COMPRESSED_3D:
  72725. case KhronosTextureContainer.TEX_3D:
  72726. }
  72727. };
  72728. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  72729. // initialize width & height for level 1
  72730. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  72731. var width = this.pixelWidth;
  72732. var height = this.pixelHeight;
  72733. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  72734. for (var level = 0; level < mipmapCount; level++) {
  72735. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  72736. for (var face = 0; face < this.numberOfFaces; face++) {
  72737. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  72738. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  72739. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  72740. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  72741. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  72742. }
  72743. width = Math.max(1.0, width * 0.5);
  72744. height = Math.max(1.0, height * 0.5);
  72745. }
  72746. };
  72747. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  72748. // load types
  72749. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  72750. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  72751. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  72752. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  72753. return KhronosTextureContainer;
  72754. }());
  72755. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  72756. })(BABYLON || (BABYLON = {}));
  72757. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  72758. var BABYLON;
  72759. (function (BABYLON) {
  72760. var Debug = /** @class */ (function () {
  72761. function Debug() {
  72762. }
  72763. Debug.AxesViewer = /** @class */ (function () {
  72764. function AxesViewer(scene, scaleLines) {
  72765. if (scaleLines === void 0) { scaleLines = 1; }
  72766. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72767. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72768. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72769. this.scaleLines = 1;
  72770. this.scaleLines = scaleLines;
  72771. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  72772. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  72773. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  72774. this._xmesh.renderingGroupId = 2;
  72775. this._ymesh.renderingGroupId = 2;
  72776. this._zmesh.renderingGroupId = 2;
  72777. this._xmesh.material.checkReadyOnlyOnce = true;
  72778. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  72779. this._ymesh.material.checkReadyOnlyOnce = true;
  72780. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  72781. this._zmesh.material.checkReadyOnlyOnce = true;
  72782. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  72783. this.scene = scene;
  72784. }
  72785. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  72786. var scaleLines = this.scaleLines;
  72787. if (this._xmesh) {
  72788. this._xmesh.position.copyFrom(position);
  72789. }
  72790. if (this._ymesh) {
  72791. this._ymesh.position.copyFrom(position);
  72792. }
  72793. if (this._zmesh) {
  72794. this._zmesh.position.copyFrom(position);
  72795. }
  72796. var point2 = this._xline[1];
  72797. point2.x = xaxis.x * scaleLines;
  72798. point2.y = xaxis.y * scaleLines;
  72799. point2.z = xaxis.z * scaleLines;
  72800. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  72801. point2 = this._yline[1];
  72802. point2.x = yaxis.x * scaleLines;
  72803. point2.y = yaxis.y * scaleLines;
  72804. point2.z = yaxis.z * scaleLines;
  72805. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  72806. point2 = this._zline[1];
  72807. point2.x = zaxis.x * scaleLines;
  72808. point2.y = zaxis.y * scaleLines;
  72809. point2.z = zaxis.z * scaleLines;
  72810. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  72811. };
  72812. AxesViewer.prototype.dispose = function () {
  72813. if (this._xmesh) {
  72814. this._xmesh.dispose();
  72815. }
  72816. if (this._ymesh) {
  72817. this._ymesh.dispose();
  72818. }
  72819. if (this._zmesh) {
  72820. this._zmesh.dispose();
  72821. }
  72822. this._xmesh = null;
  72823. this._ymesh = null;
  72824. this._zmesh = null;
  72825. this.scene = null;
  72826. };
  72827. return AxesViewer;
  72828. }());
  72829. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  72830. __extends(BoneAxesViewer, _super);
  72831. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  72832. if (scaleLines === void 0) { scaleLines = 1; }
  72833. var _this = _super.call(this, scene, scaleLines) || this;
  72834. _this.pos = BABYLON.Vector3.Zero();
  72835. _this.xaxis = BABYLON.Vector3.Zero();
  72836. _this.yaxis = BABYLON.Vector3.Zero();
  72837. _this.zaxis = BABYLON.Vector3.Zero();
  72838. _this.mesh = mesh;
  72839. _this.bone = bone;
  72840. return _this;
  72841. }
  72842. BoneAxesViewer.prototype.update = function () {
  72843. if (!this.mesh || !this.bone) {
  72844. return;
  72845. }
  72846. var bone = this.bone;
  72847. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  72848. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  72849. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  72850. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  72851. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  72852. };
  72853. BoneAxesViewer.prototype.dispose = function () {
  72854. if (this.mesh) {
  72855. this.mesh = null;
  72856. this.bone = null;
  72857. _super.prototype.dispose.call(this);
  72858. }
  72859. };
  72860. return BoneAxesViewer;
  72861. }(Debug.AxesViewer));
  72862. Debug.PhysicsViewer = /** @class */ (function () {
  72863. function PhysicsViewer(scene) {
  72864. this._impostors = [];
  72865. this._meshes = [];
  72866. this._numMeshes = 0;
  72867. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72868. var physicEngine = this._scene.getPhysicsEngine();
  72869. if (physicEngine) {
  72870. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  72871. }
  72872. }
  72873. PhysicsViewer.prototype._updateDebugMeshes = function () {
  72874. var plugin = this._physicsEnginePlugin;
  72875. for (var i = 0; i < this._numMeshes; i++) {
  72876. var impostor = this._impostors[i];
  72877. if (!impostor) {
  72878. continue;
  72879. }
  72880. if (impostor.isDisposed) {
  72881. this.hideImpostor(this._impostors[i--]);
  72882. }
  72883. else {
  72884. var mesh = this._meshes[i];
  72885. if (mesh && plugin) {
  72886. plugin.syncMeshWithImpostor(mesh, impostor);
  72887. }
  72888. }
  72889. }
  72890. };
  72891. PhysicsViewer.prototype.showImpostor = function (impostor) {
  72892. if (!this._scene) {
  72893. return;
  72894. }
  72895. for (var i = 0; i < this._numMeshes; i++) {
  72896. if (this._impostors[i] == impostor) {
  72897. return;
  72898. }
  72899. }
  72900. var debugMesh = this._getDebugMesh(impostor, this._scene);
  72901. if (debugMesh) {
  72902. this._impostors[this._numMeshes] = impostor;
  72903. this._meshes[this._numMeshes] = debugMesh;
  72904. if (this._numMeshes === 0) {
  72905. this._renderFunction = this._updateDebugMeshes.bind(this);
  72906. this._scene.registerBeforeRender(this._renderFunction);
  72907. }
  72908. this._numMeshes++;
  72909. }
  72910. };
  72911. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  72912. if (!impostor || !this._scene) {
  72913. return;
  72914. }
  72915. var removed = false;
  72916. for (var i = 0; i < this._numMeshes; i++) {
  72917. if (this._impostors[i] == impostor) {
  72918. var mesh = this._meshes[i];
  72919. if (!mesh) {
  72920. continue;
  72921. }
  72922. this._scene.removeMesh(mesh);
  72923. mesh.dispose();
  72924. this._numMeshes--;
  72925. if (this._numMeshes > 0) {
  72926. this._meshes[i] = this._meshes[this._numMeshes];
  72927. this._impostors[i] = this._impostors[this._numMeshes];
  72928. this._meshes[this._numMeshes] = null;
  72929. this._impostors[this._numMeshes] = null;
  72930. }
  72931. else {
  72932. this._meshes[0] = null;
  72933. this._impostors[0] = null;
  72934. }
  72935. removed = true;
  72936. break;
  72937. }
  72938. }
  72939. if (removed && this._numMeshes === 0) {
  72940. this._scene.unregisterBeforeRender(this._renderFunction);
  72941. }
  72942. };
  72943. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  72944. if (!this._debugMaterial) {
  72945. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  72946. this._debugMaterial.wireframe = true;
  72947. }
  72948. return this._debugMaterial;
  72949. };
  72950. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  72951. if (!this._debugBoxMesh) {
  72952. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  72953. this._debugBoxMesh.renderingGroupId = 1;
  72954. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  72955. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  72956. scene.removeMesh(this._debugBoxMesh);
  72957. }
  72958. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  72959. };
  72960. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  72961. if (!this._debugSphereMesh) {
  72962. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  72963. this._debugSphereMesh.renderingGroupId = 1;
  72964. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  72965. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  72966. scene.removeMesh(this._debugSphereMesh);
  72967. }
  72968. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  72969. };
  72970. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  72971. var mesh = null;
  72972. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  72973. mesh = this._getDebugBoxMesh(scene);
  72974. impostor.getBoxSizeToRef(mesh.scaling);
  72975. }
  72976. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  72977. mesh = this._getDebugSphereMesh(scene);
  72978. var radius = impostor.getRadius();
  72979. mesh.scaling.x = radius * 2;
  72980. mesh.scaling.y = radius * 2;
  72981. mesh.scaling.z = radius * 2;
  72982. }
  72983. return mesh;
  72984. };
  72985. PhysicsViewer.prototype.dispose = function () {
  72986. for (var i = 0; i < this._numMeshes; i++) {
  72987. this.hideImpostor(this._impostors[i]);
  72988. }
  72989. if (this._debugBoxMesh) {
  72990. this._debugBoxMesh.dispose();
  72991. }
  72992. if (this._debugSphereMesh) {
  72993. this._debugSphereMesh.dispose();
  72994. }
  72995. if (this._debugMaterial) {
  72996. this._debugMaterial.dispose();
  72997. }
  72998. this._impostors.length = 0;
  72999. this._scene = null;
  73000. this._physicsEnginePlugin = null;
  73001. };
  73002. return PhysicsViewer;
  73003. }());
  73004. Debug.SkeletonViewer = /** @class */ (function () {
  73005. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  73006. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  73007. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  73008. this.skeleton = skeleton;
  73009. this.mesh = mesh;
  73010. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  73011. this.renderingGroupId = renderingGroupId;
  73012. this.color = BABYLON.Color3.White();
  73013. this._debugLines = new Array();
  73014. this._isEnabled = false;
  73015. this._scene = scene;
  73016. this.update();
  73017. this._renderFunction = this.update.bind(this);
  73018. }
  73019. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  73020. get: function () {
  73021. return this._isEnabled;
  73022. },
  73023. set: function (value) {
  73024. if (this._isEnabled === value) {
  73025. return;
  73026. }
  73027. this._isEnabled = value;
  73028. if (value) {
  73029. this._scene.registerBeforeRender(this._renderFunction);
  73030. }
  73031. else {
  73032. this._scene.unregisterBeforeRender(this._renderFunction);
  73033. }
  73034. },
  73035. enumerable: true,
  73036. configurable: true
  73037. });
  73038. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  73039. if (x === void 0) { x = 0; }
  73040. if (y === void 0) { y = 0; }
  73041. if (z === void 0) { z = 0; }
  73042. var tmat = BABYLON.Tmp.Matrix[0];
  73043. var parentBone = bone.getParent();
  73044. tmat.copyFrom(bone.getLocalMatrix());
  73045. if (x !== 0 || y !== 0 || z !== 0) {
  73046. var tmat2 = BABYLON.Tmp.Matrix[1];
  73047. BABYLON.Matrix.IdentityToRef(tmat2);
  73048. tmat2.m[12] = x;
  73049. tmat2.m[13] = y;
  73050. tmat2.m[14] = z;
  73051. tmat2.multiplyToRef(tmat, tmat);
  73052. }
  73053. if (parentBone) {
  73054. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  73055. }
  73056. tmat.multiplyToRef(meshMat, tmat);
  73057. position.x = tmat.m[12];
  73058. position.y = tmat.m[13];
  73059. position.z = tmat.m[14];
  73060. };
  73061. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  73062. var len = bones.length;
  73063. var meshPos = this.mesh.position;
  73064. for (var i = 0; i < len; i++) {
  73065. var bone = bones[i];
  73066. var points = this._debugLines[i];
  73067. if (!points) {
  73068. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73069. this._debugLines[i] = points;
  73070. }
  73071. this._getBonePosition(points[0], bone, meshMat);
  73072. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  73073. points[0].subtractInPlace(meshPos);
  73074. points[1].subtractInPlace(meshPos);
  73075. }
  73076. };
  73077. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  73078. var len = bones.length;
  73079. var boneNum = 0;
  73080. var meshPos = this.mesh.position;
  73081. for (var i = len - 1; i >= 0; i--) {
  73082. var childBone = bones[i];
  73083. var parentBone = childBone.getParent();
  73084. if (!parentBone) {
  73085. continue;
  73086. }
  73087. var points = this._debugLines[boneNum];
  73088. if (!points) {
  73089. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73090. this._debugLines[boneNum] = points;
  73091. }
  73092. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  73093. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  73094. points[0].subtractInPlace(meshPos);
  73095. points[1].subtractInPlace(meshPos);
  73096. boneNum++;
  73097. }
  73098. };
  73099. SkeletonViewer.prototype.update = function () {
  73100. if (this.autoUpdateBonesMatrices) {
  73101. this.skeleton.computeAbsoluteTransforms();
  73102. }
  73103. if (this.skeleton.bones[0].length === undefined) {
  73104. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73105. }
  73106. else {
  73107. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73108. }
  73109. if (!this._debugMesh) {
  73110. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  73111. this._debugMesh.renderingGroupId = this.renderingGroupId;
  73112. }
  73113. else {
  73114. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  73115. }
  73116. this._debugMesh.position.copyFrom(this.mesh.position);
  73117. this._debugMesh.color = this.color;
  73118. };
  73119. SkeletonViewer.prototype.dispose = function () {
  73120. if (this._debugMesh) {
  73121. this.isEnabled = false;
  73122. this._debugMesh.dispose();
  73123. this._debugMesh = null;
  73124. }
  73125. };
  73126. return SkeletonViewer;
  73127. }());
  73128. return Debug;
  73129. }());
  73130. BABYLON.Debug = Debug;
  73131. })(BABYLON || (BABYLON = {}));
  73132. //# sourceMappingURL=babylon.debugModules.js.map
  73133. var BABYLON;
  73134. (function (BABYLON) {
  73135. var RayHelper = /** @class */ (function () {
  73136. function RayHelper(ray) {
  73137. this.ray = ray;
  73138. }
  73139. RayHelper.CreateAndShow = function (ray, scene, color) {
  73140. var helper = new RayHelper(ray);
  73141. helper.show(scene, color);
  73142. return helper;
  73143. };
  73144. RayHelper.prototype.show = function (scene, color) {
  73145. if (!this._renderFunction && this.ray) {
  73146. var ray = this.ray;
  73147. this._renderFunction = this._render.bind(this);
  73148. this._scene = scene;
  73149. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  73150. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  73151. if (this._renderFunction) {
  73152. this._scene.registerBeforeRender(this._renderFunction);
  73153. }
  73154. }
  73155. if (color && this._renderLine) {
  73156. this._renderLine.color.copyFrom(color);
  73157. }
  73158. };
  73159. RayHelper.prototype.hide = function () {
  73160. if (this._renderFunction && this._scene) {
  73161. this._scene.unregisterBeforeRender(this._renderFunction);
  73162. this._scene = null;
  73163. this._renderFunction = null;
  73164. if (this._renderLine) {
  73165. this._renderLine.dispose();
  73166. this._renderLine = null;
  73167. }
  73168. this._renderPoints = [];
  73169. }
  73170. };
  73171. RayHelper.prototype._render = function () {
  73172. var ray = this.ray;
  73173. if (!ray) {
  73174. return;
  73175. }
  73176. var point = this._renderPoints[1];
  73177. var len = Math.min(ray.length, 1000000);
  73178. point.copyFrom(ray.direction);
  73179. point.scaleInPlace(len);
  73180. point.addInPlace(ray.origin);
  73181. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  73182. };
  73183. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  73184. this._attachedToMesh = mesh;
  73185. var ray = this.ray;
  73186. if (!ray) {
  73187. return;
  73188. }
  73189. if (!ray.direction) {
  73190. ray.direction = BABYLON.Vector3.Zero();
  73191. }
  73192. if (!ray.origin) {
  73193. ray.origin = BABYLON.Vector3.Zero();
  73194. }
  73195. if (length) {
  73196. ray.length = length;
  73197. }
  73198. if (!meshSpaceOrigin) {
  73199. meshSpaceOrigin = BABYLON.Vector3.Zero();
  73200. }
  73201. if (!meshSpaceDirection) {
  73202. // -1 so that this will work with Mesh.lookAt
  73203. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  73204. }
  73205. if (!this._meshSpaceDirection) {
  73206. this._meshSpaceDirection = meshSpaceDirection.clone();
  73207. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  73208. }
  73209. else {
  73210. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  73211. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  73212. }
  73213. if (!this._updateToMeshFunction) {
  73214. this._updateToMeshFunction = this._updateToMesh.bind(this);
  73215. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  73216. }
  73217. this._updateToMesh();
  73218. };
  73219. RayHelper.prototype.detachFromMesh = function () {
  73220. if (this._attachedToMesh) {
  73221. if (this._updateToMeshFunction) {
  73222. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  73223. }
  73224. this._attachedToMesh = null;
  73225. this._updateToMeshFunction = null;
  73226. }
  73227. };
  73228. RayHelper.prototype._updateToMesh = function () {
  73229. var ray = this.ray;
  73230. if (!this._attachedToMesh || !ray) {
  73231. return;
  73232. }
  73233. if (this._attachedToMesh._isDisposed) {
  73234. this.detachFromMesh();
  73235. return;
  73236. }
  73237. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  73238. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  73239. };
  73240. RayHelper.prototype.dispose = function () {
  73241. this.hide();
  73242. this.detachFromMesh();
  73243. this.ray = null;
  73244. };
  73245. return RayHelper;
  73246. }());
  73247. BABYLON.RayHelper = RayHelper;
  73248. })(BABYLON || (BABYLON = {}));
  73249. //# sourceMappingURL=babylon.rayHelper.js.map
  73250. var BABYLON;
  73251. (function (BABYLON) {
  73252. // load the inspector using require, if not present in the global namespace.
  73253. var DebugLayer = /** @class */ (function () {
  73254. function DebugLayer(scene) {
  73255. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73256. this._scene = scene;
  73257. // load inspector using require, if it doesn't exist on the global namespace.
  73258. }
  73259. /** Creates the inspector window. */
  73260. DebugLayer.prototype._createInspector = function (config) {
  73261. if (config === void 0) { config = {}; }
  73262. var popup = config.popup || false;
  73263. var initialTab = config.initialTab || 0;
  73264. var parentElement = config.parentElement || null;
  73265. if (!this._inspector) {
  73266. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73267. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  73268. } // else nothing to do,; instance is already existing
  73269. };
  73270. DebugLayer.prototype.isVisible = function () {
  73271. if (!this._inspector) {
  73272. return false;
  73273. }
  73274. return true;
  73275. };
  73276. DebugLayer.prototype.hide = function () {
  73277. if (this._inspector) {
  73278. try {
  73279. this._inspector.dispose();
  73280. }
  73281. catch (e) {
  73282. // If the inspector has been removed directly from the inspector tool
  73283. }
  73284. this._inspector = null;
  73285. }
  73286. };
  73287. DebugLayer.prototype.show = function (config) {
  73288. if (config === void 0) { config = {}; }
  73289. if (typeof this.BJSINSPECTOR == 'undefined') {
  73290. // Load inspector and add it to the DOM
  73291. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  73292. }
  73293. else {
  73294. // Otherwise creates the inspector
  73295. this._createInspector(config);
  73296. }
  73297. };
  73298. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  73299. return DebugLayer;
  73300. }());
  73301. BABYLON.DebugLayer = DebugLayer;
  73302. })(BABYLON || (BABYLON = {}));
  73303. //# sourceMappingURL=babylon.debugLayer.js.map
  73304. var BABYLON;
  73305. (function (BABYLON) {
  73306. var BoundingBoxRenderer = /** @class */ (function () {
  73307. function BoundingBoxRenderer(scene) {
  73308. this.frontColor = new BABYLON.Color3(1, 1, 1);
  73309. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  73310. this.showBackLines = true;
  73311. this.renderList = new BABYLON.SmartArray(32);
  73312. this._vertexBuffers = {};
  73313. this._scene = scene;
  73314. }
  73315. BoundingBoxRenderer.prototype._prepareRessources = function () {
  73316. if (this._colorShader) {
  73317. return;
  73318. }
  73319. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  73320. attributes: [BABYLON.VertexBuffer.PositionKind],
  73321. uniforms: ["world", "viewProjection", "color"]
  73322. });
  73323. var engine = this._scene.getEngine();
  73324. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  73325. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  73326. this._createIndexBuffer();
  73327. };
  73328. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  73329. var engine = this._scene.getEngine();
  73330. 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]);
  73331. };
  73332. BoundingBoxRenderer.prototype._rebuild = function () {
  73333. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73334. if (vb) {
  73335. vb._rebuild();
  73336. }
  73337. this._createIndexBuffer();
  73338. };
  73339. BoundingBoxRenderer.prototype.reset = function () {
  73340. this.renderList.reset();
  73341. };
  73342. BoundingBoxRenderer.prototype.render = function () {
  73343. if (this.renderList.length === 0) {
  73344. return;
  73345. }
  73346. this._prepareRessources();
  73347. if (!this._colorShader.isReady()) {
  73348. return;
  73349. }
  73350. var engine = this._scene.getEngine();
  73351. engine.setDepthWrite(false);
  73352. this._colorShader._preBind();
  73353. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  73354. var boundingBox = this.renderList.data[boundingBoxIndex];
  73355. var min = boundingBox.minimum;
  73356. var max = boundingBox.maximum;
  73357. var diff = max.subtract(min);
  73358. var median = min.add(diff.scale(0.5));
  73359. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73360. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73361. .multiply(boundingBox.getWorldMatrix());
  73362. // VBOs
  73363. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73364. if (this.showBackLines) {
  73365. // Back
  73366. engine.setDepthFunctionToGreaterOrEqual();
  73367. this._scene.resetCachedMaterial();
  73368. this._colorShader.setColor4("color", this.backColor.toColor4());
  73369. this._colorShader.bind(worldMatrix);
  73370. // Draw order
  73371. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73372. }
  73373. // Front
  73374. engine.setDepthFunctionToLess();
  73375. this._scene.resetCachedMaterial();
  73376. this._colorShader.setColor4("color", this.frontColor.toColor4());
  73377. this._colorShader.bind(worldMatrix);
  73378. // Draw order
  73379. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73380. }
  73381. this._colorShader.unbind();
  73382. engine.setDepthFunctionToLessOrEqual();
  73383. engine.setDepthWrite(true);
  73384. };
  73385. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  73386. this._prepareRessources();
  73387. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  73388. return;
  73389. }
  73390. var engine = this._scene.getEngine();
  73391. engine.setDepthWrite(false);
  73392. engine.setColorWrite(false);
  73393. this._colorShader._preBind();
  73394. var boundingBox = mesh._boundingInfo.boundingBox;
  73395. var min = boundingBox.minimum;
  73396. var max = boundingBox.maximum;
  73397. var diff = max.subtract(min);
  73398. var median = min.add(diff.scale(0.5));
  73399. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73400. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73401. .multiply(boundingBox.getWorldMatrix());
  73402. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73403. engine.setDepthFunctionToLess();
  73404. this._scene.resetCachedMaterial();
  73405. this._colorShader.bind(worldMatrix);
  73406. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73407. this._colorShader.unbind();
  73408. engine.setDepthFunctionToLessOrEqual();
  73409. engine.setDepthWrite(true);
  73410. engine.setColorWrite(true);
  73411. };
  73412. BoundingBoxRenderer.prototype.dispose = function () {
  73413. if (!this._colorShader) {
  73414. return;
  73415. }
  73416. this.renderList.dispose();
  73417. this._colorShader.dispose();
  73418. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73419. if (buffer) {
  73420. buffer.dispose();
  73421. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73422. }
  73423. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73424. };
  73425. return BoundingBoxRenderer;
  73426. }());
  73427. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  73428. })(BABYLON || (BABYLON = {}));
  73429. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  73430. var BABYLON;
  73431. (function (BABYLON) {
  73432. var MorphTarget = /** @class */ (function () {
  73433. function MorphTarget(name, influence) {
  73434. if (influence === void 0) { influence = 0; }
  73435. this.name = name;
  73436. this.animations = new Array();
  73437. this._positions = null;
  73438. this._normals = null;
  73439. this._tangents = null;
  73440. this.onInfluenceChanged = new BABYLON.Observable();
  73441. this.influence = influence;
  73442. }
  73443. Object.defineProperty(MorphTarget.prototype, "influence", {
  73444. get: function () {
  73445. return this._influence;
  73446. },
  73447. set: function (influence) {
  73448. if (this._influence === influence) {
  73449. return;
  73450. }
  73451. var previous = this._influence;
  73452. this._influence = influence;
  73453. if (this.onInfluenceChanged.hasObservers) {
  73454. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  73455. }
  73456. },
  73457. enumerable: true,
  73458. configurable: true
  73459. });
  73460. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  73461. get: function () {
  73462. return !!this._positions;
  73463. },
  73464. enumerable: true,
  73465. configurable: true
  73466. });
  73467. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  73468. get: function () {
  73469. return !!this._normals;
  73470. },
  73471. enumerable: true,
  73472. configurable: true
  73473. });
  73474. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  73475. get: function () {
  73476. return !!this._tangents;
  73477. },
  73478. enumerable: true,
  73479. configurable: true
  73480. });
  73481. MorphTarget.prototype.setPositions = function (data) {
  73482. this._positions = data;
  73483. };
  73484. MorphTarget.prototype.getPositions = function () {
  73485. return this._positions;
  73486. };
  73487. MorphTarget.prototype.setNormals = function (data) {
  73488. this._normals = data;
  73489. };
  73490. MorphTarget.prototype.getNormals = function () {
  73491. return this._normals;
  73492. };
  73493. MorphTarget.prototype.setTangents = function (data) {
  73494. this._tangents = data;
  73495. };
  73496. MorphTarget.prototype.getTangents = function () {
  73497. return this._tangents;
  73498. };
  73499. /**
  73500. * Serializes the current target into a Serialization object.
  73501. * Returns the serialized object.
  73502. */
  73503. MorphTarget.prototype.serialize = function () {
  73504. var serializationObject = {};
  73505. serializationObject.name = this.name;
  73506. serializationObject.influence = this.influence;
  73507. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  73508. if (this.hasNormals) {
  73509. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  73510. }
  73511. if (this.hasTangents) {
  73512. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  73513. }
  73514. // Animations
  73515. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  73516. return serializationObject;
  73517. };
  73518. // Statics
  73519. MorphTarget.Parse = function (serializationObject) {
  73520. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  73521. result.setPositions(serializationObject.positions);
  73522. if (serializationObject.normals) {
  73523. result.setNormals(serializationObject.normals);
  73524. }
  73525. if (serializationObject.tangents) {
  73526. result.setTangents(serializationObject.tangents);
  73527. }
  73528. // Animations
  73529. if (serializationObject.animations) {
  73530. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  73531. var parsedAnimation = serializationObject.animations[animationIndex];
  73532. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  73533. }
  73534. }
  73535. return result;
  73536. };
  73537. MorphTarget.FromMesh = function (mesh, name, influence) {
  73538. if (!name) {
  73539. name = mesh.name;
  73540. }
  73541. var result = new MorphTarget(name, influence);
  73542. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  73543. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73544. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  73545. }
  73546. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  73547. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  73548. }
  73549. return result;
  73550. };
  73551. return MorphTarget;
  73552. }());
  73553. BABYLON.MorphTarget = MorphTarget;
  73554. })(BABYLON || (BABYLON = {}));
  73555. //# sourceMappingURL=babylon.morphTarget.js.map
  73556. var BABYLON;
  73557. (function (BABYLON) {
  73558. var MorphTargetManager = /** @class */ (function () {
  73559. function MorphTargetManager(scene) {
  73560. if (scene === void 0) { scene = null; }
  73561. this._targets = new Array();
  73562. this._targetObservable = new Array();
  73563. this._activeTargets = new BABYLON.SmartArray(16);
  73564. this._supportsNormals = false;
  73565. this._supportsTangents = false;
  73566. this._vertexCount = 0;
  73567. this._uniqueId = 0;
  73568. this._tempInfluences = new Array();
  73569. if (!scene) {
  73570. scene = BABYLON.Engine.LastCreatedScene;
  73571. }
  73572. this._scene = scene;
  73573. if (this._scene) {
  73574. this._scene.morphTargetManagers.push(this);
  73575. this._uniqueId = this._scene.getUniqueId();
  73576. }
  73577. }
  73578. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  73579. get: function () {
  73580. return this._uniqueId;
  73581. },
  73582. enumerable: true,
  73583. configurable: true
  73584. });
  73585. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  73586. get: function () {
  73587. return this._vertexCount;
  73588. },
  73589. enumerable: true,
  73590. configurable: true
  73591. });
  73592. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  73593. get: function () {
  73594. return this._supportsNormals;
  73595. },
  73596. enumerable: true,
  73597. configurable: true
  73598. });
  73599. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  73600. get: function () {
  73601. return this._supportsTangents;
  73602. },
  73603. enumerable: true,
  73604. configurable: true
  73605. });
  73606. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  73607. get: function () {
  73608. return this._targets.length;
  73609. },
  73610. enumerable: true,
  73611. configurable: true
  73612. });
  73613. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  73614. get: function () {
  73615. return this._activeTargets.length;
  73616. },
  73617. enumerable: true,
  73618. configurable: true
  73619. });
  73620. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  73621. get: function () {
  73622. return this._influences;
  73623. },
  73624. enumerable: true,
  73625. configurable: true
  73626. });
  73627. MorphTargetManager.prototype.getActiveTarget = function (index) {
  73628. return this._activeTargets.data[index];
  73629. };
  73630. MorphTargetManager.prototype.getTarget = function (index) {
  73631. return this._targets[index];
  73632. };
  73633. MorphTargetManager.prototype.addTarget = function (target) {
  73634. var _this = this;
  73635. this._targets.push(target);
  73636. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  73637. _this._syncActiveTargets(needUpdate);
  73638. }));
  73639. this._syncActiveTargets(true);
  73640. };
  73641. MorphTargetManager.prototype.removeTarget = function (target) {
  73642. var index = this._targets.indexOf(target);
  73643. if (index >= 0) {
  73644. this._targets.splice(index, 1);
  73645. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  73646. this._syncActiveTargets(true);
  73647. }
  73648. };
  73649. /**
  73650. * Serializes the current manager into a Serialization object.
  73651. * Returns the serialized object.
  73652. */
  73653. MorphTargetManager.prototype.serialize = function () {
  73654. var serializationObject = {};
  73655. serializationObject.id = this.uniqueId;
  73656. serializationObject.targets = [];
  73657. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  73658. var target = _a[_i];
  73659. serializationObject.targets.push(target.serialize());
  73660. }
  73661. return serializationObject;
  73662. };
  73663. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  73664. var influenceCount = 0;
  73665. this._activeTargets.reset();
  73666. this._supportsNormals = true;
  73667. this._supportsTangents = true;
  73668. this._vertexCount = 0;
  73669. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  73670. var target = _a[_i];
  73671. this._activeTargets.push(target);
  73672. this._tempInfluences[influenceCount++] = target.influence;
  73673. var positions = target.getPositions();
  73674. if (positions) {
  73675. this._supportsNormals = this._supportsNormals && target.hasNormals;
  73676. this._supportsTangents = this._supportsTangents && target.hasTangents;
  73677. var vertexCount = positions.length / 3;
  73678. if (this._vertexCount === 0) {
  73679. this._vertexCount = vertexCount;
  73680. }
  73681. else if (this._vertexCount !== vertexCount) {
  73682. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  73683. return;
  73684. }
  73685. }
  73686. }
  73687. if (!this._influences || this._influences.length !== influenceCount) {
  73688. this._influences = new Float32Array(influenceCount);
  73689. }
  73690. for (var index = 0; index < influenceCount; index++) {
  73691. this._influences[index] = this._tempInfluences[index];
  73692. }
  73693. if (needUpdate && this._scene) {
  73694. // Flag meshes as dirty to resync with the active targets
  73695. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  73696. var mesh = _c[_b];
  73697. if (mesh.morphTargetManager === this) {
  73698. mesh._syncGeometryWithMorphTargetManager();
  73699. }
  73700. }
  73701. }
  73702. };
  73703. // Statics
  73704. MorphTargetManager.Parse = function (serializationObject, scene) {
  73705. var result = new MorphTargetManager(scene);
  73706. result._uniqueId = serializationObject.id;
  73707. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  73708. var targetData = _a[_i];
  73709. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  73710. }
  73711. return result;
  73712. };
  73713. return MorphTargetManager;
  73714. }());
  73715. BABYLON.MorphTargetManager = MorphTargetManager;
  73716. })(BABYLON || (BABYLON = {}));
  73717. //# sourceMappingURL=babylon.morphTargetManager.js.map
  73718. var BABYLON;
  73719. (function (BABYLON) {
  73720. var Octree = /** @class */ (function () {
  73721. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  73722. if (maxDepth === void 0) { maxDepth = 2; }
  73723. this.maxDepth = maxDepth;
  73724. this.dynamicContent = new Array();
  73725. this._maxBlockCapacity = maxBlockCapacity || 64;
  73726. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  73727. this._creationFunc = creationFunc;
  73728. }
  73729. // Methods
  73730. Octree.prototype.update = function (worldMin, worldMax, entries) {
  73731. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  73732. };
  73733. Octree.prototype.addMesh = function (entry) {
  73734. for (var index = 0; index < this.blocks.length; index++) {
  73735. var block = this.blocks[index];
  73736. block.addEntry(entry);
  73737. }
  73738. };
  73739. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  73740. this._selectionContent.reset();
  73741. for (var index = 0; index < this.blocks.length; index++) {
  73742. var block = this.blocks[index];
  73743. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  73744. }
  73745. if (allowDuplicate) {
  73746. this._selectionContent.concat(this.dynamicContent);
  73747. }
  73748. else {
  73749. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73750. }
  73751. return this._selectionContent;
  73752. };
  73753. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  73754. this._selectionContent.reset();
  73755. for (var index = 0; index < this.blocks.length; index++) {
  73756. var block = this.blocks[index];
  73757. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  73758. }
  73759. if (allowDuplicate) {
  73760. this._selectionContent.concat(this.dynamicContent);
  73761. }
  73762. else {
  73763. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73764. }
  73765. return this._selectionContent;
  73766. };
  73767. Octree.prototype.intersectsRay = function (ray) {
  73768. this._selectionContent.reset();
  73769. for (var index = 0; index < this.blocks.length; index++) {
  73770. var block = this.blocks[index];
  73771. block.intersectsRay(ray, this._selectionContent);
  73772. }
  73773. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73774. return this._selectionContent;
  73775. };
  73776. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  73777. target.blocks = new Array();
  73778. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  73779. // Segmenting space
  73780. for (var x = 0; x < 2; x++) {
  73781. for (var y = 0; y < 2; y++) {
  73782. for (var z = 0; z < 2; z++) {
  73783. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  73784. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  73785. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  73786. block.addEntries(entries);
  73787. target.blocks.push(block);
  73788. }
  73789. }
  73790. }
  73791. };
  73792. Octree.CreationFuncForMeshes = function (entry, block) {
  73793. var boundingInfo = entry.getBoundingInfo();
  73794. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  73795. block.entries.push(entry);
  73796. }
  73797. };
  73798. Octree.CreationFuncForSubMeshes = function (entry, block) {
  73799. var boundingInfo = entry.getBoundingInfo();
  73800. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  73801. block.entries.push(entry);
  73802. }
  73803. };
  73804. return Octree;
  73805. }());
  73806. BABYLON.Octree = Octree;
  73807. })(BABYLON || (BABYLON = {}));
  73808. //# sourceMappingURL=babylon.octree.js.map
  73809. var BABYLON;
  73810. (function (BABYLON) {
  73811. var OctreeBlock = /** @class */ (function () {
  73812. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  73813. this.entries = new Array();
  73814. this._boundingVectors = new Array();
  73815. this._capacity = capacity;
  73816. this._depth = depth;
  73817. this._maxDepth = maxDepth;
  73818. this._creationFunc = creationFunc;
  73819. this._minPoint = minPoint;
  73820. this._maxPoint = maxPoint;
  73821. this._boundingVectors.push(minPoint.clone());
  73822. this._boundingVectors.push(maxPoint.clone());
  73823. this._boundingVectors.push(minPoint.clone());
  73824. this._boundingVectors[2].x = maxPoint.x;
  73825. this._boundingVectors.push(minPoint.clone());
  73826. this._boundingVectors[3].y = maxPoint.y;
  73827. this._boundingVectors.push(minPoint.clone());
  73828. this._boundingVectors[4].z = maxPoint.z;
  73829. this._boundingVectors.push(maxPoint.clone());
  73830. this._boundingVectors[5].z = minPoint.z;
  73831. this._boundingVectors.push(maxPoint.clone());
  73832. this._boundingVectors[6].x = minPoint.x;
  73833. this._boundingVectors.push(maxPoint.clone());
  73834. this._boundingVectors[7].y = minPoint.y;
  73835. }
  73836. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  73837. // Property
  73838. get: function () {
  73839. return this._capacity;
  73840. },
  73841. enumerable: true,
  73842. configurable: true
  73843. });
  73844. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  73845. get: function () {
  73846. return this._minPoint;
  73847. },
  73848. enumerable: true,
  73849. configurable: true
  73850. });
  73851. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  73852. get: function () {
  73853. return this._maxPoint;
  73854. },
  73855. enumerable: true,
  73856. configurable: true
  73857. });
  73858. // Methods
  73859. OctreeBlock.prototype.addEntry = function (entry) {
  73860. if (this.blocks) {
  73861. for (var index = 0; index < this.blocks.length; index++) {
  73862. var block = this.blocks[index];
  73863. block.addEntry(entry);
  73864. }
  73865. return;
  73866. }
  73867. this._creationFunc(entry, this);
  73868. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  73869. this.createInnerBlocks();
  73870. }
  73871. };
  73872. OctreeBlock.prototype.addEntries = function (entries) {
  73873. for (var index = 0; index < entries.length; index++) {
  73874. var mesh = entries[index];
  73875. this.addEntry(mesh);
  73876. }
  73877. };
  73878. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  73879. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  73880. if (this.blocks) {
  73881. for (var index = 0; index < this.blocks.length; index++) {
  73882. var block = this.blocks[index];
  73883. block.select(frustumPlanes, selection, allowDuplicate);
  73884. }
  73885. return;
  73886. }
  73887. if (allowDuplicate) {
  73888. selection.concat(this.entries);
  73889. }
  73890. else {
  73891. selection.concatWithNoDuplicate(this.entries);
  73892. }
  73893. }
  73894. };
  73895. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  73896. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  73897. if (this.blocks) {
  73898. for (var index = 0; index < this.blocks.length; index++) {
  73899. var block = this.blocks[index];
  73900. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  73901. }
  73902. return;
  73903. }
  73904. if (allowDuplicate) {
  73905. selection.concat(this.entries);
  73906. }
  73907. else {
  73908. selection.concatWithNoDuplicate(this.entries);
  73909. }
  73910. }
  73911. };
  73912. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  73913. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  73914. if (this.blocks) {
  73915. for (var index = 0; index < this.blocks.length; index++) {
  73916. var block = this.blocks[index];
  73917. block.intersectsRay(ray, selection);
  73918. }
  73919. return;
  73920. }
  73921. selection.concatWithNoDuplicate(this.entries);
  73922. }
  73923. };
  73924. OctreeBlock.prototype.createInnerBlocks = function () {
  73925. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  73926. };
  73927. return OctreeBlock;
  73928. }());
  73929. BABYLON.OctreeBlock = OctreeBlock;
  73930. })(BABYLON || (BABYLON = {}));
  73931. //# sourceMappingURL=babylon.octreeBlock.js.map
  73932. var BABYLON;
  73933. (function (BABYLON) {
  73934. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  73935. __extends(VRDistortionCorrectionPostProcess, _super);
  73936. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  73937. var _this = _super.call(this, name, "vrDistortionCorrection", [
  73938. 'LensCenter',
  73939. 'Scale',
  73940. 'ScaleIn',
  73941. 'HmdWarpParam'
  73942. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  73943. _this._isRightEye = isRightEye;
  73944. _this._distortionFactors = vrMetrics.distortionK;
  73945. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  73946. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  73947. _this.adaptScaleToCurrentViewport = true;
  73948. _this.onSizeChangedObservable.add(function () {
  73949. _this.aspectRatio = _this.width * .5 / _this.height;
  73950. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  73951. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  73952. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  73953. });
  73954. _this.onApplyObservable.add(function (effect) {
  73955. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  73956. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  73957. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  73958. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  73959. });
  73960. return _this;
  73961. }
  73962. return VRDistortionCorrectionPostProcess;
  73963. }(BABYLON.PostProcess));
  73964. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  73965. })(BABYLON || (BABYLON = {}));
  73966. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  73967. var BABYLON;
  73968. (function (BABYLON) {
  73969. var AnaglyphPostProcess = /** @class */ (function (_super) {
  73970. __extends(AnaglyphPostProcess, _super);
  73971. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  73972. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  73973. _this._passedProcess = rigCameras[0]._rigPostProcess;
  73974. _this.onApplyObservable.add(function (effect) {
  73975. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  73976. });
  73977. return _this;
  73978. }
  73979. return AnaglyphPostProcess;
  73980. }(BABYLON.PostProcess));
  73981. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  73982. })(BABYLON || (BABYLON = {}));
  73983. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  73984. var BABYLON;
  73985. (function (BABYLON) {
  73986. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  73987. __extends(StereoscopicInterlacePostProcess, _super);
  73988. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  73989. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  73990. _this._passedProcess = rigCameras[0]._rigPostProcess;
  73991. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  73992. _this.onSizeChangedObservable.add(function () {
  73993. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  73994. });
  73995. _this.onApplyObservable.add(function (effect) {
  73996. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  73997. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  73998. });
  73999. return _this;
  74000. }
  74001. return StereoscopicInterlacePostProcess;
  74002. }(BABYLON.PostProcess));
  74003. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  74004. })(BABYLON || (BABYLON = {}));
  74005. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  74006. var BABYLON;
  74007. (function (BABYLON) {
  74008. /**
  74009. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  74010. * Screen rotation is taken into account.
  74011. */
  74012. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  74013. function FreeCameraDeviceOrientationInput() {
  74014. var _this = this;
  74015. this._screenOrientationAngle = 0;
  74016. this._screenQuaternion = new BABYLON.Quaternion();
  74017. this._alpha = 0;
  74018. this._beta = 0;
  74019. this._gamma = 0;
  74020. this._orientationChanged = function () {
  74021. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  74022. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  74023. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  74024. };
  74025. this._deviceOrientation = function (evt) {
  74026. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  74027. _this._beta = evt.beta !== null ? evt.beta : 0;
  74028. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  74029. };
  74030. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  74031. this._orientationChanged();
  74032. }
  74033. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  74034. get: function () {
  74035. return this._camera;
  74036. },
  74037. set: function (camera) {
  74038. this._camera = camera;
  74039. if (this._camera != null && !this._camera.rotationQuaternion) {
  74040. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  74041. }
  74042. },
  74043. enumerable: true,
  74044. configurable: true
  74045. });
  74046. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74047. window.addEventListener("orientationchange", this._orientationChanged);
  74048. window.addEventListener("deviceorientation", this._deviceOrientation);
  74049. //In certain cases, the attach control is called AFTER orientation was changed,
  74050. //So this is needed.
  74051. this._orientationChanged();
  74052. };
  74053. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  74054. window.removeEventListener("orientationchange", this._orientationChanged);
  74055. window.removeEventListener("deviceorientation", this._deviceOrientation);
  74056. };
  74057. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  74058. //if no device orientation provided, don't update the rotation.
  74059. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  74060. if (!this._alpha)
  74061. return;
  74062. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  74063. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  74064. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  74065. //Mirror on XY Plane
  74066. this._camera.rotationQuaternion.z *= -1;
  74067. this._camera.rotationQuaternion.w *= -1;
  74068. };
  74069. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  74070. return "FreeCameraDeviceOrientationInput";
  74071. };
  74072. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  74073. return "deviceOrientation";
  74074. };
  74075. return FreeCameraDeviceOrientationInput;
  74076. }());
  74077. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  74078. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  74079. })(BABYLON || (BABYLON = {}));
  74080. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  74081. var BABYLON;
  74082. (function (BABYLON) {
  74083. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  74084. function ArcRotateCameraVRDeviceOrientationInput() {
  74085. this.alphaCorrection = 1;
  74086. this.betaCorrection = 1;
  74087. this.gammaCorrection = 1;
  74088. this._alpha = 0;
  74089. this._gamma = 0;
  74090. this._dirty = false;
  74091. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  74092. }
  74093. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74094. this.camera.attachControl(element, noPreventDefault);
  74095. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  74096. };
  74097. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  74098. if (evt.alpha !== null) {
  74099. this._alpha = +evt.alpha | 0;
  74100. }
  74101. if (evt.gamma !== null) {
  74102. this._gamma = +evt.gamma | 0;
  74103. }
  74104. this._dirty = true;
  74105. };
  74106. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  74107. if (this._dirty) {
  74108. this._dirty = false;
  74109. if (this._gamma < 0) {
  74110. this._gamma = 180 + this._gamma;
  74111. }
  74112. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  74113. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  74114. }
  74115. };
  74116. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  74117. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  74118. };
  74119. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  74120. return "ArcRotateCameraVRDeviceOrientationInput";
  74121. };
  74122. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  74123. return "VRDeviceOrientation";
  74124. };
  74125. return ArcRotateCameraVRDeviceOrientationInput;
  74126. }());
  74127. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  74128. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  74129. })(BABYLON || (BABYLON = {}));
  74130. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  74131. var BABYLON;
  74132. (function (BABYLON) {
  74133. var VRCameraMetrics = /** @class */ (function () {
  74134. function VRCameraMetrics() {
  74135. this.compensateDistortion = true;
  74136. }
  74137. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  74138. get: function () {
  74139. return this.hResolution / (2 * this.vResolution);
  74140. },
  74141. enumerable: true,
  74142. configurable: true
  74143. });
  74144. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  74145. get: function () {
  74146. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  74147. },
  74148. enumerable: true,
  74149. configurable: true
  74150. });
  74151. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  74152. get: function () {
  74153. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74154. var h = (4 * meters) / this.hScreenSize;
  74155. return BABYLON.Matrix.Translation(h, 0, 0);
  74156. },
  74157. enumerable: true,
  74158. configurable: true
  74159. });
  74160. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  74161. get: function () {
  74162. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74163. var h = (4 * meters) / this.hScreenSize;
  74164. return BABYLON.Matrix.Translation(-h, 0, 0);
  74165. },
  74166. enumerable: true,
  74167. configurable: true
  74168. });
  74169. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  74170. get: function () {
  74171. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  74172. },
  74173. enumerable: true,
  74174. configurable: true
  74175. });
  74176. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  74177. get: function () {
  74178. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  74179. },
  74180. enumerable: true,
  74181. configurable: true
  74182. });
  74183. VRCameraMetrics.GetDefault = function () {
  74184. var result = new VRCameraMetrics();
  74185. result.hResolution = 1280;
  74186. result.vResolution = 800;
  74187. result.hScreenSize = 0.149759993;
  74188. result.vScreenSize = 0.0935999975;
  74189. result.vScreenCenter = 0.0467999987;
  74190. result.eyeToScreenDistance = 0.0410000011;
  74191. result.lensSeparationDistance = 0.0635000020;
  74192. result.interpupillaryDistance = 0.0640000030;
  74193. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  74194. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  74195. result.postProcessScaleFactor = 1.714605507808412;
  74196. result.lensCenterOffset = 0.151976421;
  74197. return result;
  74198. };
  74199. return VRCameraMetrics;
  74200. }());
  74201. BABYLON.VRCameraMetrics = VRCameraMetrics;
  74202. })(BABYLON || (BABYLON = {}));
  74203. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  74204. var BABYLON;
  74205. (function (BABYLON) {
  74206. /**
  74207. * This represents a WebVR camera.
  74208. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  74209. * @example http://doc.babylonjs.com/how_to/webvr_camera
  74210. */
  74211. var WebVRFreeCamera = /** @class */ (function (_super) {
  74212. __extends(WebVRFreeCamera, _super);
  74213. /**
  74214. * Instantiates a WebVRFreeCamera.
  74215. * @param name The name of the WebVRFreeCamera
  74216. * @param position The starting anchor position for the camera
  74217. * @param scene The scene the camera belongs to
  74218. * @param webVROptions a set of customizable options for the webVRCamera
  74219. */
  74220. function WebVRFreeCamera(name, position, scene, webVROptions) {
  74221. if (webVROptions === void 0) { webVROptions = {}; }
  74222. var _this = _super.call(this, name, position, scene) || this;
  74223. _this.webVROptions = webVROptions;
  74224. /**
  74225. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  74226. */
  74227. _this._vrDevice = null;
  74228. /**
  74229. * The rawPose of the vrDevice.
  74230. */
  74231. _this.rawPose = null;
  74232. _this._specsVersion = "1.1";
  74233. _this._attached = false;
  74234. _this._descendants = [];
  74235. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74236. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74237. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  74238. _this._standingMatrix = null;
  74239. /**
  74240. * Represents device position in babylon space.
  74241. */
  74242. _this.devicePosition = BABYLON.Vector3.Zero();
  74243. /**
  74244. * Represents device rotation in babylon space.
  74245. */
  74246. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  74247. /**
  74248. * The scale of the device to be used when translating from device space to babylon space.
  74249. */
  74250. _this.deviceScaleFactor = 1;
  74251. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74252. _this._worldToDevice = BABYLON.Matrix.Identity();
  74253. /**
  74254. * References to the webVR controllers for the vrDevice.
  74255. */
  74256. _this.controllers = [];
  74257. /**
  74258. * Emits an event when a controller is attached.
  74259. */
  74260. _this.onControllersAttachedObservable = new BABYLON.Observable();
  74261. /**
  74262. * Emits an event when a controller's mesh has been loaded;
  74263. */
  74264. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  74265. /**
  74266. * If the rig cameras be used as parent instead of this camera.
  74267. */
  74268. _this.rigParenting = true;
  74269. _this._defaultHeight = undefined;
  74270. _this._workingVector = BABYLON.Vector3.Zero();
  74271. _this._oneVector = BABYLON.Vector3.One();
  74272. _this._workingMatrix = BABYLON.Matrix.Identity();
  74273. _this._cache.position = BABYLON.Vector3.Zero();
  74274. if (webVROptions.defaultHeight) {
  74275. _this._defaultHeight = webVROptions.defaultHeight;
  74276. _this.position.y = _this._defaultHeight;
  74277. }
  74278. _this.minZ = 0.1;
  74279. //legacy support - the compensation boolean was removed.
  74280. if (arguments.length === 5) {
  74281. _this.webVROptions = arguments[4];
  74282. }
  74283. // default webVR options
  74284. if (_this.webVROptions.trackPosition == undefined) {
  74285. _this.webVROptions.trackPosition = true;
  74286. }
  74287. if (_this.webVROptions.controllerMeshes == undefined) {
  74288. _this.webVROptions.controllerMeshes = true;
  74289. }
  74290. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  74291. _this.webVROptions.defaultLightingOnControllers = true;
  74292. }
  74293. _this.rotationQuaternion = new BABYLON.Quaternion();
  74294. if (_this.webVROptions && _this.webVROptions.positionScale) {
  74295. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  74296. }
  74297. //enable VR
  74298. var engine = _this.getEngine();
  74299. _this._onVREnabled = function (success) { if (success) {
  74300. _this.initControllers();
  74301. } };
  74302. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  74303. engine.initWebVR().add(function (event) {
  74304. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  74305. return;
  74306. }
  74307. _this._vrDevice = event.vrDisplay;
  74308. //reset the rig parameters.
  74309. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  74310. if (_this._attached) {
  74311. _this.getEngine().enableVR();
  74312. }
  74313. });
  74314. if (typeof (VRFrameData) !== "undefined")
  74315. _this._frameData = new VRFrameData();
  74316. /**
  74317. * The idea behind the following lines:
  74318. * objects that have the camera as parent should actually have the rig cameras as a parent.
  74319. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  74320. * the second will not show it correctly.
  74321. *
  74322. * To solve this - each object that has the camera as parent will be added to a protected array.
  74323. * When the rig camera renders, it will take this array and set all of those to be its children.
  74324. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  74325. * Amazing!
  74326. */
  74327. scene.onBeforeCameraRenderObservable.add(function (camera) {
  74328. if (camera.parent === _this && _this.rigParenting) {
  74329. _this._descendants = _this.getDescendants(true, function (n) {
  74330. // don't take the cameras or the controllers!
  74331. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  74332. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  74333. return !isController && !isRigCamera;
  74334. });
  74335. _this._descendants.forEach(function (node) {
  74336. node.parent = camera;
  74337. });
  74338. }
  74339. });
  74340. scene.onAfterCameraRenderObservable.add(function (camera) {
  74341. if (camera.parent === _this && _this.rigParenting) {
  74342. _this._descendants.forEach(function (node) {
  74343. node.parent = _this;
  74344. });
  74345. }
  74346. });
  74347. return _this;
  74348. }
  74349. /**
  74350. * Gets the device distance from the ground.
  74351. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  74352. */
  74353. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  74354. if (this._standingMatrix && this._defaultHeight === undefined) {
  74355. // Add standing matrix offset to get real offset from ground in room
  74356. this._standingMatrix.getTranslationToRef(this._workingVector);
  74357. return this._deviceRoomPosition.y + this._workingVector.y;
  74358. }
  74359. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  74360. return this._defaultHeight || 0;
  74361. };
  74362. /**
  74363. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  74364. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  74365. */
  74366. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  74367. var _this = this;
  74368. if (callback === void 0) { callback = function (bool) { }; }
  74369. // Use standing matrix if available
  74370. if (!navigator || !navigator.getVRDisplays) {
  74371. callback(false);
  74372. }
  74373. else {
  74374. navigator.getVRDisplays().then(function (displays) {
  74375. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  74376. callback(false);
  74377. }
  74378. else {
  74379. _this._standingMatrix = new BABYLON.Matrix();
  74380. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  74381. if (!_this.getScene().useRightHandedSystem) {
  74382. [2, 6, 8, 9, 14].forEach(function (num) {
  74383. if (_this._standingMatrix) {
  74384. _this._standingMatrix.m[num] *= -1;
  74385. }
  74386. });
  74387. }
  74388. callback(true);
  74389. }
  74390. });
  74391. }
  74392. };
  74393. /**
  74394. * Disposes the camera
  74395. */
  74396. WebVRFreeCamera.prototype.dispose = function () {
  74397. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  74398. _super.prototype.dispose.call(this);
  74399. };
  74400. /**
  74401. * Gets a vrController by name.
  74402. * @param name The name of the controller to retreive
  74403. * @returns the controller matching the name specified or null if not found
  74404. */
  74405. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  74406. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  74407. var gp = _a[_i];
  74408. if (gp.hand === name) {
  74409. return gp;
  74410. }
  74411. }
  74412. return null;
  74413. };
  74414. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  74415. /**
  74416. * The controller corrisponding to the users left hand.
  74417. */
  74418. get: function () {
  74419. if (!this._leftController) {
  74420. this._leftController = this.getControllerByName("left");
  74421. }
  74422. return this._leftController;
  74423. },
  74424. enumerable: true,
  74425. configurable: true
  74426. });
  74427. ;
  74428. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  74429. /**
  74430. * The controller corrisponding to the users right hand.
  74431. */
  74432. get: function () {
  74433. if (!this._rightController) {
  74434. this._rightController = this.getControllerByName("right");
  74435. }
  74436. return this._rightController;
  74437. },
  74438. enumerable: true,
  74439. configurable: true
  74440. });
  74441. ;
  74442. /**
  74443. * Casts a ray forward from the vrCamera's gaze.
  74444. * @param length Length of the ray (default: 100)
  74445. * @returns the ray corrisponding to the gaze
  74446. */
  74447. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  74448. if (length === void 0) { length = 100; }
  74449. if (this.leftCamera) {
  74450. // Use left eye to avoid computation to compute center on every call
  74451. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  74452. }
  74453. else {
  74454. return _super.prototype.getForwardRay.call(this, length);
  74455. }
  74456. };
  74457. /**
  74458. * Updates the camera based on device's frame data
  74459. */
  74460. WebVRFreeCamera.prototype._checkInputs = function () {
  74461. if (this._vrDevice && this._vrDevice.isPresenting) {
  74462. this._vrDevice.getFrameData(this._frameData);
  74463. this.updateFromDevice(this._frameData.pose);
  74464. }
  74465. _super.prototype._checkInputs.call(this);
  74466. };
  74467. /**
  74468. * Updates the poseControlled values based on the input device pose.
  74469. * @param poseData Pose coming from the device
  74470. */
  74471. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  74472. if (poseData && poseData.orientation) {
  74473. this.rawPose = poseData;
  74474. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  74475. if (this.getScene().useRightHandedSystem) {
  74476. this._deviceRoomRotationQuaternion.z *= -1;
  74477. this._deviceRoomRotationQuaternion.w *= -1;
  74478. }
  74479. if (this.webVROptions.trackPosition && this.rawPose.position) {
  74480. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  74481. if (this.getScene().useRightHandedSystem) {
  74482. this._deviceRoomPosition.z *= -1;
  74483. }
  74484. }
  74485. }
  74486. };
  74487. /**
  74488. * WebVR's attach control will start broadcasting frames to the device.
  74489. * Note that in certain browsers (chrome for example) this function must be called
  74490. * within a user-interaction callback. Example:
  74491. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  74492. *
  74493. * @param element html element to attach the vrDevice to
  74494. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  74495. */
  74496. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  74497. _super.prototype.attachControl.call(this, element, noPreventDefault);
  74498. this._attached = true;
  74499. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  74500. if (this._vrDevice) {
  74501. this.getEngine().enableVR();
  74502. }
  74503. };
  74504. /**
  74505. * Detaches the camera from the html element and disables VR
  74506. *
  74507. * @param element html element to detach from
  74508. */
  74509. WebVRFreeCamera.prototype.detachControl = function (element) {
  74510. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74511. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74512. _super.prototype.detachControl.call(this, element);
  74513. this._attached = false;
  74514. this.getEngine().disableVR();
  74515. };
  74516. /**
  74517. * @returns the name of this class
  74518. */
  74519. WebVRFreeCamera.prototype.getClassName = function () {
  74520. return "WebVRFreeCamera";
  74521. };
  74522. /**
  74523. * Calls resetPose on the vrDisplay
  74524. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  74525. */
  74526. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  74527. //uses the vrDisplay's "resetPose()".
  74528. //pitch and roll won't be affected.
  74529. this._vrDevice.resetPose();
  74530. };
  74531. /**
  74532. * Updates the rig cameras (left and right eye)
  74533. */
  74534. WebVRFreeCamera.prototype._updateRigCameras = function () {
  74535. var camLeft = this._rigCameras[0];
  74536. var camRight = this._rigCameras[1];
  74537. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74538. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74539. camLeft.position.copyFrom(this._deviceRoomPosition);
  74540. camRight.position.copyFrom(this._deviceRoomPosition);
  74541. };
  74542. /**
  74543. * Updates the cached values of the camera
  74544. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  74545. */
  74546. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  74547. var _this = this;
  74548. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  74549. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  74550. if (!this.updateCacheCalled) {
  74551. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  74552. this.updateCacheCalled = true;
  74553. this.update();
  74554. }
  74555. // Set working vector to the device position in room space rotated by the new rotation
  74556. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  74557. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  74558. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  74559. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  74560. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  74561. // Add translation from anchor position
  74562. this._deviceToWorld.getTranslationToRef(this._workingVector);
  74563. this._workingVector.addInPlace(this.position);
  74564. this._workingVector.subtractInPlace(this._cache.position);
  74565. this._deviceToWorld.setTranslation(this._workingVector);
  74566. // Set an inverted matrix to be used when updating the camera
  74567. this._deviceToWorld.invertToRef(this._worldToDevice);
  74568. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  74569. this.controllers.forEach(function (controller) {
  74570. controller._deviceToWorld = _this._deviceToWorld;
  74571. controller.update();
  74572. });
  74573. }
  74574. if (!ignoreParentClass) {
  74575. _super.prototype._updateCache.call(this);
  74576. }
  74577. this.updateCacheCalled = false;
  74578. };
  74579. /**
  74580. * Updates the current device position and rotation in the babylon world
  74581. */
  74582. WebVRFreeCamera.prototype.update = function () {
  74583. // Get current device position in babylon world
  74584. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  74585. // Get current device rotation in babylon world
  74586. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  74587. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  74588. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74589. _super.prototype.update.call(this);
  74590. };
  74591. /**
  74592. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  74593. * @returns an identity matrix
  74594. */
  74595. WebVRFreeCamera.prototype._getViewMatrix = function () {
  74596. return BABYLON.Matrix.Identity();
  74597. };
  74598. /**
  74599. * This function is called by the two RIG cameras.
  74600. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  74601. */
  74602. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  74603. var _this = this;
  74604. //WebVR 1.1
  74605. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  74606. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  74607. if (!this.getScene().useRightHandedSystem) {
  74608. [2, 6, 8, 9, 14].forEach(function (num) {
  74609. _this._webvrViewMatrix.m[num] *= -1;
  74610. });
  74611. }
  74612. // update the camera rotation matrix
  74613. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  74614. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  74615. // Computing target and final matrix
  74616. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  74617. var parentCamera = this._cameraRigParams["parentCamera"];
  74618. // should the view matrix be updated with scale and position offset?
  74619. if (parentCamera.deviceScaleFactor !== 1) {
  74620. this._webvrViewMatrix.invert();
  74621. // scale the position, if set
  74622. if (parentCamera.deviceScaleFactor) {
  74623. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  74624. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  74625. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  74626. }
  74627. this._webvrViewMatrix.invert();
  74628. }
  74629. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  74630. return this._webvrViewMatrix;
  74631. };
  74632. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  74633. var _this = this;
  74634. var parentCamera = this.parent;
  74635. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  74636. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  74637. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  74638. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  74639. //babylon compatible matrix
  74640. if (!this.getScene().useRightHandedSystem) {
  74641. [8, 9, 10, 11].forEach(function (num) {
  74642. _this._projectionMatrix.m[num] *= -1;
  74643. });
  74644. }
  74645. return this._projectionMatrix;
  74646. };
  74647. /**
  74648. * Initializes the controllers and their meshes
  74649. */
  74650. WebVRFreeCamera.prototype.initControllers = function () {
  74651. var _this = this;
  74652. this.controllers = [];
  74653. var manager = this.getScene().gamepadManager;
  74654. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74655. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  74656. var webVrController = gamepad;
  74657. if (webVrController.defaultModel) {
  74658. webVrController.defaultModel.setEnabled(false);
  74659. }
  74660. if (webVrController.hand === "right") {
  74661. _this._rightController = null;
  74662. }
  74663. if (webVrController.hand === "left") {
  74664. _this._rightController = null;
  74665. }
  74666. var controllerIndex = _this.controllers.indexOf(webVrController);
  74667. if (controllerIndex !== -1) {
  74668. _this.controllers.splice(controllerIndex, 1);
  74669. }
  74670. }
  74671. });
  74672. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74673. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  74674. var webVrController_1 = gamepad;
  74675. webVrController_1._deviceToWorld = _this._deviceToWorld;
  74676. if (_this.webVROptions.controllerMeshes) {
  74677. if (webVrController_1.defaultModel) {
  74678. webVrController_1.defaultModel.setEnabled(true);
  74679. }
  74680. else {
  74681. // Load the meshes
  74682. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  74683. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  74684. if (_this.webVROptions.defaultLightingOnControllers) {
  74685. if (!_this._lightOnControllers) {
  74686. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  74687. }
  74688. var activateLightOnSubMeshes_1 = function (mesh, light) {
  74689. var children = mesh.getChildren();
  74690. if (children.length !== 0) {
  74691. children.forEach(function (mesh) {
  74692. light.includedOnlyMeshes.push(mesh);
  74693. activateLightOnSubMeshes_1(mesh, light);
  74694. });
  74695. }
  74696. };
  74697. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  74698. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  74699. }
  74700. });
  74701. }
  74702. }
  74703. webVrController_1.attachToPoseControlledCamera(_this);
  74704. // since this is async - sanity check. Is the controller already stored?
  74705. if (_this.controllers.indexOf(webVrController_1) === -1) {
  74706. //add to the controllers array
  74707. _this.controllers.push(webVrController_1);
  74708. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  74709. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  74710. // So we're overriding setting left & right manually to be sure
  74711. var firstViveWandDetected = false;
  74712. for (var i = 0; i < _this.controllers.length; i++) {
  74713. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  74714. if (!firstViveWandDetected) {
  74715. firstViveWandDetected = true;
  74716. _this.controllers[i].hand = "left";
  74717. }
  74718. else {
  74719. _this.controllers[i].hand = "right";
  74720. }
  74721. }
  74722. }
  74723. //did we find enough controllers? Great! let the developer know.
  74724. if (_this.controllers.length >= 2) {
  74725. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  74726. }
  74727. }
  74728. }
  74729. });
  74730. };
  74731. return WebVRFreeCamera;
  74732. }(BABYLON.FreeCamera));
  74733. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  74734. })(BABYLON || (BABYLON = {}));
  74735. //# sourceMappingURL=babylon.webVRCamera.js.map
  74736. var BABYLON;
  74737. (function (BABYLON) {
  74738. // We're mainly based on the logic defined into the FreeCamera code
  74739. /**
  74740. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  74741. * being tilted forward or back and left or right.
  74742. */
  74743. var DeviceOrientationCamera = /** @class */ (function (_super) {
  74744. __extends(DeviceOrientationCamera, _super);
  74745. /**
  74746. * Creates a new device orientation camera. @see DeviceOrientationCamera
  74747. * @param name The name of the camera
  74748. * @param position The start position camera
  74749. * @param scene The scene the camera belongs to
  74750. */
  74751. function DeviceOrientationCamera(name, position, scene) {
  74752. var _this = _super.call(this, name, position, scene) || this;
  74753. _this._quaternionCache = new BABYLON.Quaternion();
  74754. _this.inputs.addDeviceOrientation();
  74755. return _this;
  74756. }
  74757. /**
  74758. * Gets the current instance class name ("DeviceOrientationCamera").
  74759. * This helps avoiding instanceof at run time.
  74760. * @returns the class name
  74761. */
  74762. DeviceOrientationCamera.prototype.getClassName = function () {
  74763. return "DeviceOrientationCamera";
  74764. };
  74765. /**
  74766. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  74767. */
  74768. DeviceOrientationCamera.prototype._checkInputs = function () {
  74769. _super.prototype._checkInputs.call(this);
  74770. this._quaternionCache.copyFrom(this.rotationQuaternion);
  74771. if (this._initialQuaternion) {
  74772. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  74773. }
  74774. };
  74775. /**
  74776. * Reset the camera to its default orientation on the specified axis only.
  74777. * @param axis The axis to reset
  74778. */
  74779. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  74780. var _this = this;
  74781. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  74782. //can only work if this camera has a rotation quaternion already.
  74783. if (!this.rotationQuaternion)
  74784. return;
  74785. if (!this._initialQuaternion) {
  74786. this._initialQuaternion = new BABYLON.Quaternion();
  74787. }
  74788. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  74789. ['x', 'y', 'z'].forEach(function (axisName) {
  74790. if (!axis[axisName]) {
  74791. _this._initialQuaternion[axisName] = 0;
  74792. }
  74793. else {
  74794. _this._initialQuaternion[axisName] *= -1;
  74795. }
  74796. });
  74797. this._initialQuaternion.normalize();
  74798. //force rotation update
  74799. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  74800. };
  74801. return DeviceOrientationCamera;
  74802. }(BABYLON.FreeCamera));
  74803. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  74804. })(BABYLON || (BABYLON = {}));
  74805. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  74806. var BABYLON;
  74807. (function (BABYLON) {
  74808. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  74809. __extends(VRDeviceOrientationFreeCamera, _super);
  74810. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  74811. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74812. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74813. var _this = _super.call(this, name, position, scene) || this;
  74814. vrCameraMetrics.compensateDistortion = compensateDistortion;
  74815. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  74816. return _this;
  74817. }
  74818. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  74819. return "VRDeviceOrientationFreeCamera";
  74820. };
  74821. return VRDeviceOrientationFreeCamera;
  74822. }(BABYLON.DeviceOrientationCamera));
  74823. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  74824. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  74825. __extends(VRDeviceOrientationGamepadCamera, _super);
  74826. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  74827. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74828. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74829. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  74830. _this.inputs.addGamepad();
  74831. return _this;
  74832. }
  74833. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  74834. return "VRDeviceOrientationGamepadCamera";
  74835. };
  74836. return VRDeviceOrientationGamepadCamera;
  74837. }(VRDeviceOrientationFreeCamera));
  74838. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  74839. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  74840. __extends(VRDeviceOrientationArcRotateCamera, _super);
  74841. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  74842. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74843. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74844. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74845. vrCameraMetrics.compensateDistortion = compensateDistortion;
  74846. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  74847. _this.inputs.addVRDeviceOrientation();
  74848. return _this;
  74849. }
  74850. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  74851. return "VRDeviceOrientationArcRotateCamera";
  74852. };
  74853. return VRDeviceOrientationArcRotateCamera;
  74854. }(BABYLON.ArcRotateCamera));
  74855. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  74856. })(BABYLON || (BABYLON = {}));
  74857. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  74858. var BABYLON;
  74859. (function (BABYLON) {
  74860. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  74861. __extends(AnaglyphFreeCamera, _super);
  74862. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  74863. var _this = _super.call(this, name, position, scene) || this;
  74864. _this.interaxialDistance = interaxialDistance;
  74865. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74866. return _this;
  74867. }
  74868. AnaglyphFreeCamera.prototype.getClassName = function () {
  74869. return "AnaglyphFreeCamera";
  74870. };
  74871. return AnaglyphFreeCamera;
  74872. }(BABYLON.FreeCamera));
  74873. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  74874. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  74875. __extends(AnaglyphArcRotateCamera, _super);
  74876. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  74877. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74878. _this.interaxialDistance = interaxialDistance;
  74879. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74880. return _this;
  74881. }
  74882. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  74883. return "AnaglyphArcRotateCamera";
  74884. };
  74885. return AnaglyphArcRotateCamera;
  74886. }(BABYLON.ArcRotateCamera));
  74887. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  74888. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  74889. __extends(AnaglyphGamepadCamera, _super);
  74890. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  74891. var _this = _super.call(this, name, position, scene) || this;
  74892. _this.interaxialDistance = interaxialDistance;
  74893. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74894. return _this;
  74895. }
  74896. AnaglyphGamepadCamera.prototype.getClassName = function () {
  74897. return "AnaglyphGamepadCamera";
  74898. };
  74899. return AnaglyphGamepadCamera;
  74900. }(BABYLON.GamepadCamera));
  74901. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  74902. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  74903. __extends(AnaglyphUniversalCamera, _super);
  74904. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  74905. var _this = _super.call(this, name, position, scene) || this;
  74906. _this.interaxialDistance = interaxialDistance;
  74907. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74908. return _this;
  74909. }
  74910. AnaglyphUniversalCamera.prototype.getClassName = function () {
  74911. return "AnaglyphUniversalCamera";
  74912. };
  74913. return AnaglyphUniversalCamera;
  74914. }(BABYLON.UniversalCamera));
  74915. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  74916. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  74917. __extends(StereoscopicFreeCamera, _super);
  74918. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74919. var _this = _super.call(this, name, position, scene) || this;
  74920. _this.interaxialDistance = interaxialDistance;
  74921. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74922. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74923. return _this;
  74924. }
  74925. StereoscopicFreeCamera.prototype.getClassName = function () {
  74926. return "StereoscopicFreeCamera";
  74927. };
  74928. return StereoscopicFreeCamera;
  74929. }(BABYLON.FreeCamera));
  74930. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  74931. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  74932. __extends(StereoscopicArcRotateCamera, _super);
  74933. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  74934. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74935. _this.interaxialDistance = interaxialDistance;
  74936. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74937. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74938. return _this;
  74939. }
  74940. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  74941. return "StereoscopicArcRotateCamera";
  74942. };
  74943. return StereoscopicArcRotateCamera;
  74944. }(BABYLON.ArcRotateCamera));
  74945. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  74946. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  74947. __extends(StereoscopicGamepadCamera, _super);
  74948. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74949. var _this = _super.call(this, name, position, scene) || this;
  74950. _this.interaxialDistance = interaxialDistance;
  74951. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74952. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74953. return _this;
  74954. }
  74955. StereoscopicGamepadCamera.prototype.getClassName = function () {
  74956. return "StereoscopicGamepadCamera";
  74957. };
  74958. return StereoscopicGamepadCamera;
  74959. }(BABYLON.GamepadCamera));
  74960. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  74961. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  74962. __extends(StereoscopicUniversalCamera, _super);
  74963. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74964. var _this = _super.call(this, name, position, scene) || this;
  74965. _this.interaxialDistance = interaxialDistance;
  74966. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74967. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74968. return _this;
  74969. }
  74970. StereoscopicUniversalCamera.prototype.getClassName = function () {
  74971. return "StereoscopicUniversalCamera";
  74972. };
  74973. return StereoscopicUniversalCamera;
  74974. }(BABYLON.UniversalCamera));
  74975. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  74976. })(BABYLON || (BABYLON = {}));
  74977. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  74978. var BABYLON;
  74979. (function (BABYLON) {
  74980. /**
  74981. * Helps to quickly add VR support to an existing scene.
  74982. * See http://doc.babylonjs.com/how_to/webvr_helper
  74983. */
  74984. var VRExperienceHelper = /** @class */ (function () {
  74985. /**
  74986. * Instantiates a VRExperienceHelper.
  74987. * Helps to quickly add VR support to an existing scene.
  74988. * @param scene The scene the VRExperienceHelper belongs to.
  74989. * @param webVROptions Options to modify the vr experience helper's behavior.
  74990. */
  74991. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  74992. if (webVROptions === void 0) { webVROptions = {}; }
  74993. var _this = this;
  74994. this.webVROptions = webVROptions;
  74995. // Can the system support WebVR, even if a headset isn't plugged in?
  74996. this._webVRsupported = false;
  74997. // If WebVR is supported, is a headset plugged in and are we ready to present?
  74998. this._webVRready = false;
  74999. // Are we waiting for the requestPresent callback to complete?
  75000. this._webVRrequesting = false;
  75001. // Are we presenting to the headset right now?
  75002. this._webVRpresenting = false;
  75003. // Are we presenting in the fullscreen fallback?
  75004. this._fullscreenVRpresenting = false;
  75005. /**
  75006. * Observable raised when entering VR.
  75007. */
  75008. this.onEnteringVRObservable = new BABYLON.Observable();
  75009. /**
  75010. * Observable raised when exiting VR.
  75011. */
  75012. this.onExitingVRObservable = new BABYLON.Observable();
  75013. /**
  75014. * Observable raised when controller mesh is loaded.
  75015. */
  75016. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75017. this._useCustomVRButton = false;
  75018. this._teleportationRequested = false;
  75019. this._teleportationEnabledOnLeftController = false;
  75020. this._teleportationEnabledOnRightController = false;
  75021. this._interactionsEnabledOnLeftController = false;
  75022. this._interactionsEnabledOnRightController = false;
  75023. this._leftControllerReady = false;
  75024. this._rightControllerReady = false;
  75025. this._floorMeshesCollection = [];
  75026. this._teleportationAllowed = false;
  75027. this._rotationAllowed = true;
  75028. this._teleportationRequestInitiated = false;
  75029. this._teleportationBackRequestInitiated = false;
  75030. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  75031. this._rotationRightAsked = false;
  75032. this._rotationLeftAsked = false;
  75033. this._isDefaultTeleportationTarget = true;
  75034. this._teleportationFillColor = "#444444";
  75035. this._teleportationBorderColor = "#FFFFFF";
  75036. this._rotationAngle = 0;
  75037. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  75038. this._padSensibilityUp = 0.65;
  75039. this._padSensibilityDown = 0.35;
  75040. /**
  75041. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  75042. */
  75043. this.onNewMeshSelected = new BABYLON.Observable();
  75044. /**
  75045. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  75046. */
  75047. this.onNewMeshPicked = new BABYLON.Observable();
  75048. /**
  75049. * Observable raised before camera teleportation
  75050. */
  75051. this.onBeforeCameraTeleport = new BABYLON.Observable();
  75052. /**
  75053. * Observable raised after camera teleportation
  75054. */
  75055. this.onAfterCameraTeleport = new BABYLON.Observable();
  75056. /**
  75057. * Observable raised when current selected mesh gets unselected
  75058. */
  75059. this.onSelectedMeshUnselected = new BABYLON.Observable();
  75060. /**
  75061. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  75062. */
  75063. this.teleportationEnabled = true;
  75064. this._pointerDownOnMeshAsked = false;
  75065. this._isActionableMesh = false;
  75066. this._teleportationInitialized = false;
  75067. this._interactionsEnabled = false;
  75068. this._interactionsRequested = false;
  75069. this._displayGaze = true;
  75070. this._displayLaserPointer = true;
  75071. this._dpadPressed = true;
  75072. this._onResize = function () {
  75073. _this.moveButtonToBottomRight();
  75074. if (_this._fullscreenVRpresenting && _this._webVRready) {
  75075. _this.exitVR();
  75076. }
  75077. };
  75078. this._onFullscreenChange = function () {
  75079. if (document.fullscreen !== undefined) {
  75080. _this._fullscreenVRpresenting = document.fullscreen;
  75081. }
  75082. else if (document.mozFullScreen !== undefined) {
  75083. _this._fullscreenVRpresenting = document.mozFullScreen;
  75084. }
  75085. else if (document.webkitIsFullScreen !== undefined) {
  75086. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  75087. }
  75088. else if (document.msIsFullScreen !== undefined) {
  75089. _this._fullscreenVRpresenting = document.msIsFullScreen;
  75090. }
  75091. if (!_this._fullscreenVRpresenting && _this._canvas) {
  75092. _this.exitVR();
  75093. if (!_this._useCustomVRButton) {
  75094. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  75095. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  75096. }
  75097. }
  75098. };
  75099. this.beforeRender = function () {
  75100. _this._castRayAndSelectObject();
  75101. };
  75102. this._onNewGamepadConnected = function (gamepad) {
  75103. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  75104. if (gamepad.leftStick) {
  75105. gamepad.onleftstickchanged(function (stickValues) {
  75106. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  75107. // Listening to classic/xbox gamepad only if no VR controller is active
  75108. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  75109. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  75110. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  75111. _this._checkTeleportWithRay(stickValues);
  75112. _this._checkTeleportBackwards(stickValues);
  75113. }
  75114. }
  75115. });
  75116. }
  75117. if (gamepad.rightStick) {
  75118. gamepad.onrightstickchanged(function (stickValues) {
  75119. if (_this._teleportationInitialized) {
  75120. _this._checkRotate(stickValues);
  75121. }
  75122. });
  75123. }
  75124. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  75125. gamepad.onbuttondown(function (buttonPressed) {
  75126. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75127. _this._selectionPointerDown();
  75128. }
  75129. });
  75130. gamepad.onbuttonup(function (buttonPressed) {
  75131. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75132. _this._selectionPointerUp();
  75133. }
  75134. });
  75135. }
  75136. }
  75137. else {
  75138. var webVRController = gamepad;
  75139. _this._tryEnableInteractionOnController(webVRController);
  75140. }
  75141. };
  75142. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  75143. this._tryEnableInteractionOnController = function (webVRController) {
  75144. if (webVRController.hand === "left") {
  75145. _this._leftControllerReady = true;
  75146. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  75147. _this._enableInteractionOnController(webVRController);
  75148. }
  75149. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  75150. _this._enableTeleportationOnController(webVRController);
  75151. }
  75152. }
  75153. if (webVRController.hand === "right") {
  75154. _this._rightControllerReady = true;
  75155. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  75156. _this._enableInteractionOnController(webVRController);
  75157. }
  75158. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  75159. _this._enableTeleportationOnController(webVRController);
  75160. }
  75161. }
  75162. };
  75163. this._onNewGamepadDisconnected = function (gamepad) {
  75164. if (gamepad instanceof BABYLON.WebVRController) {
  75165. if (gamepad.hand === "left") {
  75166. _this._interactionsEnabledOnLeftController = false;
  75167. _this._teleportationEnabledOnLeftController = false;
  75168. _this._leftControllerReady = false;
  75169. if (_this._leftLaserPointer) {
  75170. _this._leftLaserPointer.dispose();
  75171. }
  75172. }
  75173. if (gamepad.hand === "right") {
  75174. _this._interactionsEnabledOnRightController = false;
  75175. _this._teleportationEnabledOnRightController = false;
  75176. _this._rightControllerReady = false;
  75177. if (_this._rightLaserPointer) {
  75178. _this._rightLaserPointer.dispose();
  75179. }
  75180. }
  75181. }
  75182. };
  75183. this._workingVector = BABYLON.Vector3.Zero();
  75184. this._workingQuaternion = BABYLON.Quaternion.Identity();
  75185. this._workingMatrix = BABYLON.Matrix.Identity();
  75186. this._scene = scene;
  75187. this._canvas = scene.getEngine().getRenderingCanvas();
  75188. // Parse options
  75189. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  75190. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  75191. }
  75192. if (webVROptions.createDeviceOrientationCamera === undefined) {
  75193. webVROptions.createDeviceOrientationCamera = true;
  75194. }
  75195. if (webVROptions.defaultHeight === undefined) {
  75196. webVROptions.defaultHeight = 1.7;
  75197. }
  75198. if (webVROptions.useCustomVRButton) {
  75199. this._useCustomVRButton = true;
  75200. if (webVROptions.customVRButton) {
  75201. this._btnVR = webVROptions.customVRButton;
  75202. }
  75203. }
  75204. if (webVROptions.rayLength) {
  75205. this._rayLength = webVROptions.rayLength;
  75206. }
  75207. this._defaultHeight = webVROptions.defaultHeight;
  75208. // Set position
  75209. if (this._scene.activeCamera) {
  75210. this._position = this._scene.activeCamera.position.clone();
  75211. }
  75212. else {
  75213. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  75214. }
  75215. // Set non-vr camera
  75216. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  75217. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  75218. // Copy data from existing camera
  75219. if (this._scene.activeCamera) {
  75220. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  75221. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  75222. // Set rotation from previous camera
  75223. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  75224. var targetCamera = this._scene.activeCamera;
  75225. if (targetCamera.rotationQuaternion) {
  75226. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  75227. }
  75228. else {
  75229. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  75230. }
  75231. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  75232. }
  75233. }
  75234. this._scene.activeCamera = this._deviceOrientationCamera;
  75235. if (this._canvas) {
  75236. this._scene.activeCamera.attachControl(this._canvas);
  75237. }
  75238. }
  75239. else {
  75240. this._existingCamera = this._scene.activeCamera;
  75241. }
  75242. // Create VR cameras
  75243. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75244. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  75245. }
  75246. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  75247. this._webVRCamera.useStandingMatrix();
  75248. // Create default button
  75249. if (!this._useCustomVRButton) {
  75250. this._btnVR = document.createElement("BUTTON");
  75251. this._btnVR.className = "babylonVRicon";
  75252. this._btnVR.id = "babylonVRiconbtn";
  75253. this._btnVR.title = "Click to switch to VR";
  75254. 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) }";
  75255. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  75256. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  75257. // css += ".babylonVRicon.vrdisplaysupported { }";
  75258. // css += ".babylonVRicon.vrdisplayready { }";
  75259. // css += ".babylonVRicon.vrdisplayrequesting { }";
  75260. var style = document.createElement('style');
  75261. style.appendChild(document.createTextNode(css));
  75262. document.getElementsByTagName('head')[0].appendChild(style);
  75263. this.moveButtonToBottomRight();
  75264. }
  75265. // VR button click event
  75266. if (this._btnVR) {
  75267. this._btnVR.addEventListener("click", function () {
  75268. if (!_this.isInVRMode) {
  75269. _this.enterVR();
  75270. }
  75271. else {
  75272. _this.exitVR();
  75273. }
  75274. });
  75275. }
  75276. // Window events
  75277. window.addEventListener("resize", this._onResize);
  75278. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  75279. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  75280. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  75281. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  75282. // Display vr button when headset is connected
  75283. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75284. this.displayVRButton();
  75285. }
  75286. else {
  75287. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  75288. if (e.vrDisplay) {
  75289. _this.displayVRButton();
  75290. }
  75291. });
  75292. }
  75293. // Exiting VR mode using 'ESC' key on desktop
  75294. this._onKeyDown = function (event) {
  75295. if (event.keyCode === 27 && _this.isInVRMode) {
  75296. _this.exitVR();
  75297. }
  75298. };
  75299. document.addEventListener("keydown", this._onKeyDown);
  75300. // Exiting VR mode double tapping the touch screen
  75301. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  75302. if (_this.isInVRMode) {
  75303. _this.exitVR();
  75304. if (_this._fullscreenVRpresenting) {
  75305. _this._scene.getEngine().switchFullscreen(true);
  75306. }
  75307. }
  75308. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  75309. // Listen for WebVR display changes
  75310. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  75311. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  75312. this._onVRRequestPresentStart = function () {
  75313. _this._webVRrequesting = true;
  75314. _this.updateButtonVisibility();
  75315. };
  75316. this._onVRRequestPresentComplete = function (success) {
  75317. _this._webVRrequesting = false;
  75318. _this.updateButtonVisibility();
  75319. };
  75320. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  75321. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  75322. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  75323. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  75324. scene.onDisposeObservable.add(function () {
  75325. _this.dispose();
  75326. });
  75327. // Gamepad connection events
  75328. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  75329. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  75330. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  75331. this.updateButtonVisibility();
  75332. //create easing functions
  75333. this._circleEase = new BABYLON.CircleEase();
  75334. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  75335. }
  75336. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  75337. /** Return this.onEnteringVRObservable
  75338. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  75339. */
  75340. get: function () {
  75341. return this.onEnteringVRObservable;
  75342. },
  75343. enumerable: true,
  75344. configurable: true
  75345. });
  75346. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  75347. /** Return this.onExitingVRObservable
  75348. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  75349. */
  75350. get: function () {
  75351. return this.onExitingVRObservable;
  75352. },
  75353. enumerable: true,
  75354. configurable: true
  75355. });
  75356. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  75357. /** Return this.onControllerMeshLoadedObservable
  75358. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  75359. */
  75360. get: function () {
  75361. return this.onControllerMeshLoadedObservable;
  75362. },
  75363. enumerable: true,
  75364. configurable: true
  75365. });
  75366. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  75367. /**
  75368. * The mesh used to display where the user is going to teleport.
  75369. */
  75370. get: function () {
  75371. return this._teleportationTarget;
  75372. },
  75373. /**
  75374. * Sets the mesh to be used to display where the user is going to teleport.
  75375. */
  75376. set: function (value) {
  75377. if (value) {
  75378. value.name = "teleportationTarget";
  75379. this._isDefaultTeleportationTarget = false;
  75380. this._teleportationTarget = value;
  75381. }
  75382. },
  75383. enumerable: true,
  75384. configurable: true
  75385. });
  75386. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  75387. /**
  75388. * If the ray of the gaze should be displayed.
  75389. */
  75390. get: function () {
  75391. return this._displayGaze;
  75392. },
  75393. /**
  75394. * Sets if the ray of the gaze should be displayed.
  75395. */
  75396. set: function (value) {
  75397. this._displayGaze = value;
  75398. if (!value) {
  75399. this._gazeTracker.isVisible = false;
  75400. }
  75401. },
  75402. enumerable: true,
  75403. configurable: true
  75404. });
  75405. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  75406. /**
  75407. * If the ray of the LaserPointer should be displayed.
  75408. */
  75409. get: function () {
  75410. return this._displayLaserPointer;
  75411. },
  75412. /**
  75413. * Sets if the ray of the LaserPointer should be displayed.
  75414. */
  75415. set: function (value) {
  75416. this._displayLaserPointer = value;
  75417. if (!value) {
  75418. if (this._rightLaserPointer) {
  75419. this._rightLaserPointer.isVisible = false;
  75420. }
  75421. if (this._leftLaserPointer) {
  75422. this._leftLaserPointer.isVisible = false;
  75423. }
  75424. }
  75425. else {
  75426. if (this._rightLaserPointer) {
  75427. this._rightLaserPointer.isVisible = true;
  75428. }
  75429. else if (this._leftLaserPointer) {
  75430. this._leftLaserPointer.isVisible = true;
  75431. }
  75432. }
  75433. },
  75434. enumerable: true,
  75435. configurable: true
  75436. });
  75437. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  75438. /**
  75439. * The deviceOrientationCamera used as the camera when not in VR.
  75440. */
  75441. get: function () {
  75442. return this._deviceOrientationCamera;
  75443. },
  75444. enumerable: true,
  75445. configurable: true
  75446. });
  75447. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  75448. /**
  75449. * Based on the current WebVR support, returns the current VR camera used.
  75450. */
  75451. get: function () {
  75452. if (this._webVRready) {
  75453. return this._webVRCamera;
  75454. }
  75455. else {
  75456. return this._scene.activeCamera;
  75457. }
  75458. },
  75459. enumerable: true,
  75460. configurable: true
  75461. });
  75462. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  75463. /**
  75464. * The webVRCamera which is used when in VR.
  75465. */
  75466. get: function () {
  75467. return this._webVRCamera;
  75468. },
  75469. enumerable: true,
  75470. configurable: true
  75471. });
  75472. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  75473. /**
  75474. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  75475. */
  75476. get: function () {
  75477. return this._vrDeviceOrientationCamera;
  75478. },
  75479. enumerable: true,
  75480. configurable: true
  75481. });
  75482. // Raised when one of the controller has loaded successfully its associated default mesh
  75483. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  75484. this._tryEnableInteractionOnController(webVRController);
  75485. try {
  75486. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  75487. }
  75488. catch (err) {
  75489. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  75490. }
  75491. };
  75492. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  75493. /**
  75494. * Gets a value indicating if we are currently in VR mode.
  75495. */
  75496. get: function () {
  75497. return this._webVRpresenting || this._fullscreenVRpresenting;
  75498. },
  75499. enumerable: true,
  75500. configurable: true
  75501. });
  75502. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  75503. var vrDisplay = this._scene.getEngine().getVRDevice();
  75504. if (vrDisplay) {
  75505. var wasPresenting = this._webVRpresenting;
  75506. // A VR display is connected
  75507. this._webVRpresenting = vrDisplay.isPresenting;
  75508. if (wasPresenting && !this._webVRpresenting)
  75509. this.exitVR();
  75510. }
  75511. else {
  75512. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  75513. }
  75514. this.updateButtonVisibility();
  75515. };
  75516. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  75517. this._webVRsupported = eventArgs.vrSupported;
  75518. this._webVRready = !!eventArgs.vrDisplay;
  75519. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  75520. this.updateButtonVisibility();
  75521. };
  75522. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  75523. if (this._canvas && !this._useCustomVRButton) {
  75524. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  75525. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  75526. }
  75527. };
  75528. VRExperienceHelper.prototype.displayVRButton = function () {
  75529. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  75530. document.body.appendChild(this._btnVR);
  75531. this._btnVRDisplayed = true;
  75532. }
  75533. };
  75534. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  75535. if (!this._btnVR || this._useCustomVRButton) {
  75536. return;
  75537. }
  75538. this._btnVR.className = "babylonVRicon";
  75539. if (this.isInVRMode) {
  75540. this._btnVR.className += " vrdisplaypresenting";
  75541. }
  75542. else {
  75543. if (this._webVRready)
  75544. this._btnVR.className += " vrdisplayready";
  75545. if (this._webVRsupported)
  75546. this._btnVR.className += " vrdisplaysupported";
  75547. if (this._webVRrequesting)
  75548. this._btnVR.className += " vrdisplayrequesting";
  75549. }
  75550. };
  75551. /**
  75552. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  75553. * Otherwise, will use the fullscreen API.
  75554. */
  75555. VRExperienceHelper.prototype.enterVR = function () {
  75556. if (this.onEnteringVRObservable) {
  75557. try {
  75558. this.onEnteringVRObservable.notifyObservers(this);
  75559. }
  75560. catch (err) {
  75561. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  75562. }
  75563. }
  75564. if (this._scene.activeCamera) {
  75565. this._position = this._scene.activeCamera.position.clone();
  75566. // make sure that we return to the last active camera
  75567. this._existingCamera = this._scene.activeCamera;
  75568. }
  75569. if (this._webVRrequesting)
  75570. return;
  75571. // If WebVR is supported and a headset is connected
  75572. if (this._webVRready) {
  75573. if (!this._webVRpresenting) {
  75574. this._webVRCamera.position = this._position;
  75575. this._scene.activeCamera = this._webVRCamera;
  75576. }
  75577. }
  75578. else if (this._vrDeviceOrientationCamera) {
  75579. this._vrDeviceOrientationCamera.position = this._position;
  75580. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  75581. this._scene.getEngine().switchFullscreen(true);
  75582. this.updateButtonVisibility();
  75583. }
  75584. if (this._scene.activeCamera && this._canvas) {
  75585. this._scene.activeCamera.attachControl(this._canvas);
  75586. }
  75587. if (this._interactionsEnabled) {
  75588. this._scene.registerBeforeRender(this.beforeRender);
  75589. }
  75590. };
  75591. /**
  75592. * Attempt to exit VR, or fullscreen.
  75593. */
  75594. VRExperienceHelper.prototype.exitVR = function () {
  75595. if (this.onExitingVRObservable) {
  75596. try {
  75597. this.onExitingVRObservable.notifyObservers(this);
  75598. }
  75599. catch (err) {
  75600. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  75601. }
  75602. }
  75603. if (this._webVRpresenting) {
  75604. this._scene.getEngine().disableVR();
  75605. }
  75606. if (this._scene.activeCamera) {
  75607. this._position = this._scene.activeCamera.position.clone();
  75608. }
  75609. if (this._deviceOrientationCamera) {
  75610. this._deviceOrientationCamera.position = this._position;
  75611. this._scene.activeCamera = this._deviceOrientationCamera;
  75612. if (this._canvas) {
  75613. this._scene.activeCamera.attachControl(this._canvas);
  75614. }
  75615. }
  75616. else if (this._existingCamera) {
  75617. this._existingCamera.position = this._position;
  75618. this._scene.activeCamera = this._existingCamera;
  75619. }
  75620. this.updateButtonVisibility();
  75621. if (this._interactionsEnabled) {
  75622. this._scene.unregisterBeforeRender(this.beforeRender);
  75623. }
  75624. };
  75625. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  75626. /**
  75627. * The position of the vr experience helper.
  75628. */
  75629. get: function () {
  75630. return this._position;
  75631. },
  75632. /**
  75633. * Sets the position of the vr experience helper.
  75634. */
  75635. set: function (value) {
  75636. this._position = value;
  75637. if (this._scene.activeCamera) {
  75638. this._scene.activeCamera.position = value;
  75639. }
  75640. },
  75641. enumerable: true,
  75642. configurable: true
  75643. });
  75644. /**
  75645. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  75646. */
  75647. VRExperienceHelper.prototype.enableInteractions = function () {
  75648. var _this = this;
  75649. if (!this._interactionsEnabled) {
  75650. this._interactionsRequested = true;
  75651. if (this._leftControllerReady && this._webVRCamera.leftController) {
  75652. this._enableInteractionOnController(this._webVRCamera.leftController);
  75653. }
  75654. if (this._rightControllerReady && this._webVRCamera.rightController) {
  75655. this._enableInteractionOnController(this._webVRCamera.rightController);
  75656. }
  75657. this._createGazeTracker();
  75658. this.raySelectionPredicate = function (mesh) {
  75659. return mesh.isVisible;
  75660. };
  75661. this.meshSelectionPredicate = function (mesh) {
  75662. return true;
  75663. };
  75664. this._raySelectionPredicate = function (mesh) {
  75665. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  75666. && mesh.name.indexOf("teleportationTarget") === -1
  75667. && mesh.name.indexOf("torusTeleportation") === -1
  75668. && mesh.name.indexOf("laserPointer") === -1)) {
  75669. return _this.raySelectionPredicate(mesh);
  75670. }
  75671. return false;
  75672. };
  75673. this._interactionsEnabled = true;
  75674. }
  75675. };
  75676. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  75677. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  75678. if (this._floorMeshesCollection[i].id === mesh.id) {
  75679. return true;
  75680. }
  75681. }
  75682. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  75683. return true;
  75684. }
  75685. return false;
  75686. };
  75687. /**
  75688. * Adds a floor mesh to be used for teleportation.
  75689. * @param floorMesh the mesh to be used for teleportation.
  75690. */
  75691. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  75692. if (!this._floorMeshesCollection) {
  75693. return;
  75694. }
  75695. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  75696. return;
  75697. }
  75698. this._floorMeshesCollection.push(floorMesh);
  75699. };
  75700. /**
  75701. * Removes a floor mesh from being used for teleportation.
  75702. * @param floorMesh the mesh to be removed.
  75703. */
  75704. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  75705. if (!this._floorMeshesCollection) {
  75706. return;
  75707. }
  75708. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  75709. if (meshIndex !== -1) {
  75710. this._floorMeshesCollection.splice(meshIndex, 1);
  75711. }
  75712. };
  75713. /**
  75714. * Enables interactions and teleportation using the VR controllers and gaze.
  75715. * @param vrTeleportationOptions options to modify teleportation behavior.
  75716. */
  75717. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  75718. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  75719. if (!this._teleportationInitialized) {
  75720. this._teleportationRequested = true;
  75721. this.enableInteractions();
  75722. if (vrTeleportationOptions.floorMeshName) {
  75723. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  75724. }
  75725. if (vrTeleportationOptions.floorMeshes) {
  75726. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  75727. }
  75728. if (this._leftControllerReady && this._webVRCamera.leftController) {
  75729. this._enableTeleportationOnController(this._webVRCamera.leftController);
  75730. }
  75731. if (this._rightControllerReady && this._webVRCamera.rightController) {
  75732. this._enableTeleportationOnController(this._webVRCamera.rightController);
  75733. }
  75734. // Creates an image processing post process for the vignette not relying
  75735. // on the main scene configuration for image processing to reduce setup and spaces
  75736. // (gamma/linear) conflicts.
  75737. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  75738. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  75739. imageProcessingConfiguration.vignetteEnabled = true;
  75740. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  75741. this._webVRCamera.detachPostProcess(this._postProcessMove);
  75742. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  75743. this._teleportationInitialized = true;
  75744. if (this._isDefaultTeleportationTarget) {
  75745. this._createTeleportationCircles();
  75746. }
  75747. }
  75748. };
  75749. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  75750. var _this = this;
  75751. var controllerMesh = webVRController.mesh;
  75752. if (controllerMesh) {
  75753. var makeNotPick = function (root) {
  75754. root.name += " laserPointer";
  75755. root.getChildMeshes().forEach(function (c) {
  75756. makeNotPick(c);
  75757. });
  75758. };
  75759. makeNotPick(controllerMesh);
  75760. var childMeshes = controllerMesh.getChildMeshes();
  75761. for (var i = 0; i < childMeshes.length; i++) {
  75762. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  75763. controllerMesh = childMeshes[i];
  75764. break;
  75765. }
  75766. }
  75767. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  75768. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  75769. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  75770. laserPointerMaterial.alpha = 0.6;
  75771. laserPointer.material = laserPointerMaterial;
  75772. laserPointer.rotation.x = Math.PI / 2;
  75773. laserPointer.parent = controllerMesh;
  75774. laserPointer.position.z = -0.5;
  75775. laserPointer.isVisible = false;
  75776. if (webVRController.hand === "left") {
  75777. this._leftLaserPointer = laserPointer;
  75778. this._interactionsEnabledOnLeftController = true;
  75779. if (!this._rightLaserPointer) {
  75780. this._leftLaserPointer.isVisible = true;
  75781. }
  75782. }
  75783. else {
  75784. this._rightLaserPointer = laserPointer;
  75785. this._interactionsEnabledOnRightController = true;
  75786. if (!this._leftLaserPointer) {
  75787. this._rightLaserPointer.isVisible = true;
  75788. }
  75789. }
  75790. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  75791. // Enabling / disabling laserPointer
  75792. if (_this._displayLaserPointer && stateObject.value === 1) {
  75793. laserPointer.isVisible = !laserPointer.isVisible;
  75794. // Laser pointer can only be active on left or right, not both at the same time
  75795. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  75796. _this._rightLaserPointer.isVisible = false;
  75797. }
  75798. else if (_this._leftLaserPointer) {
  75799. _this._leftLaserPointer.isVisible = false;
  75800. }
  75801. }
  75802. });
  75803. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  75804. if (!_this._pointerDownOnMeshAsked) {
  75805. if (stateObject.value > _this._padSensibilityUp) {
  75806. _this._selectionPointerDown();
  75807. }
  75808. }
  75809. else if (stateObject.value < _this._padSensibilityDown) {
  75810. _this._selectionPointerUp();
  75811. }
  75812. });
  75813. }
  75814. };
  75815. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  75816. if (webVRController === void 0) { webVRController = null; }
  75817. if (!this._teleportationRequestInitiated) {
  75818. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  75819. if (webVRController) {
  75820. // If laser pointer wasn't enabled yet
  75821. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  75822. this._leftLaserPointer.isVisible = true;
  75823. if (this._rightLaserPointer) {
  75824. this._rightLaserPointer.isVisible = false;
  75825. }
  75826. }
  75827. else if (this._displayLaserPointer && this._rightLaserPointer) {
  75828. this._rightLaserPointer.isVisible = true;
  75829. if (this._leftLaserPointer) {
  75830. this._leftLaserPointer.isVisible = false;
  75831. }
  75832. }
  75833. }
  75834. this._teleportationRequestInitiated = true;
  75835. }
  75836. }
  75837. else {
  75838. // Listening to the proper controller values changes to confirm teleportation
  75839. if (webVRController == null
  75840. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  75841. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  75842. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  75843. if (this._teleportationAllowed) {
  75844. this._teleportationAllowed = false;
  75845. this._teleportCamera();
  75846. }
  75847. this._teleportationRequestInitiated = false;
  75848. }
  75849. }
  75850. }
  75851. };
  75852. VRExperienceHelper.prototype._selectionPointerDown = function () {
  75853. this._pointerDownOnMeshAsked = true;
  75854. if (this._currentMeshSelected && this._currentHit) {
  75855. this._scene.simulatePointerDown(this._currentHit);
  75856. }
  75857. };
  75858. VRExperienceHelper.prototype._selectionPointerUp = function () {
  75859. if (this._currentMeshSelected && this._currentHit) {
  75860. this._scene.simulatePointerUp(this._currentHit);
  75861. }
  75862. this._pointerDownOnMeshAsked = false;
  75863. };
  75864. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  75865. // Only rotate when user is not currently selecting a teleportation location
  75866. if (this._teleportationRequestInitiated) {
  75867. return;
  75868. }
  75869. if (!this._rotationLeftAsked) {
  75870. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  75871. this._rotationLeftAsked = true;
  75872. if (this._rotationAllowed) {
  75873. this._rotateCamera(false);
  75874. }
  75875. }
  75876. }
  75877. else {
  75878. if (stateObject.x > -this._padSensibilityDown) {
  75879. this._rotationLeftAsked = false;
  75880. }
  75881. }
  75882. if (!this._rotationRightAsked) {
  75883. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  75884. this._rotationRightAsked = true;
  75885. if (this._rotationAllowed) {
  75886. this._rotateCamera(true);
  75887. }
  75888. }
  75889. }
  75890. else {
  75891. if (stateObject.x < this._padSensibilityDown) {
  75892. this._rotationRightAsked = false;
  75893. }
  75894. }
  75895. };
  75896. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  75897. // Only teleport backwards when user is not currently selecting a teleportation location
  75898. if (this._teleportationRequestInitiated) {
  75899. return;
  75900. }
  75901. // Teleport backwards
  75902. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  75903. if (!this._teleportationBackRequestInitiated) {
  75904. if (!this.currentVRCamera) {
  75905. return;
  75906. }
  75907. // Get rotation and position of the current camera
  75908. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  75909. var position = this.currentVRCamera.position;
  75910. // If the camera has device position, use that instead
  75911. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  75912. rotation = this.currentVRCamera.deviceRotationQuaternion;
  75913. position = this.currentVRCamera.devicePosition;
  75914. }
  75915. // Get matrix with only the y rotation of the device rotation
  75916. rotation.toEulerAnglesToRef(this._workingVector);
  75917. this._workingVector.z = 0;
  75918. this._workingVector.x = 0;
  75919. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  75920. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  75921. // Rotate backwards ray by device rotation to cast at the ground behind the user
  75922. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  75923. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  75924. var ray = new BABYLON.Ray(position, this._workingVector);
  75925. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  75926. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  75927. this._teleportCamera(hit.pickedPoint);
  75928. }
  75929. this._teleportationBackRequestInitiated = true;
  75930. }
  75931. }
  75932. else {
  75933. this._teleportationBackRequestInitiated = false;
  75934. }
  75935. };
  75936. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  75937. var _this = this;
  75938. var controllerMesh = webVRController.mesh;
  75939. if (controllerMesh) {
  75940. if (webVRController.hand === "left") {
  75941. if (!this._interactionsEnabledOnLeftController) {
  75942. this._enableInteractionOnController(webVRController);
  75943. }
  75944. this._teleportationEnabledOnLeftController = true;
  75945. }
  75946. else {
  75947. if (!this._interactionsEnabledOnRightController) {
  75948. this._enableInteractionOnController(webVRController);
  75949. }
  75950. this._teleportationEnabledOnRightController = true;
  75951. }
  75952. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75953. this._dpadPressed = false;
  75954. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  75955. _this._dpadPressed = stateObject.pressed;
  75956. if (!_this._dpadPressed) {
  75957. _this._rotationLeftAsked = false;
  75958. _this._rotationRightAsked = false;
  75959. _this._teleportationBackRequestInitiated = false;
  75960. }
  75961. });
  75962. }
  75963. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  75964. if (_this.teleportationEnabled) {
  75965. _this._checkTeleportBackwards(stateObject);
  75966. _this._checkTeleportWithRay(stateObject, webVRController);
  75967. }
  75968. _this._checkRotate(stateObject);
  75969. });
  75970. }
  75971. };
  75972. // Gaze support used to point to teleport or to interact with an object
  75973. VRExperienceHelper.prototype._createGazeTracker = function () {
  75974. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  75975. this._gazeTracker.bakeCurrentTransformIntoVertices();
  75976. this._gazeTracker.isPickable = false;
  75977. this._gazeTracker.isVisible = false;
  75978. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  75979. targetMat.specularColor = BABYLON.Color3.Black();
  75980. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  75981. targetMat.backFaceCulling = false;
  75982. this._gazeTracker.material = targetMat;
  75983. };
  75984. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  75985. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  75986. this._teleportationTarget.isPickable = false;
  75987. var length = 512;
  75988. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  75989. dynamicTexture.hasAlpha = true;
  75990. var context = dynamicTexture.getContext();
  75991. var centerX = length / 2;
  75992. var centerY = length / 2;
  75993. var radius = 200;
  75994. context.beginPath();
  75995. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  75996. context.fillStyle = this._teleportationFillColor;
  75997. context.fill();
  75998. context.lineWidth = 10;
  75999. context.strokeStyle = this._teleportationBorderColor;
  76000. context.stroke();
  76001. context.closePath();
  76002. dynamicTexture.update();
  76003. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  76004. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  76005. this._teleportationTarget.material = teleportationCircleMaterial;
  76006. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  76007. torus.isPickable = false;
  76008. torus.parent = this._teleportationTarget;
  76009. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76010. var keys = [];
  76011. keys.push({
  76012. frame: 0,
  76013. value: 0
  76014. });
  76015. keys.push({
  76016. frame: 30,
  76017. value: 0.4
  76018. });
  76019. keys.push({
  76020. frame: 60,
  76021. value: 0
  76022. });
  76023. animationInnerCircle.setKeys(keys);
  76024. var easingFunction = new BABYLON.SineEase();
  76025. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  76026. animationInnerCircle.setEasingFunction(easingFunction);
  76027. torus.animations = [];
  76028. torus.animations.push(animationInnerCircle);
  76029. this._scene.beginAnimation(torus, 0, 60, true);
  76030. this._hideTeleportationTarget();
  76031. };
  76032. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  76033. if (this._teleportationInitialized) {
  76034. this._teleportationTarget.isVisible = true;
  76035. if (this._isDefaultTeleportationTarget) {
  76036. this._teleportationTarget.getChildren()[0].isVisible = true;
  76037. }
  76038. }
  76039. };
  76040. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  76041. if (this._teleportationInitialized) {
  76042. this._teleportationTarget.isVisible = false;
  76043. if (this._isDefaultTeleportationTarget) {
  76044. this._teleportationTarget.getChildren()[0].isVisible = false;
  76045. }
  76046. }
  76047. };
  76048. VRExperienceHelper.prototype._rotateCamera = function (right) {
  76049. var _this = this;
  76050. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76051. return;
  76052. }
  76053. if (right) {
  76054. this._rotationAngle++;
  76055. }
  76056. else {
  76057. this._rotationAngle--;
  76058. }
  76059. this.currentVRCamera.animations = [];
  76060. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  76061. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76062. var animationRotationKeys = [];
  76063. animationRotationKeys.push({
  76064. frame: 0,
  76065. value: this.currentVRCamera.rotationQuaternion
  76066. });
  76067. animationRotationKeys.push({
  76068. frame: 6,
  76069. value: target
  76070. });
  76071. animationRotation.setKeys(animationRotationKeys);
  76072. animationRotation.setEasingFunction(this._circleEase);
  76073. this.currentVRCamera.animations.push(animationRotation);
  76074. this._postProcessMove.animations = [];
  76075. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76076. var vignetteWeightKeys = [];
  76077. vignetteWeightKeys.push({
  76078. frame: 0,
  76079. value: 0
  76080. });
  76081. vignetteWeightKeys.push({
  76082. frame: 3,
  76083. value: 4
  76084. });
  76085. vignetteWeightKeys.push({
  76086. frame: 6,
  76087. value: 0
  76088. });
  76089. animationPP.setKeys(vignetteWeightKeys);
  76090. animationPP.setEasingFunction(this._circleEase);
  76091. this._postProcessMove.animations.push(animationPP);
  76092. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76093. var vignetteStretchKeys = [];
  76094. vignetteStretchKeys.push({
  76095. frame: 0,
  76096. value: 0
  76097. });
  76098. vignetteStretchKeys.push({
  76099. frame: 3,
  76100. value: 10
  76101. });
  76102. vignetteStretchKeys.push({
  76103. frame: 6,
  76104. value: 0
  76105. });
  76106. animationPP2.setKeys(vignetteStretchKeys);
  76107. animationPP2.setEasingFunction(this._circleEase);
  76108. this._postProcessMove.animations.push(animationPP2);
  76109. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76110. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76111. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76112. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  76113. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76114. });
  76115. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  76116. };
  76117. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  76118. if (hit.pickedPoint) {
  76119. this._teleportationAllowed = true;
  76120. if (this._teleportationRequestInitiated) {
  76121. this._displayTeleportationTarget();
  76122. }
  76123. else {
  76124. this._hideTeleportationTarget();
  76125. }
  76126. this._haloCenter.copyFrom(hit.pickedPoint);
  76127. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  76128. var pickNormal = hit.getNormal(true, false);
  76129. if (pickNormal) {
  76130. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76131. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76132. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  76133. }
  76134. this._teleportationTarget.position.y += 0.1;
  76135. }
  76136. };
  76137. VRExperienceHelper.prototype._teleportCamera = function (location) {
  76138. var _this = this;
  76139. if (location === void 0) { location = null; }
  76140. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76141. return;
  76142. }
  76143. if (!location) {
  76144. location = this._haloCenter;
  76145. }
  76146. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  76147. // offset of the headset from the anchor.
  76148. if (this.webVRCamera.leftCamera) {
  76149. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  76150. this._workingVector.subtractInPlace(this.webVRCamera.position);
  76151. location.subtractToRef(this._workingVector, this._workingVector);
  76152. }
  76153. else {
  76154. this._workingVector.copyFrom(location);
  76155. }
  76156. // Add height to account for user's height offset
  76157. if (this.isInVRMode) {
  76158. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  76159. }
  76160. else {
  76161. this._workingVector.y += this._defaultHeight;
  76162. }
  76163. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  76164. // Create animation from the camera's position to the new location
  76165. this.currentVRCamera.animations = [];
  76166. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76167. var animationCameraTeleportationKeys = [{
  76168. frame: 0,
  76169. value: this.currentVRCamera.position
  76170. },
  76171. {
  76172. frame: 11,
  76173. value: this._workingVector
  76174. }
  76175. ];
  76176. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  76177. animationCameraTeleportation.setEasingFunction(this._circleEase);
  76178. this.currentVRCamera.animations.push(animationCameraTeleportation);
  76179. this._postProcessMove.animations = [];
  76180. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76181. var vignetteWeightKeys = [];
  76182. vignetteWeightKeys.push({
  76183. frame: 0,
  76184. value: 0
  76185. });
  76186. vignetteWeightKeys.push({
  76187. frame: 5,
  76188. value: 8
  76189. });
  76190. vignetteWeightKeys.push({
  76191. frame: 11,
  76192. value: 0
  76193. });
  76194. animationPP.setKeys(vignetteWeightKeys);
  76195. this._postProcessMove.animations.push(animationPP);
  76196. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76197. var vignetteStretchKeys = [];
  76198. vignetteStretchKeys.push({
  76199. frame: 0,
  76200. value: 0
  76201. });
  76202. vignetteStretchKeys.push({
  76203. frame: 5,
  76204. value: 10
  76205. });
  76206. vignetteStretchKeys.push({
  76207. frame: 11,
  76208. value: 0
  76209. });
  76210. animationPP2.setKeys(vignetteStretchKeys);
  76211. this._postProcessMove.animations.push(animationPP2);
  76212. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76213. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76214. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76215. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  76216. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76217. });
  76218. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  76219. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  76220. });
  76221. };
  76222. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  76223. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76224. return;
  76225. }
  76226. var ray;
  76227. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  76228. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  76229. }
  76230. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  76231. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  76232. }
  76233. else {
  76234. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  76235. }
  76236. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  76237. // Moving the gazeTracker on the mesh face targetted
  76238. if (hit && hit.pickedPoint) {
  76239. if (this._displayGaze) {
  76240. var multiplier = 1;
  76241. this._gazeTracker.isVisible = true;
  76242. if (this._isActionableMesh) {
  76243. multiplier = 3;
  76244. }
  76245. this._gazeTracker.scaling.x = hit.distance * multiplier;
  76246. this._gazeTracker.scaling.y = hit.distance * multiplier;
  76247. this._gazeTracker.scaling.z = hit.distance * multiplier;
  76248. var pickNormal = hit.getNormal();
  76249. // To avoid z-fighting
  76250. var deltaFighting = 0.002;
  76251. if (pickNormal) {
  76252. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76253. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76254. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  76255. }
  76256. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  76257. if (this._gazeTracker.position.x < 0) {
  76258. this._gazeTracker.position.x += deltaFighting;
  76259. }
  76260. else {
  76261. this._gazeTracker.position.x -= deltaFighting;
  76262. }
  76263. if (this._gazeTracker.position.y < 0) {
  76264. this._gazeTracker.position.y += deltaFighting;
  76265. }
  76266. else {
  76267. this._gazeTracker.position.y -= deltaFighting;
  76268. }
  76269. if (this._gazeTracker.position.z < 0) {
  76270. this._gazeTracker.position.z += deltaFighting;
  76271. }
  76272. else {
  76273. this._gazeTracker.position.z -= deltaFighting;
  76274. }
  76275. }
  76276. // Changing the size of the laser pointer based on the distance from the targetted point
  76277. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  76278. this._rightLaserPointer.scaling.y = hit.distance;
  76279. this._rightLaserPointer.position.z = -hit.distance / 2;
  76280. }
  76281. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  76282. this._leftLaserPointer.scaling.y = hit.distance;
  76283. this._leftLaserPointer.position.z = -hit.distance / 2;
  76284. }
  76285. }
  76286. else {
  76287. this._gazeTracker.isVisible = false;
  76288. }
  76289. if (hit && hit.pickedMesh) {
  76290. this._currentHit = hit;
  76291. if (this._pointerDownOnMeshAsked) {
  76292. this._scene.simulatePointerMove(this._currentHit);
  76293. }
  76294. // The object selected is the floor, we're in a teleportation scenario
  76295. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  76296. // Moving the teleportation area to this targetted point
  76297. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  76298. if (this._currentMeshSelected &&
  76299. !this._isTeleportationFloor(this._currentMeshSelected)) {
  76300. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76301. }
  76302. this._currentMeshSelected = null;
  76303. this._moveTeleportationSelectorTo(hit);
  76304. return;
  76305. }
  76306. // If not, we're in a selection scenario
  76307. this._hideTeleportationTarget();
  76308. this._teleportationAllowed = false;
  76309. if (hit.pickedMesh !== this._currentMeshSelected) {
  76310. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  76311. this.onNewMeshPicked.notifyObservers(hit);
  76312. this._currentMeshSelected = hit.pickedMesh;
  76313. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  76314. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  76315. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  76316. this._isActionableMesh = true;
  76317. }
  76318. else {
  76319. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76320. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76321. this._isActionableMesh = false;
  76322. }
  76323. try {
  76324. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  76325. }
  76326. catch (err) {
  76327. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  76328. }
  76329. }
  76330. else {
  76331. if (this._currentMeshSelected) {
  76332. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76333. }
  76334. this._currentMeshSelected = null;
  76335. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76336. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76337. }
  76338. }
  76339. }
  76340. else {
  76341. this._currentHit = null;
  76342. this._currentMeshSelected = null;
  76343. this._teleportationAllowed = false;
  76344. this._hideTeleportationTarget();
  76345. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76346. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76347. }
  76348. };
  76349. /**
  76350. * Sets the color of the laser ray from the vr controllers.
  76351. * @param color new color for the ray.
  76352. */
  76353. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  76354. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  76355. this._leftLaserPointer.material.emissiveColor = color;
  76356. }
  76357. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  76358. this._rightLaserPointer.material.emissiveColor = color;
  76359. }
  76360. };
  76361. /**
  76362. * Sets the color of the ray from the vr headsets gaze.
  76363. * @param color new color for the ray.
  76364. */
  76365. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  76366. if (this._gazeTracker.material) {
  76367. this._gazeTracker.material.emissiveColor = color;
  76368. }
  76369. };
  76370. /**
  76371. * Exits VR and disposes of the vr experience helper
  76372. */
  76373. VRExperienceHelper.prototype.dispose = function () {
  76374. if (this.isInVRMode) {
  76375. this.exitVR();
  76376. }
  76377. if (this._passProcessMove) {
  76378. this._passProcessMove.dispose();
  76379. }
  76380. if (this._postProcessMove) {
  76381. this._postProcessMove.dispose();
  76382. }
  76383. if (this._webVRCamera) {
  76384. this._webVRCamera.dispose();
  76385. }
  76386. if (this._vrDeviceOrientationCamera) {
  76387. this._vrDeviceOrientationCamera.dispose();
  76388. }
  76389. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  76390. document.body.removeChild(this._btnVR);
  76391. }
  76392. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  76393. this._deviceOrientationCamera.dispose();
  76394. }
  76395. if (this._gazeTracker) {
  76396. this._gazeTracker.dispose();
  76397. }
  76398. if (this._teleportationTarget) {
  76399. this._teleportationTarget.dispose();
  76400. }
  76401. this._floorMeshesCollection = [];
  76402. document.removeEventListener("keydown", this._onKeyDown);
  76403. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76404. window.removeEventListener("resize", this._onResize);
  76405. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  76406. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  76407. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  76408. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  76409. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  76410. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  76411. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  76412. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76413. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  76414. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  76415. this._scene.unregisterBeforeRender(this.beforeRender);
  76416. };
  76417. /**
  76418. * Gets the name of the VRExperienceHelper class
  76419. * @returns "VRExperienceHelper"
  76420. */
  76421. VRExperienceHelper.prototype.getClassName = function () {
  76422. return "VRExperienceHelper";
  76423. };
  76424. return VRExperienceHelper;
  76425. }());
  76426. BABYLON.VRExperienceHelper = VRExperienceHelper;
  76427. })(BABYLON || (BABYLON = {}));
  76428. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  76429. // Mainly based on these 2 articles :
  76430. // 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
  76431. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  76432. var BABYLON;
  76433. (function (BABYLON) {
  76434. var JoystickAxis;
  76435. (function (JoystickAxis) {
  76436. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  76437. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  76438. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  76439. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  76440. var VirtualJoystick = /** @class */ (function () {
  76441. function VirtualJoystick(leftJoystick) {
  76442. var _this = this;
  76443. if (leftJoystick) {
  76444. this._leftJoystick = true;
  76445. }
  76446. else {
  76447. this._leftJoystick = false;
  76448. }
  76449. VirtualJoystick._globalJoystickIndex++;
  76450. // By default left & right arrow keys are moving the X
  76451. // and up & down keys are moving the Y
  76452. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76453. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76454. this.reverseLeftRight = false;
  76455. this.reverseUpDown = false;
  76456. // collections of pointers
  76457. this._touches = new BABYLON.StringDictionary();
  76458. this.deltaPosition = BABYLON.Vector3.Zero();
  76459. this._joystickSensibility = 25;
  76460. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76461. this._onResize = function (evt) {
  76462. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76463. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76464. if (VirtualJoystick.vjCanvas) {
  76465. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  76466. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  76467. }
  76468. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  76469. };
  76470. // injecting a canvas element on top of the canvas 3D game
  76471. if (!VirtualJoystick.vjCanvas) {
  76472. window.addEventListener("resize", this._onResize, false);
  76473. VirtualJoystick.vjCanvas = document.createElement("canvas");
  76474. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76475. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76476. VirtualJoystick.vjCanvas.width = window.innerWidth;
  76477. VirtualJoystick.vjCanvas.height = window.innerHeight;
  76478. VirtualJoystick.vjCanvas.style.width = "100%";
  76479. VirtualJoystick.vjCanvas.style.height = "100%";
  76480. VirtualJoystick.vjCanvas.style.position = "absolute";
  76481. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  76482. VirtualJoystick.vjCanvas.style.top = "0px";
  76483. VirtualJoystick.vjCanvas.style.left = "0px";
  76484. VirtualJoystick.vjCanvas.style.zIndex = "5";
  76485. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  76486. // Support for jQuery PEP polyfill
  76487. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  76488. var context = VirtualJoystick.vjCanvas.getContext('2d');
  76489. if (!context) {
  76490. throw new Error("Unable to create canvas for virtual joystick");
  76491. }
  76492. VirtualJoystick.vjCanvasContext = context;
  76493. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  76494. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76495. document.body.appendChild(VirtualJoystick.vjCanvas);
  76496. }
  76497. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  76498. this.pressed = false;
  76499. // default joystick color
  76500. this._joystickColor = "cyan";
  76501. this._joystickPointerID = -1;
  76502. // current joystick position
  76503. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  76504. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  76505. // origin joystick position
  76506. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  76507. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  76508. this._onPointerDownHandlerRef = function (evt) {
  76509. _this._onPointerDown(evt);
  76510. };
  76511. this._onPointerMoveHandlerRef = function (evt) {
  76512. _this._onPointerMove(evt);
  76513. };
  76514. this._onPointerUpHandlerRef = function (evt) {
  76515. _this._onPointerUp(evt);
  76516. };
  76517. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  76518. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  76519. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  76520. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  76521. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  76522. evt.preventDefault(); // Disables system menu
  76523. }, false);
  76524. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76525. }
  76526. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  76527. this._joystickSensibility = newJoystickSensibility;
  76528. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76529. };
  76530. VirtualJoystick.prototype._onPointerDown = function (e) {
  76531. var positionOnScreenCondition;
  76532. e.preventDefault();
  76533. if (this._leftJoystick === true) {
  76534. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  76535. }
  76536. else {
  76537. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  76538. }
  76539. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  76540. // First contact will be dedicated to the virtual joystick
  76541. this._joystickPointerID = e.pointerId;
  76542. this._joystickPointerStartPos.x = e.clientX;
  76543. this._joystickPointerStartPos.y = e.clientY;
  76544. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  76545. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  76546. this._deltaJoystickVector.x = 0;
  76547. this._deltaJoystickVector.y = 0;
  76548. this.pressed = true;
  76549. this._touches.add(e.pointerId.toString(), e);
  76550. }
  76551. else {
  76552. // You can only trigger the action buttons with a joystick declared
  76553. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  76554. this._action();
  76555. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  76556. }
  76557. }
  76558. };
  76559. VirtualJoystick.prototype._onPointerMove = function (e) {
  76560. // If the current pointer is the one associated to the joystick (first touch contact)
  76561. if (this._joystickPointerID == e.pointerId) {
  76562. this._joystickPointerPos.x = e.clientX;
  76563. this._joystickPointerPos.y = e.clientY;
  76564. this._deltaJoystickVector = this._joystickPointerPos.clone();
  76565. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  76566. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  76567. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  76568. switch (this._axisTargetedByLeftAndRight) {
  76569. case JoystickAxis.X:
  76570. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  76571. break;
  76572. case JoystickAxis.Y:
  76573. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  76574. break;
  76575. case JoystickAxis.Z:
  76576. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  76577. break;
  76578. }
  76579. var directionUpDown = this.reverseUpDown ? 1 : -1;
  76580. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  76581. switch (this._axisTargetedByUpAndDown) {
  76582. case JoystickAxis.X:
  76583. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  76584. break;
  76585. case JoystickAxis.Y:
  76586. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  76587. break;
  76588. case JoystickAxis.Z:
  76589. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  76590. break;
  76591. }
  76592. }
  76593. else {
  76594. var data = this._touches.get(e.pointerId.toString());
  76595. if (data) {
  76596. data.x = e.clientX;
  76597. data.y = e.clientY;
  76598. }
  76599. }
  76600. };
  76601. VirtualJoystick.prototype._onPointerUp = function (e) {
  76602. if (this._joystickPointerID == e.pointerId) {
  76603. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  76604. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  76605. this._joystickPointerID = -1;
  76606. this.pressed = false;
  76607. }
  76608. else {
  76609. var touch = this._touches.get(e.pointerId.toString());
  76610. if (touch) {
  76611. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  76612. }
  76613. }
  76614. this._deltaJoystickVector.x = 0;
  76615. this._deltaJoystickVector.y = 0;
  76616. this._touches.remove(e.pointerId.toString());
  76617. };
  76618. /**
  76619. * Change the color of the virtual joystick
  76620. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  76621. */
  76622. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  76623. this._joystickColor = newColor;
  76624. };
  76625. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  76626. this._action = action;
  76627. };
  76628. // Define which axis you'd like to control for left & right
  76629. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  76630. switch (axis) {
  76631. case JoystickAxis.X:
  76632. case JoystickAxis.Y:
  76633. case JoystickAxis.Z:
  76634. this._axisTargetedByLeftAndRight = axis;
  76635. break;
  76636. default:
  76637. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76638. break;
  76639. }
  76640. };
  76641. // Define which axis you'd like to control for up & down
  76642. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  76643. switch (axis) {
  76644. case JoystickAxis.X:
  76645. case JoystickAxis.Y:
  76646. case JoystickAxis.Z:
  76647. this._axisTargetedByUpAndDown = axis;
  76648. break;
  76649. default:
  76650. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76651. break;
  76652. }
  76653. };
  76654. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  76655. var _this = this;
  76656. if (this.pressed) {
  76657. this._touches.forEach(function (key, touch) {
  76658. if (touch.pointerId === _this._joystickPointerID) {
  76659. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  76660. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  76661. VirtualJoystick.vjCanvasContext.beginPath();
  76662. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  76663. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76664. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  76665. VirtualJoystick.vjCanvasContext.stroke();
  76666. VirtualJoystick.vjCanvasContext.closePath();
  76667. VirtualJoystick.vjCanvasContext.beginPath();
  76668. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76669. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76670. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  76671. VirtualJoystick.vjCanvasContext.stroke();
  76672. VirtualJoystick.vjCanvasContext.closePath();
  76673. VirtualJoystick.vjCanvasContext.beginPath();
  76674. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76675. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  76676. VirtualJoystick.vjCanvasContext.stroke();
  76677. VirtualJoystick.vjCanvasContext.closePath();
  76678. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  76679. }
  76680. else {
  76681. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  76682. VirtualJoystick.vjCanvasContext.beginPath();
  76683. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  76684. VirtualJoystick.vjCanvasContext.beginPath();
  76685. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  76686. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  76687. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  76688. VirtualJoystick.vjCanvasContext.stroke();
  76689. VirtualJoystick.vjCanvasContext.closePath();
  76690. touch.prevX = touch.x;
  76691. touch.prevY = touch.y;
  76692. }
  76693. ;
  76694. });
  76695. }
  76696. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76697. };
  76698. VirtualJoystick.prototype.releaseCanvas = function () {
  76699. if (VirtualJoystick.vjCanvas) {
  76700. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  76701. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  76702. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  76703. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  76704. window.removeEventListener("resize", this._onResize);
  76705. document.body.removeChild(VirtualJoystick.vjCanvas);
  76706. VirtualJoystick.vjCanvas = null;
  76707. }
  76708. };
  76709. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  76710. VirtualJoystick._globalJoystickIndex = 0;
  76711. return VirtualJoystick;
  76712. }());
  76713. BABYLON.VirtualJoystick = VirtualJoystick;
  76714. })(BABYLON || (BABYLON = {}));
  76715. //# sourceMappingURL=babylon.virtualJoystick.js.map
  76716. var BABYLON;
  76717. (function (BABYLON) {
  76718. // We're mainly based on the logic defined into the FreeCamera code
  76719. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  76720. __extends(VirtualJoysticksCamera, _super);
  76721. function VirtualJoysticksCamera(name, position, scene) {
  76722. var _this = _super.call(this, name, position, scene) || this;
  76723. _this.inputs.addVirtualJoystick();
  76724. return _this;
  76725. }
  76726. VirtualJoysticksCamera.prototype.getClassName = function () {
  76727. return "VirtualJoysticksCamera";
  76728. };
  76729. return VirtualJoysticksCamera;
  76730. }(BABYLON.FreeCamera));
  76731. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  76732. })(BABYLON || (BABYLON = {}));
  76733. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  76734. var BABYLON;
  76735. (function (BABYLON) {
  76736. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  76737. function FreeCameraVirtualJoystickInput() {
  76738. }
  76739. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  76740. return this._leftjoystick;
  76741. };
  76742. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  76743. return this._rightjoystick;
  76744. };
  76745. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  76746. if (this._leftjoystick) {
  76747. var camera = this.camera;
  76748. var speed = camera._computeLocalCameraSpeed() * 50;
  76749. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  76750. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  76751. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  76752. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  76753. if (!this._leftjoystick.pressed) {
  76754. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  76755. }
  76756. if (!this._rightjoystick.pressed) {
  76757. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  76758. }
  76759. }
  76760. };
  76761. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  76762. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  76763. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  76764. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  76765. this._leftjoystick.setJoystickSensibility(0.15);
  76766. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  76767. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  76768. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  76769. this._rightjoystick.reverseUpDown = true;
  76770. this._rightjoystick.setJoystickSensibility(0.05);
  76771. this._rightjoystick.setJoystickColor("yellow");
  76772. };
  76773. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  76774. this._leftjoystick.releaseCanvas();
  76775. this._rightjoystick.releaseCanvas();
  76776. };
  76777. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  76778. return "FreeCameraVirtualJoystickInput";
  76779. };
  76780. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  76781. return "virtualJoystick";
  76782. };
  76783. return FreeCameraVirtualJoystickInput;
  76784. }());
  76785. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  76786. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  76787. })(BABYLON || (BABYLON = {}));
  76788. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  76789. var BABYLON;
  76790. (function (BABYLON) {
  76791. var SimplificationSettings = /** @class */ (function () {
  76792. function SimplificationSettings(quality, distance, optimizeMesh) {
  76793. this.quality = quality;
  76794. this.distance = distance;
  76795. this.optimizeMesh = optimizeMesh;
  76796. }
  76797. return SimplificationSettings;
  76798. }());
  76799. BABYLON.SimplificationSettings = SimplificationSettings;
  76800. var SimplificationQueue = /** @class */ (function () {
  76801. function SimplificationQueue() {
  76802. this.running = false;
  76803. this._simplificationArray = [];
  76804. }
  76805. SimplificationQueue.prototype.addTask = function (task) {
  76806. this._simplificationArray.push(task);
  76807. };
  76808. SimplificationQueue.prototype.executeNext = function () {
  76809. var task = this._simplificationArray.pop();
  76810. if (task) {
  76811. this.running = true;
  76812. this.runSimplification(task);
  76813. }
  76814. else {
  76815. this.running = false;
  76816. }
  76817. };
  76818. SimplificationQueue.prototype.runSimplification = function (task) {
  76819. var _this = this;
  76820. if (task.parallelProcessing) {
  76821. //parallel simplifier
  76822. task.settings.forEach(function (setting) {
  76823. var simplifier = _this.getSimplifier(task);
  76824. simplifier.simplify(setting, function (newMesh) {
  76825. task.mesh.addLODLevel(setting.distance, newMesh);
  76826. newMesh.isVisible = true;
  76827. //check if it is the last
  76828. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  76829. //all done, run the success callback.
  76830. task.successCallback();
  76831. }
  76832. _this.executeNext();
  76833. });
  76834. });
  76835. }
  76836. else {
  76837. //single simplifier.
  76838. var simplifier = this.getSimplifier(task);
  76839. var runDecimation = function (setting, callback) {
  76840. simplifier.simplify(setting, function (newMesh) {
  76841. task.mesh.addLODLevel(setting.distance, newMesh);
  76842. newMesh.isVisible = true;
  76843. //run the next quality level
  76844. callback();
  76845. });
  76846. };
  76847. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  76848. runDecimation(task.settings[loop.index], function () {
  76849. loop.executeNext();
  76850. });
  76851. }, function () {
  76852. //execution ended, run the success callback.
  76853. if (task.successCallback) {
  76854. task.successCallback();
  76855. }
  76856. _this.executeNext();
  76857. });
  76858. }
  76859. };
  76860. SimplificationQueue.prototype.getSimplifier = function (task) {
  76861. switch (task.simplificationType) {
  76862. case SimplificationType.QUADRATIC:
  76863. default:
  76864. return new QuadraticErrorSimplification(task.mesh);
  76865. }
  76866. };
  76867. return SimplificationQueue;
  76868. }());
  76869. BABYLON.SimplificationQueue = SimplificationQueue;
  76870. /**
  76871. * The implemented types of simplification.
  76872. * At the moment only Quadratic Error Decimation is implemented.
  76873. */
  76874. var SimplificationType;
  76875. (function (SimplificationType) {
  76876. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  76877. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  76878. var DecimationTriangle = /** @class */ (function () {
  76879. function DecimationTriangle(vertices) {
  76880. this.vertices = vertices;
  76881. this.error = new Array(4);
  76882. this.deleted = false;
  76883. this.isDirty = false;
  76884. this.deletePending = false;
  76885. this.borderFactor = 0;
  76886. }
  76887. return DecimationTriangle;
  76888. }());
  76889. BABYLON.DecimationTriangle = DecimationTriangle;
  76890. var DecimationVertex = /** @class */ (function () {
  76891. function DecimationVertex(position, id) {
  76892. this.position = position;
  76893. this.id = id;
  76894. this.isBorder = true;
  76895. this.q = new QuadraticMatrix();
  76896. this.triangleCount = 0;
  76897. this.triangleStart = 0;
  76898. this.originalOffsets = [];
  76899. }
  76900. DecimationVertex.prototype.updatePosition = function (newPosition) {
  76901. this.position.copyFrom(newPosition);
  76902. };
  76903. return DecimationVertex;
  76904. }());
  76905. BABYLON.DecimationVertex = DecimationVertex;
  76906. var QuadraticMatrix = /** @class */ (function () {
  76907. function QuadraticMatrix(data) {
  76908. this.data = new Array(10);
  76909. for (var i = 0; i < 10; ++i) {
  76910. if (data && data[i]) {
  76911. this.data[i] = data[i];
  76912. }
  76913. else {
  76914. this.data[i] = 0;
  76915. }
  76916. }
  76917. }
  76918. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  76919. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  76920. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  76921. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  76922. return det;
  76923. };
  76924. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  76925. for (var i = 0; i < 10; ++i) {
  76926. this.data[i] += matrix.data[i];
  76927. }
  76928. };
  76929. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  76930. for (var i = 0; i < 10; ++i) {
  76931. this.data[i] += data[i];
  76932. }
  76933. };
  76934. QuadraticMatrix.prototype.add = function (matrix) {
  76935. var m = new QuadraticMatrix();
  76936. for (var i = 0; i < 10; ++i) {
  76937. m.data[i] = this.data[i] + matrix.data[i];
  76938. }
  76939. return m;
  76940. };
  76941. QuadraticMatrix.FromData = function (a, b, c, d) {
  76942. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  76943. };
  76944. //returning an array to avoid garbage collection
  76945. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  76946. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  76947. };
  76948. return QuadraticMatrix;
  76949. }());
  76950. BABYLON.QuadraticMatrix = QuadraticMatrix;
  76951. var Reference = /** @class */ (function () {
  76952. function Reference(vertexId, triangleId) {
  76953. this.vertexId = vertexId;
  76954. this.triangleId = triangleId;
  76955. }
  76956. return Reference;
  76957. }());
  76958. BABYLON.Reference = Reference;
  76959. /**
  76960. * An implementation of the Quadratic Error simplification algorithm.
  76961. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  76962. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  76963. * @author RaananW
  76964. */
  76965. var QuadraticErrorSimplification = /** @class */ (function () {
  76966. function QuadraticErrorSimplification(_mesh) {
  76967. this._mesh = _mesh;
  76968. this.syncIterations = 5000;
  76969. this.aggressiveness = 7;
  76970. this.decimationIterations = 100;
  76971. this.boundingBoxEpsilon = BABYLON.Epsilon;
  76972. }
  76973. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  76974. var _this = this;
  76975. this.initDecimatedMesh();
  76976. //iterating through the submeshes array, one after the other.
  76977. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  76978. _this.initWithMesh(loop.index, function () {
  76979. _this.runDecimation(settings, loop.index, function () {
  76980. loop.executeNext();
  76981. });
  76982. }, settings.optimizeMesh);
  76983. }, function () {
  76984. setTimeout(function () {
  76985. successCallback(_this._reconstructedMesh);
  76986. }, 0);
  76987. });
  76988. };
  76989. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  76990. var _this = this;
  76991. var targetCount = ~~(this.triangles.length * settings.quality);
  76992. var deletedTriangles = 0;
  76993. var triangleCount = this.triangles.length;
  76994. var iterationFunction = function (iteration, callback) {
  76995. setTimeout(function () {
  76996. if (iteration % 5 === 0) {
  76997. _this.updateMesh(iteration === 0);
  76998. }
  76999. for (var i = 0; i < _this.triangles.length; ++i) {
  77000. _this.triangles[i].isDirty = false;
  77001. }
  77002. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  77003. var trianglesIterator = function (i) {
  77004. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  77005. var t = _this.triangles[tIdx];
  77006. if (!t)
  77007. return;
  77008. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  77009. return;
  77010. }
  77011. for (var j = 0; j < 3; ++j) {
  77012. if (t.error[j] < threshold) {
  77013. var deleted0 = [];
  77014. var deleted1 = [];
  77015. var v0 = t.vertices[j];
  77016. var v1 = t.vertices[(j + 1) % 3];
  77017. if (v0.isBorder || v1.isBorder)
  77018. continue;
  77019. var p = BABYLON.Vector3.Zero();
  77020. var n = BABYLON.Vector3.Zero();
  77021. var uv = BABYLON.Vector2.Zero();
  77022. var color = new BABYLON.Color4(0, 0, 0, 1);
  77023. _this.calculateError(v0, v1, p, n, uv, color);
  77024. var delTr = new Array();
  77025. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  77026. continue;
  77027. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  77028. continue;
  77029. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  77030. continue;
  77031. var uniqueArray = new Array();
  77032. delTr.forEach(function (deletedT) {
  77033. if (uniqueArray.indexOf(deletedT) === -1) {
  77034. deletedT.deletePending = true;
  77035. uniqueArray.push(deletedT);
  77036. }
  77037. });
  77038. if (uniqueArray.length % 2 !== 0) {
  77039. continue;
  77040. }
  77041. v0.q = v1.q.add(v0.q);
  77042. v0.updatePosition(p);
  77043. var tStart = _this.references.length;
  77044. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  77045. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  77046. var tCount = _this.references.length - tStart;
  77047. if (tCount <= v0.triangleCount) {
  77048. if (tCount) {
  77049. for (var c = 0; c < tCount; c++) {
  77050. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  77051. }
  77052. }
  77053. }
  77054. else {
  77055. v0.triangleStart = tStart;
  77056. }
  77057. v0.triangleCount = tCount;
  77058. break;
  77059. }
  77060. }
  77061. };
  77062. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  77063. }, 0);
  77064. };
  77065. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  77066. if (triangleCount - deletedTriangles <= targetCount)
  77067. loop.breakLoop();
  77068. else {
  77069. iterationFunction(loop.index, function () {
  77070. loop.executeNext();
  77071. });
  77072. }
  77073. }, function () {
  77074. setTimeout(function () {
  77075. //reconstruct this part of the mesh
  77076. _this.reconstructMesh(submeshIndex);
  77077. successCallback();
  77078. }, 0);
  77079. });
  77080. };
  77081. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  77082. var _this = this;
  77083. this.vertices = [];
  77084. this.triangles = [];
  77085. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  77086. var indices = this._mesh.getIndices();
  77087. var submesh = this._mesh.subMeshes[submeshIndex];
  77088. var findInVertices = function (positionToSearch) {
  77089. if (optimizeMesh) {
  77090. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  77091. if (_this.vertices[ii].position.equals(positionToSearch)) {
  77092. return _this.vertices[ii];
  77093. }
  77094. }
  77095. }
  77096. return null;
  77097. };
  77098. var vertexReferences = [];
  77099. var vertexInit = function (i) {
  77100. if (!positionData) {
  77101. return;
  77102. }
  77103. var offset = i + submesh.verticesStart;
  77104. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  77105. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  77106. vertex.originalOffsets.push(offset);
  77107. if (vertex.id === _this.vertices.length) {
  77108. _this.vertices.push(vertex);
  77109. }
  77110. vertexReferences.push(vertex.id);
  77111. };
  77112. //var totalVertices = mesh.getTotalVertices();
  77113. var totalVertices = submesh.verticesCount;
  77114. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  77115. var indicesInit = function (i) {
  77116. if (!indices) {
  77117. return;
  77118. }
  77119. var offset = (submesh.indexStart / 3) + i;
  77120. var pos = (offset * 3);
  77121. var i0 = indices[pos + 0];
  77122. var i1 = indices[pos + 1];
  77123. var i2 = indices[pos + 2];
  77124. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  77125. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  77126. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  77127. var triangle = new DecimationTriangle([v0, v1, v2]);
  77128. triangle.originalOffset = pos;
  77129. _this.triangles.push(triangle);
  77130. };
  77131. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  77132. _this.init(callback);
  77133. });
  77134. });
  77135. };
  77136. QuadraticErrorSimplification.prototype.init = function (callback) {
  77137. var _this = this;
  77138. var triangleInit1 = function (i) {
  77139. var t = _this.triangles[i];
  77140. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  77141. for (var j = 0; j < 3; j++) {
  77142. 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))));
  77143. }
  77144. };
  77145. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  77146. var triangleInit2 = function (i) {
  77147. var t = _this.triangles[i];
  77148. for (var j = 0; j < 3; ++j) {
  77149. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  77150. }
  77151. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77152. };
  77153. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  77154. callback();
  77155. });
  77156. });
  77157. };
  77158. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  77159. var newTriangles = [];
  77160. var i;
  77161. for (i = 0; i < this.vertices.length; ++i) {
  77162. this.vertices[i].triangleCount = 0;
  77163. }
  77164. var t;
  77165. var j;
  77166. for (i = 0; i < this.triangles.length; ++i) {
  77167. if (!this.triangles[i].deleted) {
  77168. t = this.triangles[i];
  77169. for (j = 0; j < 3; ++j) {
  77170. t.vertices[j].triangleCount = 1;
  77171. }
  77172. newTriangles.push(t);
  77173. }
  77174. }
  77175. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  77176. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  77177. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  77178. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  77179. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  77180. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  77181. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  77182. var vertexCount = 0;
  77183. for (i = 0; i < this.vertices.length; ++i) {
  77184. var vertex = this.vertices[i];
  77185. vertex.id = vertexCount;
  77186. if (vertex.triangleCount) {
  77187. vertex.originalOffsets.forEach(function (originalOffset) {
  77188. if (!normalData) {
  77189. return;
  77190. }
  77191. newPositionData.push(vertex.position.x);
  77192. newPositionData.push(vertex.position.y);
  77193. newPositionData.push(vertex.position.z);
  77194. newNormalData.push(normalData[originalOffset * 3]);
  77195. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  77196. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  77197. if (uvs && uvs.length) {
  77198. newUVsData.push(uvs[(originalOffset * 2)]);
  77199. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  77200. }
  77201. else if (colorsData && colorsData.length) {
  77202. newColorsData.push(colorsData[(originalOffset * 4)]);
  77203. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  77204. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  77205. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  77206. }
  77207. ++vertexCount;
  77208. });
  77209. }
  77210. }
  77211. var startingIndex = this._reconstructedMesh.getTotalIndices();
  77212. var startingVertex = this._reconstructedMesh.getTotalVertices();
  77213. var submeshesArray = this._reconstructedMesh.subMeshes;
  77214. this._reconstructedMesh.subMeshes = [];
  77215. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  77216. var originalIndices = this._mesh.getIndices();
  77217. for (i = 0; i < newTriangles.length; ++i) {
  77218. t = newTriangles[i]; //now get the new referencing point for each vertex
  77219. [0, 1, 2].forEach(function (idx) {
  77220. var id = originalIndices[t.originalOffset + idx];
  77221. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  77222. if (offset < 0)
  77223. offset = 0;
  77224. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  77225. });
  77226. }
  77227. //overwriting the old vertex buffers and indices.
  77228. this._reconstructedMesh.setIndices(newIndicesArray);
  77229. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  77230. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  77231. if (newUVsData.length > 0)
  77232. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  77233. if (newColorsData.length > 0)
  77234. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  77235. //create submesh
  77236. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  77237. if (submeshIndex > 0) {
  77238. this._reconstructedMesh.subMeshes = [];
  77239. submeshesArray.forEach(function (submesh) {
  77240. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  77241. });
  77242. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  77243. }
  77244. };
  77245. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  77246. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  77247. this._reconstructedMesh.material = this._mesh.material;
  77248. this._reconstructedMesh.parent = this._mesh.parent;
  77249. this._reconstructedMesh.isVisible = false;
  77250. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  77251. };
  77252. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  77253. for (var i = 0; i < vertex1.triangleCount; ++i) {
  77254. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  77255. if (t.deleted)
  77256. continue;
  77257. var s = this.references[vertex1.triangleStart + i].vertexId;
  77258. var v1 = t.vertices[(s + 1) % 3];
  77259. var v2 = t.vertices[(s + 2) % 3];
  77260. if ((v1 === vertex2 || v2 === vertex2)) {
  77261. deletedArray[i] = true;
  77262. delTr.push(t);
  77263. continue;
  77264. }
  77265. var d1 = v1.position.subtract(point);
  77266. d1 = d1.normalize();
  77267. var d2 = v2.position.subtract(point);
  77268. d2 = d2.normalize();
  77269. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  77270. return true;
  77271. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  77272. deletedArray[i] = false;
  77273. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  77274. return true;
  77275. }
  77276. return false;
  77277. };
  77278. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  77279. var newDeleted = deletedTriangles;
  77280. for (var i = 0; i < vertex.triangleCount; ++i) {
  77281. var ref = this.references[vertex.triangleStart + i];
  77282. var t = this.triangles[ref.triangleId];
  77283. if (t.deleted)
  77284. continue;
  77285. if (deletedArray[i] && t.deletePending) {
  77286. t.deleted = true;
  77287. newDeleted++;
  77288. continue;
  77289. }
  77290. t.vertices[ref.vertexId] = origVertex;
  77291. t.isDirty = true;
  77292. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  77293. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  77294. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  77295. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77296. this.references.push(ref);
  77297. }
  77298. return newDeleted;
  77299. };
  77300. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  77301. for (var i = 0; i < this.vertices.length; ++i) {
  77302. var vCount = [];
  77303. var vId = [];
  77304. var v = this.vertices[i];
  77305. var j;
  77306. for (j = 0; j < v.triangleCount; ++j) {
  77307. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  77308. for (var ii = 0; ii < 3; ii++) {
  77309. var ofs = 0;
  77310. var vv = triangle.vertices[ii];
  77311. while (ofs < vCount.length) {
  77312. if (vId[ofs] === vv.id)
  77313. break;
  77314. ++ofs;
  77315. }
  77316. if (ofs === vCount.length) {
  77317. vCount.push(1);
  77318. vId.push(vv.id);
  77319. }
  77320. else {
  77321. vCount[ofs]++;
  77322. }
  77323. }
  77324. }
  77325. for (j = 0; j < vCount.length; ++j) {
  77326. if (vCount[j] === 1) {
  77327. this.vertices[vId[j]].isBorder = true;
  77328. }
  77329. else {
  77330. this.vertices[vId[j]].isBorder = false;
  77331. }
  77332. }
  77333. }
  77334. };
  77335. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  77336. if (identifyBorders === void 0) { identifyBorders = false; }
  77337. var i;
  77338. if (!identifyBorders) {
  77339. var newTrianglesVector = [];
  77340. for (i = 0; i < this.triangles.length; ++i) {
  77341. if (!this.triangles[i].deleted) {
  77342. newTrianglesVector.push(this.triangles[i]);
  77343. }
  77344. }
  77345. this.triangles = newTrianglesVector;
  77346. }
  77347. for (i = 0; i < this.vertices.length; ++i) {
  77348. this.vertices[i].triangleCount = 0;
  77349. this.vertices[i].triangleStart = 0;
  77350. }
  77351. var t;
  77352. var j;
  77353. var v;
  77354. for (i = 0; i < this.triangles.length; ++i) {
  77355. t = this.triangles[i];
  77356. for (j = 0; j < 3; ++j) {
  77357. v = t.vertices[j];
  77358. v.triangleCount++;
  77359. }
  77360. }
  77361. var tStart = 0;
  77362. for (i = 0; i < this.vertices.length; ++i) {
  77363. this.vertices[i].triangleStart = tStart;
  77364. tStart += this.vertices[i].triangleCount;
  77365. this.vertices[i].triangleCount = 0;
  77366. }
  77367. var newReferences = new Array(this.triangles.length * 3);
  77368. for (i = 0; i < this.triangles.length; ++i) {
  77369. t = this.triangles[i];
  77370. for (j = 0; j < 3; ++j) {
  77371. v = t.vertices[j];
  77372. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  77373. v.triangleCount++;
  77374. }
  77375. }
  77376. this.references = newReferences;
  77377. if (identifyBorders) {
  77378. this.identifyBorder();
  77379. }
  77380. };
  77381. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  77382. var x = point.x;
  77383. var y = point.y;
  77384. var z = point.z;
  77385. 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
  77386. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  77387. };
  77388. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  77389. var q = vertex1.q.add(vertex2.q);
  77390. var border = vertex1.isBorder && vertex2.isBorder;
  77391. var error = 0;
  77392. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  77393. if (qDet !== 0 && !border) {
  77394. if (!pointResult) {
  77395. pointResult = BABYLON.Vector3.Zero();
  77396. }
  77397. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  77398. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  77399. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  77400. error = this.vertexError(q, pointResult);
  77401. }
  77402. else {
  77403. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  77404. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  77405. var error1 = this.vertexError(q, vertex1.position);
  77406. var error2 = this.vertexError(q, vertex2.position);
  77407. var error3 = this.vertexError(q, p3);
  77408. error = Math.min(error1, error2, error3);
  77409. if (error === error1) {
  77410. if (pointResult) {
  77411. pointResult.copyFrom(vertex1.position);
  77412. }
  77413. }
  77414. else if (error === error2) {
  77415. if (pointResult) {
  77416. pointResult.copyFrom(vertex2.position);
  77417. }
  77418. }
  77419. else {
  77420. if (pointResult) {
  77421. pointResult.copyFrom(p3);
  77422. }
  77423. }
  77424. }
  77425. return error;
  77426. };
  77427. return QuadraticErrorSimplification;
  77428. }());
  77429. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  77430. })(BABYLON || (BABYLON = {}));
  77431. //# sourceMappingURL=babylon.meshSimplification.js.map
  77432. var BABYLON;
  77433. (function (BABYLON) {
  77434. var MeshLODLevel = /** @class */ (function () {
  77435. function MeshLODLevel(distance, mesh) {
  77436. this.distance = distance;
  77437. this.mesh = mesh;
  77438. }
  77439. return MeshLODLevel;
  77440. }());
  77441. BABYLON.MeshLODLevel = MeshLODLevel;
  77442. })(BABYLON || (BABYLON = {}));
  77443. //# sourceMappingURL=babylon.meshLODLevel.js.map
  77444. var BABYLON;
  77445. (function (BABYLON) {
  77446. /**
  77447. * Defines the root class used to create scene optimization to use with SceneOptimizer
  77448. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77449. */
  77450. var SceneOptimization = /** @class */ (function () {
  77451. /**
  77452. * Creates the SceneOptimization object
  77453. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77454. * @param desc defines the description associated with the optimization
  77455. */
  77456. function SceneOptimization(
  77457. /**
  77458. * Defines the priority of this optimization (0 by default which means first in the list)
  77459. */
  77460. priority) {
  77461. if (priority === void 0) { priority = 0; }
  77462. this.priority = priority;
  77463. }
  77464. /**
  77465. * Gets a string describing the action executed by the current optimization
  77466. * @returns description string
  77467. */
  77468. SceneOptimization.prototype.getDescription = function () {
  77469. return "";
  77470. };
  77471. /**
  77472. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77473. * @param scene defines the current scene where to apply this optimization
  77474. * @param optimizer defines the current optimizer
  77475. * @returns true if everything that can be done was applied
  77476. */
  77477. SceneOptimization.prototype.apply = function (scene, optimizer) {
  77478. return true;
  77479. };
  77480. ;
  77481. return SceneOptimization;
  77482. }());
  77483. BABYLON.SceneOptimization = SceneOptimization;
  77484. /**
  77485. * Defines an optimization used to reduce the size of render target textures
  77486. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77487. */
  77488. var TextureOptimization = /** @class */ (function (_super) {
  77489. __extends(TextureOptimization, _super);
  77490. /**
  77491. * Creates the TextureOptimization object
  77492. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77493. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  77494. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77495. */
  77496. function TextureOptimization(
  77497. /**
  77498. * Defines the priority of this optimization (0 by default which means first in the list)
  77499. */
  77500. priority,
  77501. /**
  77502. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  77503. */
  77504. maximumSize,
  77505. /**
  77506. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77507. */
  77508. step) {
  77509. if (priority === void 0) { priority = 0; }
  77510. if (maximumSize === void 0) { maximumSize = 1024; }
  77511. if (step === void 0) { step = 0.5; }
  77512. var _this = _super.call(this, priority) || this;
  77513. _this.priority = priority;
  77514. _this.maximumSize = maximumSize;
  77515. _this.step = step;
  77516. return _this;
  77517. }
  77518. /**
  77519. * Gets a string describing the action executed by the current optimization
  77520. * @returns description string
  77521. */
  77522. TextureOptimization.prototype.getDescription = function () {
  77523. return "Reducing render target texture size to " + this.maximumSize;
  77524. };
  77525. /**
  77526. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77527. * @param scene defines the current scene where to apply this optimization
  77528. * @param optimizer defines the current optimizer
  77529. * @returns true if everything that can be done was applied
  77530. */
  77531. TextureOptimization.prototype.apply = function (scene, optimizer) {
  77532. var allDone = true;
  77533. for (var index = 0; index < scene.textures.length; index++) {
  77534. var texture = scene.textures[index];
  77535. if (!texture.canRescale || texture.getContext) {
  77536. continue;
  77537. }
  77538. var currentSize = texture.getSize();
  77539. var maxDimension = Math.max(currentSize.width, currentSize.height);
  77540. if (maxDimension > this.maximumSize) {
  77541. texture.scale(this.step);
  77542. allDone = false;
  77543. }
  77544. }
  77545. return allDone;
  77546. };
  77547. return TextureOptimization;
  77548. }(SceneOptimization));
  77549. BABYLON.TextureOptimization = TextureOptimization;
  77550. /**
  77551. * Defines an optimization used to increase or decrease the rendering resolution
  77552. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77553. */
  77554. var HardwareScalingOptimization = /** @class */ (function (_super) {
  77555. __extends(HardwareScalingOptimization, _super);
  77556. /**
  77557. * Creates the HardwareScalingOptimization object
  77558. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77559. * @param maximumScale defines the maximum scale to use (2 by default)
  77560. * @param step defines the step to use between two passes (0.5 by default)
  77561. */
  77562. function HardwareScalingOptimization(
  77563. /**
  77564. * Defines the priority of this optimization (0 by default which means first in the list)
  77565. */
  77566. priority,
  77567. /**
  77568. * Defines the maximum scale to use (2 by default)
  77569. */
  77570. maximumScale,
  77571. /**
  77572. * Defines the step to use between two passes (0.5 by default)
  77573. */
  77574. step) {
  77575. if (priority === void 0) { priority = 0; }
  77576. if (maximumScale === void 0) { maximumScale = 2; }
  77577. if (step === void 0) { step = 0.25; }
  77578. var _this = _super.call(this, priority) || this;
  77579. _this.priority = priority;
  77580. _this.maximumScale = maximumScale;
  77581. _this.step = step;
  77582. _this._currentScale = -1;
  77583. _this._directionOffset = 1;
  77584. return _this;
  77585. }
  77586. /**
  77587. * Gets a string describing the action executed by the current optimization
  77588. * @return description string
  77589. */
  77590. HardwareScalingOptimization.prototype.getDescription = function () {
  77591. return "Setting hardware scaling level to " + this._currentScale;
  77592. };
  77593. /**
  77594. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77595. * @param scene defines the current scene where to apply this optimization
  77596. * @param optimizer defines the current optimizer
  77597. * @returns true if everything that can be done was applied
  77598. */
  77599. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  77600. if (this._currentScale === -1) {
  77601. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  77602. if (this._currentScale > this.maximumScale) {
  77603. this._directionOffset = -1;
  77604. }
  77605. }
  77606. this._currentScale += this._directionOffset * this.step;
  77607. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  77608. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  77609. };
  77610. ;
  77611. return HardwareScalingOptimization;
  77612. }(SceneOptimization));
  77613. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  77614. /**
  77615. * Defines an optimization used to remove shadows
  77616. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77617. */
  77618. var ShadowsOptimization = /** @class */ (function (_super) {
  77619. __extends(ShadowsOptimization, _super);
  77620. function ShadowsOptimization() {
  77621. return _super !== null && _super.apply(this, arguments) || this;
  77622. }
  77623. /**
  77624. * Gets a string describing the action executed by the current optimization
  77625. * @return description string
  77626. */
  77627. ShadowsOptimization.prototype.getDescription = function () {
  77628. return "Turning shadows on/off";
  77629. };
  77630. /**
  77631. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77632. * @param scene defines the current scene where to apply this optimization
  77633. * @param optimizer defines the current optimizer
  77634. * @returns true if everything that can be done was applied
  77635. */
  77636. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  77637. scene.shadowsEnabled = optimizer.isInImprovementMode;
  77638. return true;
  77639. };
  77640. ;
  77641. return ShadowsOptimization;
  77642. }(SceneOptimization));
  77643. BABYLON.ShadowsOptimization = ShadowsOptimization;
  77644. /**
  77645. * Defines an optimization used to turn post-processes off
  77646. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77647. */
  77648. var PostProcessesOptimization = /** @class */ (function (_super) {
  77649. __extends(PostProcessesOptimization, _super);
  77650. function PostProcessesOptimization() {
  77651. return _super !== null && _super.apply(this, arguments) || this;
  77652. }
  77653. /**
  77654. * Gets a string describing the action executed by the current optimization
  77655. * @return description string
  77656. */
  77657. PostProcessesOptimization.prototype.getDescription = function () {
  77658. return "Turning post-processes on/off";
  77659. };
  77660. /**
  77661. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77662. * @param scene defines the current scene where to apply this optimization
  77663. * @param optimizer defines the current optimizer
  77664. * @returns true if everything that can be done was applied
  77665. */
  77666. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  77667. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  77668. return true;
  77669. };
  77670. ;
  77671. return PostProcessesOptimization;
  77672. }(SceneOptimization));
  77673. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  77674. /**
  77675. * Defines an optimization used to turn lens flares off
  77676. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77677. */
  77678. var LensFlaresOptimization = /** @class */ (function (_super) {
  77679. __extends(LensFlaresOptimization, _super);
  77680. function LensFlaresOptimization() {
  77681. return _super !== null && _super.apply(this, arguments) || this;
  77682. }
  77683. /**
  77684. * Gets a string describing the action executed by the current optimization
  77685. * @return description string
  77686. */
  77687. LensFlaresOptimization.prototype.getDescription = function () {
  77688. return "Turning lens flares on/off";
  77689. };
  77690. /**
  77691. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77692. * @param scene defines the current scene where to apply this optimization
  77693. * @param optimizer defines the current optimizer
  77694. * @returns true if everything that can be done was applied
  77695. */
  77696. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  77697. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  77698. return true;
  77699. };
  77700. ;
  77701. return LensFlaresOptimization;
  77702. }(SceneOptimization));
  77703. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  77704. /**
  77705. * Defines an optimization based on user defined callback.
  77706. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77707. */
  77708. var CustomOptimization = /** @class */ (function (_super) {
  77709. __extends(CustomOptimization, _super);
  77710. function CustomOptimization() {
  77711. return _super !== null && _super.apply(this, arguments) || this;
  77712. }
  77713. /**
  77714. * Gets a string describing the action executed by the current optimization
  77715. * @returns description string
  77716. */
  77717. CustomOptimization.prototype.getDescription = function () {
  77718. if (this.onGetDescription) {
  77719. return this.onGetDescription();
  77720. }
  77721. return "Running user defined callback";
  77722. };
  77723. /**
  77724. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77725. * @param scene defines the current scene where to apply this optimization
  77726. * @param optimizer defines the current optimizer
  77727. * @returns true if everything that can be done was applied
  77728. */
  77729. CustomOptimization.prototype.apply = function (scene, optimizer) {
  77730. if (this.onApply) {
  77731. return this.onApply(scene, optimizer);
  77732. }
  77733. return true;
  77734. };
  77735. ;
  77736. return CustomOptimization;
  77737. }(SceneOptimization));
  77738. BABYLON.CustomOptimization = CustomOptimization;
  77739. /**
  77740. * Defines an optimization used to turn particles off
  77741. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77742. */
  77743. var ParticlesOptimization = /** @class */ (function (_super) {
  77744. __extends(ParticlesOptimization, _super);
  77745. function ParticlesOptimization() {
  77746. return _super !== null && _super.apply(this, arguments) || this;
  77747. }
  77748. /**
  77749. * Gets a string describing the action executed by the current optimization
  77750. * @return description string
  77751. */
  77752. ParticlesOptimization.prototype.getDescription = function () {
  77753. return "Turning particles on/off";
  77754. };
  77755. /**
  77756. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77757. * @param scene defines the current scene where to apply this optimization
  77758. * @param optimizer defines the current optimizer
  77759. * @returns true if everything that can be done was applied
  77760. */
  77761. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  77762. scene.particlesEnabled = optimizer.isInImprovementMode;
  77763. return true;
  77764. };
  77765. ;
  77766. return ParticlesOptimization;
  77767. }(SceneOptimization));
  77768. BABYLON.ParticlesOptimization = ParticlesOptimization;
  77769. /**
  77770. * Defines an optimization used to turn render targets off
  77771. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77772. */
  77773. var RenderTargetsOptimization = /** @class */ (function (_super) {
  77774. __extends(RenderTargetsOptimization, _super);
  77775. function RenderTargetsOptimization() {
  77776. return _super !== null && _super.apply(this, arguments) || this;
  77777. }
  77778. /**
  77779. * Gets a string describing the action executed by the current optimization
  77780. * @return description string
  77781. */
  77782. RenderTargetsOptimization.prototype.getDescription = function () {
  77783. return "Turning render targets off";
  77784. };
  77785. /**
  77786. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77787. * @param scene defines the current scene where to apply this optimization
  77788. * @param optimizer defines the current optimizer
  77789. * @returns true if everything that can be done was applied
  77790. */
  77791. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  77792. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  77793. return true;
  77794. };
  77795. ;
  77796. return RenderTargetsOptimization;
  77797. }(SceneOptimization));
  77798. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  77799. /**
  77800. * Defines an optimization used to merge meshes with compatible materials
  77801. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77802. */
  77803. var MergeMeshesOptimization = /** @class */ (function (_super) {
  77804. __extends(MergeMeshesOptimization, _super);
  77805. function MergeMeshesOptimization() {
  77806. var _this = _super !== null && _super.apply(this, arguments) || this;
  77807. _this._canBeMerged = function (abstractMesh) {
  77808. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  77809. return false;
  77810. }
  77811. var mesh = abstractMesh;
  77812. if (!mesh.isVisible || !mesh.isEnabled()) {
  77813. return false;
  77814. }
  77815. if (mesh.instances.length > 0) {
  77816. return false;
  77817. }
  77818. if (mesh.skeleton || mesh.hasLODLevels) {
  77819. return false;
  77820. }
  77821. if (mesh.parent) {
  77822. return false;
  77823. }
  77824. return true;
  77825. };
  77826. return _this;
  77827. }
  77828. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  77829. /**
  77830. * Gets or sets a boolean which defines if optimization octree has to be updated
  77831. */
  77832. get: function () {
  77833. return MergeMeshesOptimization._UpdateSelectionTree;
  77834. },
  77835. /**
  77836. * Gets or sets a boolean which defines if optimization octree has to be updated
  77837. */
  77838. set: function (value) {
  77839. MergeMeshesOptimization._UpdateSelectionTree = value;
  77840. },
  77841. enumerable: true,
  77842. configurable: true
  77843. });
  77844. /**
  77845. * Gets a string describing the action executed by the current optimization
  77846. * @return description string
  77847. */
  77848. MergeMeshesOptimization.prototype.getDescription = function () {
  77849. return "Merging similar meshes together";
  77850. };
  77851. /**
  77852. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77853. * @param scene defines the current scene where to apply this optimization
  77854. * @param optimizer defines the current optimizer
  77855. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  77856. * @returns true if everything that can be done was applied
  77857. */
  77858. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  77859. var globalPool = scene.meshes.slice(0);
  77860. var globalLength = globalPool.length;
  77861. for (var index = 0; index < globalLength; index++) {
  77862. var currentPool = new Array();
  77863. var current = globalPool[index];
  77864. // Checks
  77865. if (!this._canBeMerged(current)) {
  77866. continue;
  77867. }
  77868. currentPool.push(current);
  77869. // Find compatible meshes
  77870. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  77871. var otherMesh = globalPool[subIndex];
  77872. if (!this._canBeMerged(otherMesh)) {
  77873. continue;
  77874. }
  77875. if (otherMesh.material !== current.material) {
  77876. continue;
  77877. }
  77878. if (otherMesh.checkCollisions !== current.checkCollisions) {
  77879. continue;
  77880. }
  77881. currentPool.push(otherMesh);
  77882. globalLength--;
  77883. globalPool.splice(subIndex, 1);
  77884. subIndex--;
  77885. }
  77886. if (currentPool.length < 2) {
  77887. continue;
  77888. }
  77889. // Merge meshes
  77890. BABYLON.Mesh.MergeMeshes(currentPool);
  77891. }
  77892. if (updateSelectionTree != undefined) {
  77893. if (updateSelectionTree) {
  77894. scene.createOrUpdateSelectionOctree();
  77895. }
  77896. }
  77897. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  77898. scene.createOrUpdateSelectionOctree();
  77899. }
  77900. return true;
  77901. };
  77902. ;
  77903. MergeMeshesOptimization._UpdateSelectionTree = false;
  77904. return MergeMeshesOptimization;
  77905. }(SceneOptimization));
  77906. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  77907. /**
  77908. * Defines a list of options used by SceneOptimizer
  77909. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77910. */
  77911. var SceneOptimizerOptions = /** @class */ (function () {
  77912. /**
  77913. * Creates a new list of options used by SceneOptimizer
  77914. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  77915. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  77916. */
  77917. function SceneOptimizerOptions(
  77918. /**
  77919. * Defines the target frame rate to reach (60 by default)
  77920. */
  77921. targetFrameRate,
  77922. /**
  77923. * Defines the interval between two checkes (2000ms by default)
  77924. */
  77925. trackerDuration) {
  77926. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  77927. if (trackerDuration === void 0) { trackerDuration = 2000; }
  77928. this.targetFrameRate = targetFrameRate;
  77929. this.trackerDuration = trackerDuration;
  77930. /**
  77931. * Gets the list of optimizations to apply
  77932. */
  77933. this.optimizations = new Array();
  77934. }
  77935. /**
  77936. * Add a new optimization
  77937. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  77938. * @returns the current SceneOptimizerOptions
  77939. */
  77940. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  77941. this.optimizations.push(optimization);
  77942. return this;
  77943. };
  77944. /**
  77945. * Add a new custom optimization
  77946. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  77947. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  77948. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77949. * @returns the current SceneOptimizerOptions
  77950. */
  77951. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  77952. if (priority === void 0) { priority = 0; }
  77953. var optimization = new CustomOptimization(priority);
  77954. optimization.onApply = onApply;
  77955. optimization.onGetDescription = onGetDescription;
  77956. this.optimizations.push(optimization);
  77957. return this;
  77958. };
  77959. /**
  77960. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  77961. * @param targetFrameRate defines the target frame rate (60 by default)
  77962. * @returns a SceneOptimizerOptions object
  77963. */
  77964. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  77965. var result = new SceneOptimizerOptions(targetFrameRate);
  77966. var priority = 0;
  77967. result.addOptimization(new MergeMeshesOptimization(priority));
  77968. result.addOptimization(new ShadowsOptimization(priority));
  77969. result.addOptimization(new LensFlaresOptimization(priority));
  77970. // Next priority
  77971. priority++;
  77972. result.addOptimization(new PostProcessesOptimization(priority));
  77973. result.addOptimization(new ParticlesOptimization(priority));
  77974. // Next priority
  77975. priority++;
  77976. result.addOptimization(new TextureOptimization(priority, 1024));
  77977. return result;
  77978. };
  77979. /**
  77980. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  77981. * @param targetFrameRate defines the target frame rate (60 by default)
  77982. * @returns a SceneOptimizerOptions object
  77983. */
  77984. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  77985. var result = new SceneOptimizerOptions(targetFrameRate);
  77986. var priority = 0;
  77987. result.addOptimization(new MergeMeshesOptimization(priority));
  77988. result.addOptimization(new ShadowsOptimization(priority));
  77989. result.addOptimization(new LensFlaresOptimization(priority));
  77990. // Next priority
  77991. priority++;
  77992. result.addOptimization(new PostProcessesOptimization(priority));
  77993. result.addOptimization(new ParticlesOptimization(priority));
  77994. // Next priority
  77995. priority++;
  77996. result.addOptimization(new TextureOptimization(priority, 512));
  77997. // Next priority
  77998. priority++;
  77999. result.addOptimization(new RenderTargetsOptimization(priority));
  78000. // Next priority
  78001. priority++;
  78002. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  78003. return result;
  78004. };
  78005. /**
  78006. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  78007. * @param targetFrameRate defines the target frame rate (60 by default)
  78008. * @returns a SceneOptimizerOptions object
  78009. */
  78010. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  78011. var result = new SceneOptimizerOptions(targetFrameRate);
  78012. var priority = 0;
  78013. result.addOptimization(new MergeMeshesOptimization(priority));
  78014. result.addOptimization(new ShadowsOptimization(priority));
  78015. result.addOptimization(new LensFlaresOptimization(priority));
  78016. // Next priority
  78017. priority++;
  78018. result.addOptimization(new PostProcessesOptimization(priority));
  78019. result.addOptimization(new ParticlesOptimization(priority));
  78020. // Next priority
  78021. priority++;
  78022. result.addOptimization(new TextureOptimization(priority, 256));
  78023. // Next priority
  78024. priority++;
  78025. result.addOptimization(new RenderTargetsOptimization(priority));
  78026. // Next priority
  78027. priority++;
  78028. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  78029. return result;
  78030. };
  78031. return SceneOptimizerOptions;
  78032. }());
  78033. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  78034. /**
  78035. * Class used to run optimizations in order to reach a target frame rate
  78036. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78037. */
  78038. var SceneOptimizer = /** @class */ (function () {
  78039. /**
  78040. * Creates a new SceneOptimizer
  78041. * @param scene defines the scene to work on
  78042. * @param options defines the options to use with the SceneOptimizer
  78043. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  78044. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  78045. */
  78046. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  78047. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  78048. if (improvementMode === void 0) { improvementMode = false; }
  78049. var _this = this;
  78050. this._isRunning = false;
  78051. this._currentPriorityLevel = 0;
  78052. this._targetFrameRate = 60;
  78053. this._trackerDuration = 2000;
  78054. this._currentFrameRate = 0;
  78055. this._improvementMode = false;
  78056. /**
  78057. * Defines an observable called when the optimizer reaches the target frame rate
  78058. */
  78059. this.onSuccessObservable = new BABYLON.Observable();
  78060. /**
  78061. * Defines an observable called when the optimizer enables an optimization
  78062. */
  78063. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  78064. /**
  78065. * Defines an observable called when the optimizer is not able to reach the target frame rate
  78066. */
  78067. this.onFailureObservable = new BABYLON.Observable();
  78068. if (!options) {
  78069. this._options = new SceneOptimizerOptions();
  78070. }
  78071. else {
  78072. this._options = options;
  78073. }
  78074. if (this._options.targetFrameRate) {
  78075. this._targetFrameRate = this._options.targetFrameRate;
  78076. }
  78077. if (this._options.trackerDuration) {
  78078. this._trackerDuration = this._options.trackerDuration;
  78079. }
  78080. if (autoGeneratePriorities) {
  78081. var priority = 0;
  78082. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  78083. var optim = _a[_i];
  78084. optim.priority = priority++;
  78085. }
  78086. }
  78087. this._improvementMode = improvementMode;
  78088. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78089. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  78090. _this._sceneDisposeObserver = null;
  78091. _this.dispose();
  78092. });
  78093. }
  78094. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  78095. /**
  78096. * Gets a boolean indicating if the optimizer is in improvement mode
  78097. */
  78098. get: function () {
  78099. return this._improvementMode;
  78100. },
  78101. enumerable: true,
  78102. configurable: true
  78103. });
  78104. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  78105. /**
  78106. * Gets the current priority level (0 at start)
  78107. */
  78108. get: function () {
  78109. return this._currentPriorityLevel;
  78110. },
  78111. enumerable: true,
  78112. configurable: true
  78113. });
  78114. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  78115. /**
  78116. * Gets the current frame rate checked by the SceneOptimizer
  78117. */
  78118. get: function () {
  78119. return this._currentFrameRate;
  78120. },
  78121. enumerable: true,
  78122. configurable: true
  78123. });
  78124. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  78125. /**
  78126. * Gets or sets the current target frame rate (60 by default)
  78127. */
  78128. get: function () {
  78129. return this._targetFrameRate;
  78130. },
  78131. /**
  78132. * Gets or sets the current target frame rate (60 by default)
  78133. */
  78134. set: function (value) {
  78135. this._targetFrameRate = value;
  78136. },
  78137. enumerable: true,
  78138. configurable: true
  78139. });
  78140. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  78141. /**
  78142. * Gets or sets the current interval between two checks (every 2000ms by default)
  78143. */
  78144. get: function () {
  78145. return this._trackerDuration;
  78146. },
  78147. /**
  78148. * Gets or sets the current interval between two checks (every 2000ms by default)
  78149. */
  78150. set: function (value) {
  78151. this._trackerDuration = value;
  78152. },
  78153. enumerable: true,
  78154. configurable: true
  78155. });
  78156. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  78157. /**
  78158. * Gets the list of active optimizations
  78159. */
  78160. get: function () {
  78161. return this._options.optimizations;
  78162. },
  78163. enumerable: true,
  78164. configurable: true
  78165. });
  78166. /**
  78167. * Stops the current optimizer
  78168. */
  78169. SceneOptimizer.prototype.stop = function () {
  78170. this._isRunning = false;
  78171. };
  78172. /**
  78173. * Reset the optimizer to initial step (current priority level = 0)
  78174. */
  78175. SceneOptimizer.prototype.reset = function () {
  78176. this._currentPriorityLevel = 0;
  78177. };
  78178. /**
  78179. * Start the optimizer. By default it will try to reach a specific framerate
  78180. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  78181. */
  78182. SceneOptimizer.prototype.start = function () {
  78183. var _this = this;
  78184. if (this._isRunning) {
  78185. return;
  78186. }
  78187. this._isRunning = true;
  78188. // Let's wait for the scene to be ready before running our check
  78189. this._scene.executeWhenReady(function () {
  78190. setTimeout(function () {
  78191. _this._checkCurrentState();
  78192. }, _this._trackerDuration);
  78193. });
  78194. };
  78195. SceneOptimizer.prototype._checkCurrentState = function () {
  78196. var _this = this;
  78197. if (!this._isRunning) {
  78198. return;
  78199. }
  78200. var scene = this._scene;
  78201. var options = this._options;
  78202. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  78203. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  78204. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  78205. this._isRunning = false;
  78206. this.onSuccessObservable.notifyObservers(this);
  78207. return;
  78208. }
  78209. // Apply current level of optimizations
  78210. var allDone = true;
  78211. var noOptimizationApplied = true;
  78212. for (var index = 0; index < options.optimizations.length; index++) {
  78213. var optimization = options.optimizations[index];
  78214. if (optimization.priority === this._currentPriorityLevel) {
  78215. noOptimizationApplied = false;
  78216. allDone = allDone && optimization.apply(scene, this);
  78217. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  78218. }
  78219. }
  78220. // If no optimization was applied, this is a failure :(
  78221. if (noOptimizationApplied) {
  78222. this._isRunning = false;
  78223. this.onFailureObservable.notifyObservers(this);
  78224. return;
  78225. }
  78226. // If all optimizations were done, move to next level
  78227. if (allDone) {
  78228. this._currentPriorityLevel++;
  78229. }
  78230. // Let's the system running for a specific amount of time before checking FPS
  78231. scene.executeWhenReady(function () {
  78232. setTimeout(function () {
  78233. _this._checkCurrentState();
  78234. }, _this._trackerDuration);
  78235. });
  78236. };
  78237. /**
  78238. * Release all resources
  78239. */
  78240. SceneOptimizer.prototype.dispose = function () {
  78241. this.stop();
  78242. this.onSuccessObservable.clear();
  78243. this.onFailureObservable.clear();
  78244. this.onNewOptimizationAppliedObservable.clear();
  78245. if (this._sceneDisposeObserver) {
  78246. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  78247. }
  78248. };
  78249. /**
  78250. * Helper function to create a SceneOptimizer with one single line of code
  78251. * @param scene defines the scene to work on
  78252. * @param options defines the options to use with the SceneOptimizer
  78253. * @param onSuccess defines a callback to call on success
  78254. * @param onFailure defines a callback to call on failure
  78255. * @returns the new SceneOptimizer object
  78256. */
  78257. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  78258. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  78259. if (onSuccess) {
  78260. optimizer.onSuccessObservable.add(function () {
  78261. onSuccess();
  78262. });
  78263. }
  78264. if (onFailure) {
  78265. optimizer.onFailureObservable.add(function () {
  78266. onFailure();
  78267. });
  78268. }
  78269. optimizer.start();
  78270. return optimizer;
  78271. };
  78272. return SceneOptimizer;
  78273. }());
  78274. BABYLON.SceneOptimizer = SceneOptimizer;
  78275. })(BABYLON || (BABYLON = {}));
  78276. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  78277. var BABYLON;
  78278. (function (BABYLON) {
  78279. var OutlineRenderer = /** @class */ (function () {
  78280. function OutlineRenderer(scene) {
  78281. this.zOffset = 1;
  78282. this._scene = scene;
  78283. }
  78284. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  78285. var _this = this;
  78286. if (useOverlay === void 0) { useOverlay = false; }
  78287. var scene = this._scene;
  78288. var engine = this._scene.getEngine();
  78289. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  78290. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  78291. return;
  78292. }
  78293. var mesh = subMesh.getRenderingMesh();
  78294. var material = subMesh.getMaterial();
  78295. if (!material || !scene.activeCamera) {
  78296. return;
  78297. }
  78298. engine.enableEffect(this._effect);
  78299. // Logarithmic depth
  78300. if (material.useLogarithmicDepth) {
  78301. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  78302. }
  78303. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  78304. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  78305. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78306. // Bones
  78307. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78308. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78309. }
  78310. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  78311. // Alpha test
  78312. if (material && material.needAlphaTesting()) {
  78313. var alphaTexture = material.getAlphaTestTexture();
  78314. if (alphaTexture) {
  78315. this._effect.setTexture("diffuseSampler", alphaTexture);
  78316. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78317. }
  78318. }
  78319. engine.setZOffset(-this.zOffset);
  78320. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  78321. engine.setZOffset(0);
  78322. };
  78323. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  78324. var defines = [];
  78325. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78326. var mesh = subMesh.getMesh();
  78327. var material = subMesh.getMaterial();
  78328. if (material) {
  78329. // Alpha test
  78330. if (material.needAlphaTesting()) {
  78331. defines.push("#define ALPHATEST");
  78332. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78333. attribs.push(BABYLON.VertexBuffer.UVKind);
  78334. defines.push("#define UV1");
  78335. }
  78336. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78337. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78338. defines.push("#define UV2");
  78339. }
  78340. }
  78341. //Logarithmic depth
  78342. if (material.useLogarithmicDepth) {
  78343. defines.push("#define LOGARITHMICDEPTH");
  78344. }
  78345. }
  78346. // Bones
  78347. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78348. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78349. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78350. if (mesh.numBoneInfluencers > 4) {
  78351. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78352. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78353. }
  78354. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78355. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78356. }
  78357. else {
  78358. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78359. }
  78360. // Instances
  78361. if (useInstances) {
  78362. defines.push("#define INSTANCES");
  78363. attribs.push("world0");
  78364. attribs.push("world1");
  78365. attribs.push("world2");
  78366. attribs.push("world3");
  78367. }
  78368. // Get correct effect
  78369. var join = defines.join("\n");
  78370. if (this._cachedDefines !== join) {
  78371. this._cachedDefines = join;
  78372. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  78373. }
  78374. return this._effect.isReady();
  78375. };
  78376. return OutlineRenderer;
  78377. }());
  78378. BABYLON.OutlineRenderer = OutlineRenderer;
  78379. })(BABYLON || (BABYLON = {}));
  78380. //# sourceMappingURL=babylon.outlineRenderer.js.map
  78381. var BABYLON;
  78382. (function (BABYLON) {
  78383. var FaceAdjacencies = /** @class */ (function () {
  78384. function FaceAdjacencies() {
  78385. this.edges = new Array();
  78386. this.edgesConnectedCount = 0;
  78387. }
  78388. return FaceAdjacencies;
  78389. }());
  78390. var EdgesRenderer = /** @class */ (function () {
  78391. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  78392. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  78393. if (epsilon === void 0) { epsilon = 0.95; }
  78394. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  78395. this.edgesWidthScalerForOrthographic = 1000.0;
  78396. this.edgesWidthScalerForPerspective = 50.0;
  78397. this._linesPositions = new Array();
  78398. this._linesNormals = new Array();
  78399. this._linesIndices = new Array();
  78400. this._buffers = {};
  78401. this._checkVerticesInsteadOfIndices = false;
  78402. this._source = source;
  78403. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  78404. this._epsilon = epsilon;
  78405. this._prepareRessources();
  78406. this._generateEdgesLines();
  78407. }
  78408. EdgesRenderer.prototype._prepareRessources = function () {
  78409. if (this._lineShader) {
  78410. return;
  78411. }
  78412. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  78413. attributes: ["position", "normal"],
  78414. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  78415. });
  78416. this._lineShader.disableDepthWrite = true;
  78417. this._lineShader.backFaceCulling = false;
  78418. };
  78419. EdgesRenderer.prototype._rebuild = function () {
  78420. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78421. if (buffer) {
  78422. buffer._rebuild();
  78423. }
  78424. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78425. if (buffer) {
  78426. buffer._rebuild();
  78427. }
  78428. var scene = this._source.getScene();
  78429. var engine = scene.getEngine();
  78430. this._ib = engine.createIndexBuffer(this._linesIndices);
  78431. };
  78432. EdgesRenderer.prototype.dispose = function () {
  78433. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78434. if (buffer) {
  78435. buffer.dispose();
  78436. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  78437. }
  78438. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78439. if (buffer) {
  78440. buffer.dispose();
  78441. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  78442. }
  78443. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  78444. this._lineShader.dispose();
  78445. };
  78446. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  78447. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  78448. return 0;
  78449. }
  78450. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  78451. return 1;
  78452. }
  78453. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  78454. return 2;
  78455. }
  78456. return -1;
  78457. };
  78458. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  78459. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  78460. return 0;
  78461. }
  78462. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  78463. return 1;
  78464. }
  78465. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  78466. return 2;
  78467. }
  78468. return -1;
  78469. };
  78470. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  78471. var needToCreateLine;
  78472. if (edge === undefined) {
  78473. needToCreateLine = true;
  78474. }
  78475. else {
  78476. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  78477. needToCreateLine = dotProduct < this._epsilon;
  78478. }
  78479. if (needToCreateLine) {
  78480. var offset = this._linesPositions.length / 3;
  78481. var normal = p0.subtract(p1);
  78482. normal.normalize();
  78483. // Positions
  78484. this._linesPositions.push(p0.x);
  78485. this._linesPositions.push(p0.y);
  78486. this._linesPositions.push(p0.z);
  78487. this._linesPositions.push(p0.x);
  78488. this._linesPositions.push(p0.y);
  78489. this._linesPositions.push(p0.z);
  78490. this._linesPositions.push(p1.x);
  78491. this._linesPositions.push(p1.y);
  78492. this._linesPositions.push(p1.z);
  78493. this._linesPositions.push(p1.x);
  78494. this._linesPositions.push(p1.y);
  78495. this._linesPositions.push(p1.z);
  78496. // Normals
  78497. this._linesNormals.push(p1.x);
  78498. this._linesNormals.push(p1.y);
  78499. this._linesNormals.push(p1.z);
  78500. this._linesNormals.push(-1);
  78501. this._linesNormals.push(p1.x);
  78502. this._linesNormals.push(p1.y);
  78503. this._linesNormals.push(p1.z);
  78504. this._linesNormals.push(1);
  78505. this._linesNormals.push(p0.x);
  78506. this._linesNormals.push(p0.y);
  78507. this._linesNormals.push(p0.z);
  78508. this._linesNormals.push(-1);
  78509. this._linesNormals.push(p0.x);
  78510. this._linesNormals.push(p0.y);
  78511. this._linesNormals.push(p0.z);
  78512. this._linesNormals.push(1);
  78513. // Indices
  78514. this._linesIndices.push(offset);
  78515. this._linesIndices.push(offset + 1);
  78516. this._linesIndices.push(offset + 2);
  78517. this._linesIndices.push(offset);
  78518. this._linesIndices.push(offset + 2);
  78519. this._linesIndices.push(offset + 3);
  78520. }
  78521. };
  78522. EdgesRenderer.prototype._generateEdgesLines = function () {
  78523. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78524. var indices = this._source.getIndices();
  78525. if (!indices || !positions) {
  78526. return;
  78527. }
  78528. // First let's find adjacencies
  78529. var adjacencies = new Array();
  78530. var faceNormals = new Array();
  78531. var index;
  78532. var faceAdjacencies;
  78533. // Prepare faces
  78534. for (index = 0; index < indices.length; index += 3) {
  78535. faceAdjacencies = new FaceAdjacencies();
  78536. var p0Index = indices[index];
  78537. var p1Index = indices[index + 1];
  78538. var p2Index = indices[index + 2];
  78539. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  78540. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  78541. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  78542. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  78543. faceNormal.normalize();
  78544. faceNormals.push(faceNormal);
  78545. adjacencies.push(faceAdjacencies);
  78546. }
  78547. // Scan
  78548. for (index = 0; index < adjacencies.length; index++) {
  78549. faceAdjacencies = adjacencies[index];
  78550. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  78551. var otherFaceAdjacencies = adjacencies[otherIndex];
  78552. if (faceAdjacencies.edgesConnectedCount === 3) {
  78553. break;
  78554. }
  78555. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  78556. continue;
  78557. }
  78558. var otherP0 = indices[otherIndex * 3];
  78559. var otherP1 = indices[otherIndex * 3 + 1];
  78560. var otherP2 = indices[otherIndex * 3 + 2];
  78561. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  78562. var otherEdgeIndex = 0;
  78563. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  78564. continue;
  78565. }
  78566. switch (edgeIndex) {
  78567. case 0:
  78568. if (this._checkVerticesInsteadOfIndices) {
  78569. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78570. }
  78571. else {
  78572. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  78573. }
  78574. break;
  78575. case 1:
  78576. if (this._checkVerticesInsteadOfIndices) {
  78577. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78578. }
  78579. else {
  78580. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  78581. }
  78582. break;
  78583. case 2:
  78584. if (this._checkVerticesInsteadOfIndices) {
  78585. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78586. }
  78587. else {
  78588. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  78589. }
  78590. break;
  78591. }
  78592. if (otherEdgeIndex === -1) {
  78593. continue;
  78594. }
  78595. faceAdjacencies.edges[edgeIndex] = otherIndex;
  78596. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  78597. faceAdjacencies.edgesConnectedCount++;
  78598. otherFaceAdjacencies.edgesConnectedCount++;
  78599. if (faceAdjacencies.edgesConnectedCount === 3) {
  78600. break;
  78601. }
  78602. }
  78603. }
  78604. }
  78605. // Create lines
  78606. for (index = 0; index < adjacencies.length; index++) {
  78607. // 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
  78608. var current = adjacencies[index];
  78609. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  78610. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  78611. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  78612. }
  78613. // Merge into a single mesh
  78614. var engine = this._source.getScene().getEngine();
  78615. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  78616. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  78617. this._ib = engine.createIndexBuffer(this._linesIndices);
  78618. this._indicesCount = this._linesIndices.length;
  78619. };
  78620. EdgesRenderer.prototype.render = function () {
  78621. var scene = this._source.getScene();
  78622. if (!this._lineShader.isReady() || !scene.activeCamera) {
  78623. return;
  78624. }
  78625. var engine = scene.getEngine();
  78626. this._lineShader._preBind();
  78627. // VBOs
  78628. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  78629. scene.resetCachedMaterial();
  78630. this._lineShader.setColor4("color", this._source.edgesColor);
  78631. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  78632. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  78633. }
  78634. else {
  78635. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  78636. }
  78637. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  78638. this._lineShader.bind(this._source.getWorldMatrix());
  78639. // Draw order
  78640. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  78641. this._lineShader.unbind();
  78642. engine.setDepthWrite(true);
  78643. };
  78644. return EdgesRenderer;
  78645. }());
  78646. BABYLON.EdgesRenderer = EdgesRenderer;
  78647. })(BABYLON || (BABYLON = {}));
  78648. //# sourceMappingURL=babylon.edgesRenderer.js.map
  78649. var BABYLON;
  78650. (function (BABYLON) {
  78651. /**
  78652. * Special Glow Blur post process only blurring the alpha channel
  78653. * It enforces keeping the most luminous color in the color channel.
  78654. */
  78655. var GlowBlurPostProcess = /** @class */ (function (_super) {
  78656. __extends(GlowBlurPostProcess, _super);
  78657. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  78658. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78659. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  78660. _this.direction = direction;
  78661. _this.kernel = kernel;
  78662. _this.onApplyObservable.add(function (effect) {
  78663. effect.setFloat2("screenSize", _this.width, _this.height);
  78664. effect.setVector2("direction", _this.direction);
  78665. effect.setFloat("blurWidth", _this.kernel);
  78666. });
  78667. return _this;
  78668. }
  78669. return GlowBlurPostProcess;
  78670. }(BABYLON.PostProcess));
  78671. /**
  78672. * The highlight layer Helps adding a glow effect around a mesh.
  78673. *
  78674. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  78675. * glowy meshes to your scene.
  78676. *
  78677. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  78678. */
  78679. var HighlightLayer = /** @class */ (function () {
  78680. /**
  78681. * Instantiates a new highlight Layer and references it to the scene..
  78682. * @param name The name of the layer
  78683. * @param scene The scene to use the layer in
  78684. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  78685. */
  78686. function HighlightLayer(name, scene, options) {
  78687. this.name = name;
  78688. this._vertexBuffers = {};
  78689. this._mainTextureDesiredSize = { width: 0, height: 0 };
  78690. this._meshes = {};
  78691. this._maxSize = 0;
  78692. this._shouldRender = false;
  78693. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  78694. this._excludedMeshes = {};
  78695. /**
  78696. * Specifies whether or not the inner glow is ACTIVE in the layer.
  78697. */
  78698. this.innerGlow = true;
  78699. /**
  78700. * Specifies whether or not the outer glow is ACTIVE in the layer.
  78701. */
  78702. this.outerGlow = true;
  78703. /**
  78704. * Specifies wether the highlight layer is enabled or not.
  78705. */
  78706. this.isEnabled = true;
  78707. /**
  78708. * An event triggered when the highlight layer has been disposed.
  78709. * @type {BABYLON.Observable}
  78710. */
  78711. this.onDisposeObservable = new BABYLON.Observable();
  78712. /**
  78713. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  78714. * @type {BABYLON.Observable}
  78715. */
  78716. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  78717. /**
  78718. * An event triggered when the highlight layer is being blurred.
  78719. * @type {BABYLON.Observable}
  78720. */
  78721. this.onBeforeBlurObservable = new BABYLON.Observable();
  78722. /**
  78723. * An event triggered when the highlight layer has been blurred.
  78724. * @type {BABYLON.Observable}
  78725. */
  78726. this.onAfterBlurObservable = new BABYLON.Observable();
  78727. /**
  78728. * An event triggered when the glowing blurred texture is being merged in the scene.
  78729. * @type {BABYLON.Observable}
  78730. */
  78731. this.onBeforeComposeObservable = new BABYLON.Observable();
  78732. /**
  78733. * An event triggered when the glowing blurred texture has been merged in the scene.
  78734. * @type {BABYLON.Observable}
  78735. */
  78736. this.onAfterComposeObservable = new BABYLON.Observable();
  78737. /**
  78738. * An event triggered when the highlight layer changes its size.
  78739. * @type {BABYLON.Observable}
  78740. */
  78741. this.onSizeChangedObservable = new BABYLON.Observable();
  78742. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78743. var engine = scene.getEngine();
  78744. this._engine = engine;
  78745. this._maxSize = this._engine.getCaps().maxTextureSize;
  78746. this._scene.highlightLayers.push(this);
  78747. // Warn on stencil.
  78748. if (!this._engine.isStencilEnable) {
  78749. 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 }");
  78750. }
  78751. // Adapt options
  78752. this._options = options || {
  78753. mainTextureRatio: 0.5,
  78754. blurTextureSizeRatio: 0.5,
  78755. blurHorizontalSize: 1.0,
  78756. blurVerticalSize: 1.0,
  78757. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  78758. camera: null
  78759. };
  78760. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  78761. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  78762. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  78763. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  78764. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  78765. // VBO
  78766. var vertices = [];
  78767. vertices.push(1, 1);
  78768. vertices.push(-1, 1);
  78769. vertices.push(-1, -1);
  78770. vertices.push(1, -1);
  78771. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78772. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78773. this._createIndexBuffer();
  78774. // Effect
  78775. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  78776. // Render target
  78777. this.setMainTextureSize();
  78778. // Create Textures and post processes
  78779. this.createTextureAndPostProcesses();
  78780. }
  78781. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  78782. /**
  78783. * Gets the horizontal size of the blur.
  78784. */
  78785. get: function () {
  78786. return this._horizontalBlurPostprocess.kernel;
  78787. },
  78788. /**
  78789. * Specifies the horizontal size of the blur.
  78790. */
  78791. set: function (value) {
  78792. this._horizontalBlurPostprocess.kernel = value;
  78793. },
  78794. enumerable: true,
  78795. configurable: true
  78796. });
  78797. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  78798. /**
  78799. * Gets the vertical size of the blur.
  78800. */
  78801. get: function () {
  78802. return this._verticalBlurPostprocess.kernel;
  78803. },
  78804. /**
  78805. * Specifies the vertical size of the blur.
  78806. */
  78807. set: function (value) {
  78808. this._verticalBlurPostprocess.kernel = value;
  78809. },
  78810. enumerable: true,
  78811. configurable: true
  78812. });
  78813. Object.defineProperty(HighlightLayer.prototype, "camera", {
  78814. /**
  78815. * Gets the camera attached to the layer.
  78816. */
  78817. get: function () {
  78818. return this._options.camera;
  78819. },
  78820. enumerable: true,
  78821. configurable: true
  78822. });
  78823. HighlightLayer.prototype._createIndexBuffer = function () {
  78824. var engine = this._scene.getEngine();
  78825. // Indices
  78826. var indices = [];
  78827. indices.push(0);
  78828. indices.push(1);
  78829. indices.push(2);
  78830. indices.push(0);
  78831. indices.push(2);
  78832. indices.push(3);
  78833. this._indexBuffer = engine.createIndexBuffer(indices);
  78834. };
  78835. HighlightLayer.prototype._rebuild = function () {
  78836. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78837. if (vb) {
  78838. vb._rebuild();
  78839. }
  78840. this._createIndexBuffer();
  78841. };
  78842. /**
  78843. * Creates the render target textures and post processes used in the highlight layer.
  78844. */
  78845. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  78846. var _this = this;
  78847. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  78848. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  78849. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  78850. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  78851. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  78852. width: this._mainTextureDesiredSize.width,
  78853. height: this._mainTextureDesiredSize.height
  78854. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78855. this._mainTexture.activeCamera = this._options.camera;
  78856. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78857. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78858. this._mainTexture.anisotropicFilteringLevel = 1;
  78859. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78860. this._mainTexture.renderParticles = false;
  78861. this._mainTexture.renderList = null;
  78862. this._mainTexture.ignoreCameraViewport = true;
  78863. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  78864. width: blurTextureWidth,
  78865. height: blurTextureHeight
  78866. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78867. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78868. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78869. this._blurTexture.anisotropicFilteringLevel = 16;
  78870. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78871. this._blurTexture.renderParticles = false;
  78872. this._blurTexture.ignoreCameraViewport = true;
  78873. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78874. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  78875. effect.setTexture("textureSampler", _this._mainTexture);
  78876. });
  78877. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  78878. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78879. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  78880. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78881. });
  78882. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78883. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  78884. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78885. });
  78886. }
  78887. else {
  78888. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78889. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  78890. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78891. });
  78892. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78893. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  78894. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78895. });
  78896. }
  78897. this._mainTexture.onAfterUnbindObservable.add(function () {
  78898. _this.onBeforeBlurObservable.notifyObservers(_this);
  78899. var internalTexture = _this._blurTexture.getInternalTexture();
  78900. if (internalTexture) {
  78901. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  78902. }
  78903. _this.onAfterBlurObservable.notifyObservers(_this);
  78904. });
  78905. // Custom render function
  78906. var renderSubMesh = function (subMesh) {
  78907. if (!_this._meshes) {
  78908. return;
  78909. }
  78910. var material = subMesh.getMaterial();
  78911. var mesh = subMesh.getRenderingMesh();
  78912. var scene = _this._scene;
  78913. var engine = scene.getEngine();
  78914. if (!material) {
  78915. return;
  78916. }
  78917. // Do not block in blend mode.
  78918. if (material.needAlphaBlendingForMesh(mesh)) {
  78919. return;
  78920. }
  78921. // Culling
  78922. engine.setState(material.backFaceCulling);
  78923. // Managing instances
  78924. var batch = mesh._getInstancesRenderList(subMesh._id);
  78925. if (batch.mustReturn) {
  78926. return;
  78927. }
  78928. // Excluded Mesh
  78929. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  78930. return;
  78931. }
  78932. ;
  78933. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  78934. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  78935. var emissiveTexture = null;
  78936. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  78937. emissiveTexture = material.emissiveTexture;
  78938. }
  78939. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  78940. engine.enableEffect(_this._glowMapGenerationEffect);
  78941. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  78942. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  78943. if (highlightLayerMesh) {
  78944. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  78945. }
  78946. else {
  78947. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  78948. }
  78949. // Alpha test
  78950. if (material && material.needAlphaTesting()) {
  78951. var alphaTexture = material.getAlphaTestTexture();
  78952. if (alphaTexture) {
  78953. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  78954. var textureMatrix = alphaTexture.getTextureMatrix();
  78955. if (textureMatrix) {
  78956. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  78957. }
  78958. }
  78959. }
  78960. // Glow emissive only
  78961. if (emissiveTexture) {
  78962. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  78963. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  78964. }
  78965. // Bones
  78966. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78967. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78968. }
  78969. // Draw
  78970. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  78971. }
  78972. else {
  78973. // Need to reset refresh rate of the shadowMap
  78974. _this._mainTexture.resetRefreshCounter();
  78975. }
  78976. };
  78977. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78978. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  78979. var index;
  78980. var engine = _this._scene.getEngine();
  78981. if (depthOnlySubMeshes.length) {
  78982. engine.setColorWrite(false);
  78983. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78984. renderSubMesh(depthOnlySubMeshes.data[index]);
  78985. }
  78986. engine.setColorWrite(true);
  78987. }
  78988. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78989. renderSubMesh(opaqueSubMeshes.data[index]);
  78990. }
  78991. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78992. renderSubMesh(alphaTestSubMeshes.data[index]);
  78993. }
  78994. for (index = 0; index < transparentSubMeshes.length; index++) {
  78995. renderSubMesh(transparentSubMeshes.data[index]);
  78996. }
  78997. };
  78998. this._mainTexture.onClearObservable.add(function (engine) {
  78999. engine.clear(HighlightLayer.neutralColor, true, true, true);
  79000. });
  79001. };
  79002. /**
  79003. * Checks for the readiness of the element composing the layer.
  79004. * @param subMesh the mesh to check for
  79005. * @param useInstances specify wether or not to use instances to render the mesh
  79006. * @param emissiveTexture the associated emissive texture used to generate the glow
  79007. * @return true if ready otherwise, false
  79008. */
  79009. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  79010. var material = subMesh.getMaterial();
  79011. var mesh = subMesh.getRenderingMesh();
  79012. if (!material || !mesh || !this._meshes) {
  79013. return false;
  79014. }
  79015. var emissiveTexture = null;
  79016. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  79017. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  79018. emissiveTexture = material.emissiveTexture;
  79019. }
  79020. return this._isReady(subMesh, useInstances, emissiveTexture);
  79021. };
  79022. /**
  79023. * Checks for the readiness of the element composing the layer.
  79024. * @param subMesh the mesh to check for
  79025. * @param useInstances specify wether or not to use instances to render the mesh
  79026. * @param emissiveTexture the associated emissive texture used to generate the glow
  79027. * @return true if ready otherwise, false
  79028. */
  79029. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  79030. var material = subMesh.getMaterial();
  79031. if (!material) {
  79032. return false;
  79033. }
  79034. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  79035. return false;
  79036. }
  79037. var defines = [];
  79038. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79039. var mesh = subMesh.getMesh();
  79040. var uv1 = false;
  79041. var uv2 = false;
  79042. // Alpha test
  79043. if (material && material.needAlphaTesting()) {
  79044. var alphaTexture = material.getAlphaTestTexture();
  79045. if (alphaTexture) {
  79046. defines.push("#define ALPHATEST");
  79047. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79048. alphaTexture.coordinatesIndex === 1) {
  79049. defines.push("#define DIFFUSEUV2");
  79050. uv2 = true;
  79051. }
  79052. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79053. defines.push("#define DIFFUSEUV1");
  79054. uv1 = true;
  79055. }
  79056. }
  79057. }
  79058. // Emissive
  79059. if (emissiveTexture) {
  79060. defines.push("#define EMISSIVE");
  79061. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79062. emissiveTexture.coordinatesIndex === 1) {
  79063. defines.push("#define EMISSIVEUV2");
  79064. uv2 = true;
  79065. }
  79066. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79067. defines.push("#define EMISSIVEUV1");
  79068. uv1 = true;
  79069. }
  79070. }
  79071. if (uv1) {
  79072. attribs.push(BABYLON.VertexBuffer.UVKind);
  79073. defines.push("#define UV1");
  79074. }
  79075. if (uv2) {
  79076. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79077. defines.push("#define UV2");
  79078. }
  79079. // Bones
  79080. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79081. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79082. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79083. if (mesh.numBoneInfluencers > 4) {
  79084. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79085. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79086. }
  79087. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79088. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79089. }
  79090. else {
  79091. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79092. }
  79093. // Instances
  79094. if (useInstances) {
  79095. defines.push("#define INSTANCES");
  79096. attribs.push("world0");
  79097. attribs.push("world1");
  79098. attribs.push("world2");
  79099. attribs.push("world3");
  79100. }
  79101. // Get correct effect
  79102. var join = defines.join("\n");
  79103. if (this._cachedDefines !== join) {
  79104. this._cachedDefines = join;
  79105. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  79106. }
  79107. return this._glowMapGenerationEffect.isReady();
  79108. };
  79109. /**
  79110. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  79111. */
  79112. HighlightLayer.prototype.render = function () {
  79113. var currentEffect = this._glowMapMergeEffect;
  79114. // Check
  79115. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  79116. return;
  79117. var engine = this._scene.getEngine();
  79118. this.onBeforeComposeObservable.notifyObservers(this);
  79119. // Render
  79120. engine.enableEffect(currentEffect);
  79121. engine.setState(false);
  79122. // Cache
  79123. var previousStencilBuffer = engine.getStencilBuffer();
  79124. var previousStencilFunction = engine.getStencilFunction();
  79125. var previousStencilMask = engine.getStencilMask();
  79126. var previousStencilOperationPass = engine.getStencilOperationPass();
  79127. var previousStencilOperationFail = engine.getStencilOperationFail();
  79128. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  79129. var previousAlphaMode = engine.getAlphaMode();
  79130. // Texture
  79131. currentEffect.setTexture("textureSampler", this._blurTexture);
  79132. // VBOs
  79133. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  79134. // Stencil operations
  79135. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  79136. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  79137. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  79138. // Draw order
  79139. engine.setAlphaMode(this._options.alphaBlendingMode);
  79140. engine.setStencilMask(0x00);
  79141. engine.setStencilBuffer(true);
  79142. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  79143. if (this.outerGlow) {
  79144. currentEffect.setFloat("offset", 0);
  79145. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  79146. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79147. }
  79148. if (this.innerGlow) {
  79149. currentEffect.setFloat("offset", 1);
  79150. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  79151. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79152. }
  79153. // Restore Cache
  79154. engine.setStencilFunction(previousStencilFunction);
  79155. engine.setStencilMask(previousStencilMask);
  79156. engine.setAlphaMode(previousAlphaMode);
  79157. engine.setStencilBuffer(previousStencilBuffer);
  79158. engine.setStencilOperationPass(previousStencilOperationPass);
  79159. engine.setStencilOperationFail(previousStencilOperationFail);
  79160. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  79161. engine._stencilState.reset();
  79162. this.onAfterComposeObservable.notifyObservers(this);
  79163. // Handle size changes.
  79164. var size = this._mainTexture.getSize();
  79165. this.setMainTextureSize();
  79166. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  79167. // Recreate RTT and post processes on size change.
  79168. this.onSizeChangedObservable.notifyObservers(this);
  79169. this.disposeTextureAndPostProcesses();
  79170. this.createTextureAndPostProcesses();
  79171. }
  79172. };
  79173. /**
  79174. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  79175. * @param mesh The mesh to exclude from the highlight layer
  79176. */
  79177. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  79178. if (!this._excludedMeshes) {
  79179. return;
  79180. }
  79181. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79182. if (!meshExcluded) {
  79183. this._excludedMeshes[mesh.uniqueId] = {
  79184. mesh: mesh,
  79185. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  79186. mesh.getEngine().setStencilBuffer(false);
  79187. }),
  79188. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  79189. mesh.getEngine().setStencilBuffer(true);
  79190. }),
  79191. };
  79192. }
  79193. };
  79194. /**
  79195. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  79196. * @param mesh The mesh to highlight
  79197. */
  79198. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  79199. if (!this._excludedMeshes) {
  79200. return;
  79201. }
  79202. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79203. if (meshExcluded) {
  79204. if (meshExcluded.beforeRender) {
  79205. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  79206. }
  79207. if (meshExcluded.afterRender) {
  79208. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  79209. }
  79210. }
  79211. this._excludedMeshes[mesh.uniqueId] = null;
  79212. };
  79213. /**
  79214. * Determine if a given mesh will be highlighted by the current HighlightLayer
  79215. * @param mesh mesh to test
  79216. * @returns true if the mesh will be highlighted by the current HighlightLayer
  79217. */
  79218. HighlightLayer.prototype.hasMesh = function (mesh) {
  79219. if (!this._meshes) {
  79220. return false;
  79221. }
  79222. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  79223. };
  79224. /**
  79225. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  79226. * @param mesh The mesh to highlight
  79227. * @param color The color of the highlight
  79228. * @param glowEmissiveOnly Extract the glow from the emissive texture
  79229. */
  79230. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  79231. var _this = this;
  79232. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  79233. if (!this._meshes) {
  79234. return;
  79235. }
  79236. var meshHighlight = this._meshes[mesh.uniqueId];
  79237. if (meshHighlight) {
  79238. meshHighlight.color = color;
  79239. }
  79240. else {
  79241. this._meshes[mesh.uniqueId] = {
  79242. mesh: mesh,
  79243. color: color,
  79244. // Lambda required for capture due to Observable this context
  79245. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  79246. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  79247. _this.defaultStencilReference(mesh);
  79248. }
  79249. else {
  79250. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  79251. }
  79252. }),
  79253. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  79254. glowEmissiveOnly: glowEmissiveOnly
  79255. };
  79256. }
  79257. this._shouldRender = true;
  79258. };
  79259. /**
  79260. * Remove a mesh from the highlight layer in order to make it stop glowing.
  79261. * @param mesh The mesh to highlight
  79262. */
  79263. HighlightLayer.prototype.removeMesh = function (mesh) {
  79264. if (!this._meshes) {
  79265. return;
  79266. }
  79267. var meshHighlight = this._meshes[mesh.uniqueId];
  79268. if (meshHighlight) {
  79269. if (meshHighlight.observerHighlight) {
  79270. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79271. }
  79272. if (meshHighlight.observerDefault) {
  79273. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79274. }
  79275. delete this._meshes[mesh.uniqueId];
  79276. }
  79277. this._shouldRender = false;
  79278. for (var meshHighlightToCheck in this._meshes) {
  79279. if (this._meshes[meshHighlightToCheck]) {
  79280. this._shouldRender = true;
  79281. break;
  79282. }
  79283. }
  79284. };
  79285. /**
  79286. * Returns true if the layer contains information to display, otherwise false.
  79287. */
  79288. HighlightLayer.prototype.shouldRender = function () {
  79289. return this.isEnabled && this._shouldRender;
  79290. };
  79291. /**
  79292. * Sets the main texture desired size which is the closest power of two
  79293. * of the engine canvas size.
  79294. */
  79295. HighlightLayer.prototype.setMainTextureSize = function () {
  79296. if (this._options.mainTextureFixedSize) {
  79297. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  79298. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  79299. }
  79300. else {
  79301. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  79302. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  79303. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  79304. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  79305. }
  79306. };
  79307. /**
  79308. * Force the stencil to the normal expected value for none glowing parts
  79309. */
  79310. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  79311. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  79312. };
  79313. /**
  79314. * Dispose only the render target textures and post process.
  79315. */
  79316. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  79317. this._blurTexture.dispose();
  79318. this._mainTexture.dispose();
  79319. this._downSamplePostprocess.dispose();
  79320. this._horizontalBlurPostprocess.dispose();
  79321. this._verticalBlurPostprocess.dispose();
  79322. };
  79323. /**
  79324. * Dispose the highlight layer and free resources.
  79325. */
  79326. HighlightLayer.prototype.dispose = function () {
  79327. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79328. if (vertexBuffer) {
  79329. vertexBuffer.dispose();
  79330. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79331. }
  79332. if (this._indexBuffer) {
  79333. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79334. this._indexBuffer = null;
  79335. }
  79336. // Clean textures and post processes
  79337. this.disposeTextureAndPostProcesses();
  79338. if (this._meshes) {
  79339. // Clean mesh references
  79340. for (var id in this._meshes) {
  79341. var meshHighlight = this._meshes[id];
  79342. if (meshHighlight && meshHighlight.mesh) {
  79343. if (meshHighlight.observerHighlight) {
  79344. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79345. }
  79346. if (meshHighlight.observerDefault) {
  79347. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79348. }
  79349. }
  79350. }
  79351. this._meshes = null;
  79352. }
  79353. if (this._excludedMeshes) {
  79354. for (var id in this._excludedMeshes) {
  79355. var meshHighlight = this._excludedMeshes[id];
  79356. if (meshHighlight) {
  79357. if (meshHighlight.beforeRender) {
  79358. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  79359. }
  79360. if (meshHighlight.afterRender) {
  79361. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  79362. }
  79363. }
  79364. }
  79365. this._excludedMeshes = null;
  79366. }
  79367. // Remove from scene
  79368. var index = this._scene.highlightLayers.indexOf(this, 0);
  79369. if (index > -1) {
  79370. this._scene.highlightLayers.splice(index, 1);
  79371. }
  79372. // Callback
  79373. this.onDisposeObservable.notifyObservers(this);
  79374. this.onDisposeObservable.clear();
  79375. this.onBeforeRenderMainTextureObservable.clear();
  79376. this.onBeforeBlurObservable.clear();
  79377. this.onBeforeComposeObservable.clear();
  79378. this.onAfterComposeObservable.clear();
  79379. this.onSizeChangedObservable.clear();
  79380. };
  79381. /**
  79382. * The neutral color used during the preparation of the glow effect.
  79383. * This is black by default as the blend operation is a blend operation.
  79384. */
  79385. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  79386. /**
  79387. * Stencil value used for glowing meshes.
  79388. */
  79389. HighlightLayer.glowingMeshStencilReference = 0x02;
  79390. /**
  79391. * Stencil value used for the other meshes in the scene.
  79392. */
  79393. HighlightLayer.normalMeshStencilReference = 0x01;
  79394. return HighlightLayer;
  79395. }());
  79396. BABYLON.HighlightLayer = HighlightLayer;
  79397. })(BABYLON || (BABYLON = {}));
  79398. //# sourceMappingURL=babylon.highlightlayer.js.map
  79399. var BABYLON;
  79400. (function (BABYLON) {
  79401. /**
  79402. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  79403. */
  79404. var AssetTaskState;
  79405. (function (AssetTaskState) {
  79406. /**
  79407. * Initialization
  79408. */
  79409. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  79410. /**
  79411. * Running
  79412. */
  79413. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  79414. /**
  79415. * Done
  79416. */
  79417. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  79418. /**
  79419. * Error
  79420. */
  79421. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  79422. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  79423. /**
  79424. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  79425. */
  79426. var AbstractAssetTask = /** @class */ (function () {
  79427. /**
  79428. * Creates a new {BABYLON.AssetsManager}
  79429. * @param name defines the name of the task
  79430. */
  79431. function AbstractAssetTask(
  79432. /**
  79433. * Task name
  79434. */ name) {
  79435. this.name = name;
  79436. this._isCompleted = false;
  79437. this._taskState = AssetTaskState.INIT;
  79438. }
  79439. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  79440. /**
  79441. * Get if the task is completed
  79442. */
  79443. get: function () {
  79444. return this._isCompleted;
  79445. },
  79446. enumerable: true,
  79447. configurable: true
  79448. });
  79449. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  79450. /**
  79451. * Gets the current state of the task
  79452. */
  79453. get: function () {
  79454. return this._taskState;
  79455. },
  79456. enumerable: true,
  79457. configurable: true
  79458. });
  79459. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  79460. /**
  79461. * Gets the current error object (if task is in error)
  79462. */
  79463. get: function () {
  79464. return this._errorObject;
  79465. },
  79466. enumerable: true,
  79467. configurable: true
  79468. });
  79469. /**
  79470. * Internal only
  79471. * @ignore
  79472. */
  79473. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  79474. if (this._errorObject) {
  79475. return;
  79476. }
  79477. this._errorObject = {
  79478. message: message,
  79479. exception: exception
  79480. };
  79481. };
  79482. /**
  79483. * Execute the current task
  79484. * @param scene defines the scene where you want your assets to be loaded
  79485. * @param onSuccess is a callback called when the task is successfully executed
  79486. * @param onError is a callback called if an error occurs
  79487. */
  79488. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79489. var _this = this;
  79490. this._taskState = AssetTaskState.RUNNING;
  79491. this.runTask(scene, function () {
  79492. _this.onDoneCallback(onSuccess, onError);
  79493. }, function (msg, exception) {
  79494. _this.onErrorCallback(onError, msg, exception);
  79495. });
  79496. };
  79497. /**
  79498. * Execute the current task
  79499. * @param scene defines the scene where you want your assets to be loaded
  79500. * @param onSuccess is a callback called when the task is successfully executed
  79501. * @param onError is a callback called if an error occurs
  79502. */
  79503. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79504. throw new Error("runTask is not implemented");
  79505. };
  79506. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  79507. this._taskState = AssetTaskState.ERROR;
  79508. this._errorObject = {
  79509. message: message,
  79510. exception: exception
  79511. };
  79512. if (this.onError) {
  79513. this.onError(this, message, exception);
  79514. }
  79515. onError();
  79516. };
  79517. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  79518. try {
  79519. this._taskState = AssetTaskState.DONE;
  79520. this._isCompleted = true;
  79521. if (this.onSuccess) {
  79522. this.onSuccess(this);
  79523. }
  79524. onSuccess();
  79525. }
  79526. catch (e) {
  79527. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  79528. }
  79529. };
  79530. return AbstractAssetTask;
  79531. }());
  79532. BABYLON.AbstractAssetTask = AbstractAssetTask;
  79533. /**
  79534. * Class used to share progress information about assets loading
  79535. */
  79536. var AssetsProgressEvent = /** @class */ (function () {
  79537. /**
  79538. * Creates a {BABYLON.AssetsProgressEvent}
  79539. * @param remainingCount defines the number of remaining tasks to process
  79540. * @param totalCount defines the total number of tasks
  79541. * @param task defines the task that was just processed
  79542. */
  79543. function AssetsProgressEvent(remainingCount, totalCount, task) {
  79544. this.remainingCount = remainingCount;
  79545. this.totalCount = totalCount;
  79546. this.task = task;
  79547. }
  79548. return AssetsProgressEvent;
  79549. }());
  79550. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  79551. /**
  79552. * Define a task used by {BABYLON.AssetsManager} to load meshes
  79553. */
  79554. var MeshAssetTask = /** @class */ (function (_super) {
  79555. __extends(MeshAssetTask, _super);
  79556. /**
  79557. * Creates a new {BABYLON.MeshAssetTask}
  79558. * @param name defines the name of the task
  79559. * @param meshesNames defines the list of mesh's names you want to load
  79560. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  79561. * @param sceneFilename defines the filename of the scene to load from
  79562. */
  79563. function MeshAssetTask(
  79564. /**
  79565. * Defines the name of the task
  79566. */
  79567. name,
  79568. /**
  79569. * Defines the list of mesh's names you want to load
  79570. */
  79571. meshesNames,
  79572. /**
  79573. * Defines the root url to use as a base to load your meshes and associated resources
  79574. */
  79575. rootUrl,
  79576. /**
  79577. * Defines the filename of the scene to load from
  79578. */
  79579. sceneFilename) {
  79580. var _this = _super.call(this, name) || this;
  79581. _this.name = name;
  79582. _this.meshesNames = meshesNames;
  79583. _this.rootUrl = rootUrl;
  79584. _this.sceneFilename = sceneFilename;
  79585. return _this;
  79586. }
  79587. /**
  79588. * Execute the current task
  79589. * @param scene defines the scene where you want your assets to be loaded
  79590. * @param onSuccess is a callback called when the task is successfully executed
  79591. * @param onError is a callback called if an error occurs
  79592. */
  79593. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79594. var _this = this;
  79595. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  79596. _this.loadedMeshes = meshes;
  79597. _this.loadedParticleSystems = particleSystems;
  79598. _this.loadedSkeletons = skeletons;
  79599. onSuccess();
  79600. }, null, function (scene, message, exception) {
  79601. onError(message, exception);
  79602. });
  79603. };
  79604. return MeshAssetTask;
  79605. }(AbstractAssetTask));
  79606. BABYLON.MeshAssetTask = MeshAssetTask;
  79607. /**
  79608. * Define a task used by {BABYLON.AssetsManager} to load text content
  79609. */
  79610. var TextFileAssetTask = /** @class */ (function (_super) {
  79611. __extends(TextFileAssetTask, _super);
  79612. /**
  79613. * Creates a new TextFileAssetTask object
  79614. * @param name defines the name of the task
  79615. * @param url defines the location of the file to load
  79616. */
  79617. function TextFileAssetTask(
  79618. /**
  79619. * Defines the name of the task
  79620. */
  79621. name,
  79622. /**
  79623. * Defines the location of the file to load
  79624. */
  79625. url) {
  79626. var _this = _super.call(this, name) || this;
  79627. _this.name = name;
  79628. _this.url = url;
  79629. return _this;
  79630. }
  79631. /**
  79632. * Execute the current task
  79633. * @param scene defines the scene where you want your assets to be loaded
  79634. * @param onSuccess is a callback called when the task is successfully executed
  79635. * @param onError is a callback called if an error occurs
  79636. */
  79637. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79638. var _this = this;
  79639. scene._loadFile(this.url, function (data) {
  79640. _this.text = data;
  79641. onSuccess();
  79642. }, undefined, false, true, function (request, exception) {
  79643. if (request) {
  79644. onError(request.status + " " + request.statusText, exception);
  79645. }
  79646. });
  79647. };
  79648. return TextFileAssetTask;
  79649. }(AbstractAssetTask));
  79650. BABYLON.TextFileAssetTask = TextFileAssetTask;
  79651. /**
  79652. * Define a task used by {BABYLON.AssetsManager} to load binary data
  79653. */
  79654. var BinaryFileAssetTask = /** @class */ (function (_super) {
  79655. __extends(BinaryFileAssetTask, _super);
  79656. /**
  79657. * Creates a new BinaryFileAssetTask object
  79658. * @param name defines the name of the new task
  79659. * @param url defines the location of the file to load
  79660. */
  79661. function BinaryFileAssetTask(
  79662. /**
  79663. * Defines the name of the task
  79664. */
  79665. name,
  79666. /**
  79667. * Defines the location of the file to load
  79668. */
  79669. url) {
  79670. var _this = _super.call(this, name) || this;
  79671. _this.name = name;
  79672. _this.url = url;
  79673. return _this;
  79674. }
  79675. /**
  79676. * Execute the current task
  79677. * @param scene defines the scene where you want your assets to be loaded
  79678. * @param onSuccess is a callback called when the task is successfully executed
  79679. * @param onError is a callback called if an error occurs
  79680. */
  79681. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79682. var _this = this;
  79683. scene._loadFile(this.url, function (data) {
  79684. _this.data = data;
  79685. onSuccess();
  79686. }, undefined, true, true, function (request, exception) {
  79687. if (request) {
  79688. onError(request.status + " " + request.statusText, exception);
  79689. }
  79690. });
  79691. };
  79692. return BinaryFileAssetTask;
  79693. }(AbstractAssetTask));
  79694. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  79695. /**
  79696. * Define a task used by {BABYLON.AssetsManager} to load images
  79697. */
  79698. var ImageAssetTask = /** @class */ (function (_super) {
  79699. __extends(ImageAssetTask, _super);
  79700. /**
  79701. * Creates a new ImageAssetTask
  79702. * @param name defines the name of the task
  79703. * @param url defines the location of the image to load
  79704. */
  79705. function ImageAssetTask(
  79706. /**
  79707. * Defines the name of the task
  79708. */
  79709. name,
  79710. /**
  79711. * Defines the location of the image to load
  79712. */
  79713. url) {
  79714. var _this = _super.call(this, name) || this;
  79715. _this.name = name;
  79716. _this.url = url;
  79717. return _this;
  79718. }
  79719. /**
  79720. * Execute the current task
  79721. * @param scene defines the scene where you want your assets to be loaded
  79722. * @param onSuccess is a callback called when the task is successfully executed
  79723. * @param onError is a callback called if an error occurs
  79724. */
  79725. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79726. var _this = this;
  79727. var img = new Image();
  79728. BABYLON.Tools.SetCorsBehavior(this.url, img);
  79729. img.onload = function () {
  79730. _this.image = img;
  79731. onSuccess();
  79732. };
  79733. img.onerror = function (err) {
  79734. onError("Error loading image", err);
  79735. };
  79736. img.src = this.url;
  79737. };
  79738. return ImageAssetTask;
  79739. }(AbstractAssetTask));
  79740. BABYLON.ImageAssetTask = ImageAssetTask;
  79741. /**
  79742. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  79743. */
  79744. var TextureAssetTask = /** @class */ (function (_super) {
  79745. __extends(TextureAssetTask, _super);
  79746. /**
  79747. * Creates a new TextureAssetTask object
  79748. * @param name defines the name of the task
  79749. * @param url defines the location of the file to load
  79750. * @param noMipmap defines if mipmap should not be generated (default is false)
  79751. * @param invertY defines if texture must be inverted on Y axis (default is false)
  79752. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  79753. */
  79754. function TextureAssetTask(
  79755. /**
  79756. * Defines the name of the task
  79757. */
  79758. name,
  79759. /**
  79760. * Defines the location of the file to load
  79761. */
  79762. url,
  79763. /**
  79764. * Defines if mipmap should not be generated (default is false)
  79765. */
  79766. noMipmap,
  79767. /**
  79768. * Defines if texture must be inverted on Y axis (default is false)
  79769. */
  79770. invertY,
  79771. /**
  79772. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  79773. */
  79774. samplingMode) {
  79775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  79776. var _this = _super.call(this, name) || this;
  79777. _this.name = name;
  79778. _this.url = url;
  79779. _this.noMipmap = noMipmap;
  79780. _this.invertY = invertY;
  79781. _this.samplingMode = samplingMode;
  79782. return _this;
  79783. }
  79784. /**
  79785. * Execute the current task
  79786. * @param scene defines the scene where you want your assets to be loaded
  79787. * @param onSuccess is a callback called when the task is successfully executed
  79788. * @param onError is a callback called if an error occurs
  79789. */
  79790. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79791. var onload = function () {
  79792. onSuccess();
  79793. };
  79794. var onerror = function (message, exception) {
  79795. onError(message, exception);
  79796. };
  79797. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  79798. };
  79799. return TextureAssetTask;
  79800. }(AbstractAssetTask));
  79801. BABYLON.TextureAssetTask = TextureAssetTask;
  79802. /**
  79803. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  79804. */
  79805. var CubeTextureAssetTask = /** @class */ (function (_super) {
  79806. __extends(CubeTextureAssetTask, _super);
  79807. /**
  79808. * Creates a new CubeTextureAssetTask
  79809. * @param name defines the name of the task
  79810. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  79811. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  79812. * @param noMipmap defines if mipmaps should not be generated (default is false)
  79813. * @param files defines the explicit list of files (undefined by default)
  79814. */
  79815. function CubeTextureAssetTask(
  79816. /**
  79817. * Defines the name of the task
  79818. */
  79819. name,
  79820. /**
  79821. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  79822. */
  79823. url,
  79824. /**
  79825. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  79826. */
  79827. extensions,
  79828. /**
  79829. * Defines if mipmaps should not be generated (default is false)
  79830. */
  79831. noMipmap,
  79832. /**
  79833. * Defines the explicit list of files (undefined by default)
  79834. */
  79835. files) {
  79836. var _this = _super.call(this, name) || this;
  79837. _this.name = name;
  79838. _this.url = url;
  79839. _this.extensions = extensions;
  79840. _this.noMipmap = noMipmap;
  79841. _this.files = files;
  79842. return _this;
  79843. }
  79844. /**
  79845. * Execute the current task
  79846. * @param scene defines the scene where you want your assets to be loaded
  79847. * @param onSuccess is a callback called when the task is successfully executed
  79848. * @param onError is a callback called if an error occurs
  79849. */
  79850. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79851. var onload = function () {
  79852. onSuccess();
  79853. };
  79854. var onerror = function (message, exception) {
  79855. onError(message, exception);
  79856. };
  79857. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  79858. };
  79859. return CubeTextureAssetTask;
  79860. }(AbstractAssetTask));
  79861. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  79862. /**
  79863. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  79864. */
  79865. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  79866. __extends(HDRCubeTextureAssetTask, _super);
  79867. /**
  79868. * Creates a new HDRCubeTextureAssetTask object
  79869. * @param name defines the name of the task
  79870. * @param url defines the location of the file to load
  79871. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  79872. * @param noMipmap defines if mipmaps should not be generated (default is false)
  79873. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  79874. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  79875. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  79876. */
  79877. function HDRCubeTextureAssetTask(
  79878. /**
  79879. * Defines the name of the task
  79880. */
  79881. name,
  79882. /**
  79883. * Defines the location of the file to load
  79884. */
  79885. url,
  79886. /**
  79887. * Defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  79888. */
  79889. size,
  79890. /**
  79891. * Defines if mipmaps should not be generated (default is false)
  79892. */
  79893. noMipmap,
  79894. /**
  79895. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  79896. */
  79897. generateHarmonics,
  79898. /**
  79899. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  79900. */
  79901. useInGammaSpace,
  79902. /**
  79903. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  79904. */
  79905. usePMREMGenerator) {
  79906. if (noMipmap === void 0) { noMipmap = false; }
  79907. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79908. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79909. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79910. var _this = _super.call(this, name) || this;
  79911. _this.name = name;
  79912. _this.url = url;
  79913. _this.size = size;
  79914. _this.noMipmap = noMipmap;
  79915. _this.generateHarmonics = generateHarmonics;
  79916. _this.useInGammaSpace = useInGammaSpace;
  79917. _this.usePMREMGenerator = usePMREMGenerator;
  79918. return _this;
  79919. }
  79920. /**
  79921. * Execute the current task
  79922. * @param scene defines the scene where you want your assets to be loaded
  79923. * @param onSuccess is a callback called when the task is successfully executed
  79924. * @param onError is a callback called if an error occurs
  79925. */
  79926. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79927. var onload = function () {
  79928. onSuccess();
  79929. };
  79930. var onerror = function (message, exception) {
  79931. onError(message, exception);
  79932. };
  79933. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  79934. };
  79935. return HDRCubeTextureAssetTask;
  79936. }(AbstractAssetTask));
  79937. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  79938. /**
  79939. * This class can be used to easily import assets into a scene
  79940. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  79941. */
  79942. var AssetsManager = /** @class */ (function () {
  79943. /**
  79944. * Creates a new AssetsManager
  79945. * @param scene defines the scene to work on
  79946. */
  79947. function AssetsManager(scene) {
  79948. this._isLoading = false;
  79949. this._tasks = new Array();
  79950. this._waitingTasksCount = 0;
  79951. this._totalTasksCount = 0;
  79952. /**
  79953. * Observable called when all tasks are processed
  79954. */
  79955. this.onTaskSuccessObservable = new BABYLON.Observable();
  79956. /**
  79957. * Observable called when a task had an error
  79958. */
  79959. this.onTaskErrorObservable = new BABYLON.Observable();
  79960. /**
  79961. * Observable called when a task is successful
  79962. */
  79963. this.onTasksDoneObservable = new BABYLON.Observable();
  79964. /**
  79965. * Observable called when a task is done (whatever the result is)
  79966. */
  79967. this.onProgressObservable = new BABYLON.Observable();
  79968. /**
  79969. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  79970. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  79971. */
  79972. this.useDefaultLoadingScreen = true;
  79973. this._scene = scene;
  79974. }
  79975. /**
  79976. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  79977. * @param taskName defines the name of the new task
  79978. * @param meshesNames defines the name of meshes to load
  79979. * @param rootUrl defines the root url to use to locate files
  79980. * @param sceneFilename defines the filename of the scene file
  79981. * @returns a new {BABYLON.MeshAssetTask} object
  79982. */
  79983. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  79984. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  79985. this._tasks.push(task);
  79986. return task;
  79987. };
  79988. /**
  79989. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  79990. * @param taskName defines the name of the new task
  79991. * @param url defines the url of the file to load
  79992. * @returns a new {BABYLON.TextFileAssetTask} object
  79993. */
  79994. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  79995. var task = new TextFileAssetTask(taskName, url);
  79996. this._tasks.push(task);
  79997. return task;
  79998. };
  79999. /**
  80000. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  80001. * @param taskName defines the name of the new task
  80002. * @param url defines the url of the file to load
  80003. * @returns a new {BABYLON.BinaryFileAssetTask} object
  80004. */
  80005. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  80006. var task = new BinaryFileAssetTask(taskName, url);
  80007. this._tasks.push(task);
  80008. return task;
  80009. };
  80010. /**
  80011. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  80012. * @param taskName defines the name of the new task
  80013. * @param url defines the url of the file to load
  80014. * @returns a new {BABYLON.ImageAssetTask} object
  80015. */
  80016. AssetsManager.prototype.addImageTask = function (taskName, url) {
  80017. var task = new ImageAssetTask(taskName, url);
  80018. this._tasks.push(task);
  80019. return task;
  80020. };
  80021. /**
  80022. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  80023. * @param taskName defines the name of the new task
  80024. * @param url defines the url of the file to load
  80025. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80026. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  80027. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  80028. * @returns a new {BABYLON.TextureAssetTask} object
  80029. */
  80030. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  80031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  80032. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  80033. this._tasks.push(task);
  80034. return task;
  80035. };
  80036. /**
  80037. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  80038. * @param taskName defines the name of the new task
  80039. * @param url defines the url of the file to load
  80040. * @param extensions defines the extension to use to load the cube map (can be null)
  80041. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80042. * @param files defines the list of files to load (can be null)
  80043. * @returns a new {BABYLON.CubeTextureAssetTask} object
  80044. */
  80045. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  80046. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  80047. this._tasks.push(task);
  80048. return task;
  80049. };
  80050. /**
  80051. *
  80052. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  80053. * @param taskName defines the name of the new task
  80054. * @param url defines the url of the file to load
  80055. * @param size defines the size you want for the cubemap (can be null)
  80056. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80057. * @param generateHarmonics defines if you want to automatically generate (true by default)
  80058. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  80059. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  80060. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  80061. */
  80062. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  80063. if (noMipmap === void 0) { noMipmap = false; }
  80064. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80065. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80066. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80067. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  80068. this._tasks.push(task);
  80069. return task;
  80070. };
  80071. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  80072. var _this = this;
  80073. this._waitingTasksCount--;
  80074. try {
  80075. if (task.taskState === AssetTaskState.DONE) {
  80076. // Let's remove successfull tasks
  80077. BABYLON.Tools.SetImmediate(function () {
  80078. var index = _this._tasks.indexOf(task);
  80079. if (index > -1) {
  80080. _this._tasks.splice(index, 1);
  80081. }
  80082. });
  80083. }
  80084. if (this.onProgress) {
  80085. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  80086. }
  80087. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  80088. }
  80089. catch (e) {
  80090. BABYLON.Tools.Error("Error running progress callbacks.");
  80091. console.log(e);
  80092. }
  80093. if (this._waitingTasksCount === 0) {
  80094. try {
  80095. if (this.onFinish) {
  80096. this.onFinish(this._tasks);
  80097. }
  80098. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80099. }
  80100. catch (e) {
  80101. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  80102. console.log(e);
  80103. }
  80104. this._isLoading = false;
  80105. this._scene.getEngine().hideLoadingUI();
  80106. }
  80107. };
  80108. AssetsManager.prototype._runTask = function (task) {
  80109. var _this = this;
  80110. var done = function () {
  80111. try {
  80112. if (_this.onTaskSuccess) {
  80113. _this.onTaskSuccess(task);
  80114. }
  80115. _this.onTaskSuccessObservable.notifyObservers(task);
  80116. _this._decreaseWaitingTasksCount(task);
  80117. }
  80118. catch (e) {
  80119. error("Error executing task success callbacks", e);
  80120. }
  80121. };
  80122. var error = function (message, exception) {
  80123. task._setErrorObject(message, exception);
  80124. if (_this.onTaskError) {
  80125. _this.onTaskError(task);
  80126. }
  80127. _this.onTaskErrorObservable.notifyObservers(task);
  80128. _this._decreaseWaitingTasksCount(task);
  80129. };
  80130. task.run(this._scene, done, error);
  80131. };
  80132. /**
  80133. * Reset the {BABYLON.AssetsManager} and remove all tasks
  80134. * @return the current instance of the {BABYLON.AssetsManager}
  80135. */
  80136. AssetsManager.prototype.reset = function () {
  80137. this._isLoading = false;
  80138. this._tasks = new Array();
  80139. return this;
  80140. };
  80141. /**
  80142. * Start the loading process
  80143. * @return the current instance of the {BABYLON.AssetsManager}
  80144. */
  80145. AssetsManager.prototype.load = function () {
  80146. if (this._isLoading) {
  80147. return this;
  80148. }
  80149. this._isLoading = true;
  80150. this._waitingTasksCount = this._tasks.length;
  80151. this._totalTasksCount = this._tasks.length;
  80152. if (this._waitingTasksCount === 0) {
  80153. if (this.onFinish) {
  80154. this.onFinish(this._tasks);
  80155. }
  80156. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80157. return this;
  80158. }
  80159. if (this.useDefaultLoadingScreen) {
  80160. this._scene.getEngine().displayLoadingUI();
  80161. }
  80162. for (var index = 0; index < this._tasks.length; index++) {
  80163. var task = this._tasks[index];
  80164. this._runTask(task);
  80165. }
  80166. return this;
  80167. };
  80168. return AssetsManager;
  80169. }());
  80170. BABYLON.AssetsManager = AssetsManager;
  80171. })(BABYLON || (BABYLON = {}));
  80172. //# sourceMappingURL=babylon.assetsManager.js.map
  80173. var BABYLON;
  80174. (function (BABYLON) {
  80175. var serializedGeometries = [];
  80176. var serializeGeometry = function (geometry, serializationGeometries) {
  80177. if (serializedGeometries[geometry.id]) {
  80178. return;
  80179. }
  80180. if (geometry.doNotSerialize) {
  80181. return;
  80182. }
  80183. if (geometry instanceof BABYLON.BoxGeometry) {
  80184. serializationGeometries.boxes.push(geometry.serialize());
  80185. }
  80186. else if (geometry instanceof BABYLON.SphereGeometry) {
  80187. serializationGeometries.spheres.push(geometry.serialize());
  80188. }
  80189. else if (geometry instanceof BABYLON.CylinderGeometry) {
  80190. serializationGeometries.cylinders.push(geometry.serialize());
  80191. }
  80192. else if (geometry instanceof BABYLON.TorusGeometry) {
  80193. serializationGeometries.toruses.push(geometry.serialize());
  80194. }
  80195. else if (geometry instanceof BABYLON.GroundGeometry) {
  80196. serializationGeometries.grounds.push(geometry.serialize());
  80197. }
  80198. else if (geometry instanceof BABYLON.Plane) {
  80199. serializationGeometries.planes.push(geometry.serialize());
  80200. }
  80201. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  80202. serializationGeometries.torusKnots.push(geometry.serialize());
  80203. }
  80204. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  80205. throw new Error("Unknown primitive type");
  80206. }
  80207. else {
  80208. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  80209. }
  80210. serializedGeometries[geometry.id] = true;
  80211. };
  80212. var serializeMesh = function (mesh, serializationScene) {
  80213. var serializationObject = {};
  80214. // Geometry
  80215. var geometry = mesh._geometry;
  80216. if (geometry) {
  80217. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  80218. // 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
  80219. serializeGeometry(geometry, serializationScene.geometries);
  80220. }
  80221. }
  80222. // Custom
  80223. if (mesh.serialize) {
  80224. mesh.serialize(serializationObject);
  80225. }
  80226. return serializationObject;
  80227. };
  80228. var finalizeSingleMesh = function (mesh, serializationObject) {
  80229. //only works if the mesh is already loaded
  80230. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80231. //serialize material
  80232. if (mesh.material) {
  80233. if (mesh.material instanceof BABYLON.StandardMaterial) {
  80234. serializationObject.materials = serializationObject.materials || [];
  80235. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80236. serializationObject.materials.push(mesh.material.serialize());
  80237. }
  80238. }
  80239. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  80240. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  80241. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80242. serializationObject.multiMaterials.push(mesh.material.serialize());
  80243. }
  80244. }
  80245. }
  80246. //serialize geometry
  80247. var geometry = mesh._geometry;
  80248. if (geometry) {
  80249. if (!serializationObject.geometries) {
  80250. serializationObject.geometries = {};
  80251. serializationObject.geometries.boxes = [];
  80252. serializationObject.geometries.spheres = [];
  80253. serializationObject.geometries.cylinders = [];
  80254. serializationObject.geometries.toruses = [];
  80255. serializationObject.geometries.grounds = [];
  80256. serializationObject.geometries.planes = [];
  80257. serializationObject.geometries.torusKnots = [];
  80258. serializationObject.geometries.vertexData = [];
  80259. }
  80260. serializeGeometry(geometry, serializationObject.geometries);
  80261. }
  80262. // Skeletons
  80263. if (mesh.skeleton) {
  80264. serializationObject.skeletons = serializationObject.skeletons || [];
  80265. serializationObject.skeletons.push(mesh.skeleton.serialize());
  80266. }
  80267. //serialize the actual mesh
  80268. serializationObject.meshes = serializationObject.meshes || [];
  80269. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80270. }
  80271. };
  80272. var SceneSerializer = /** @class */ (function () {
  80273. function SceneSerializer() {
  80274. }
  80275. SceneSerializer.ClearCache = function () {
  80276. serializedGeometries = [];
  80277. };
  80278. SceneSerializer.Serialize = function (scene) {
  80279. var serializationObject = {};
  80280. SceneSerializer.ClearCache();
  80281. // Scene
  80282. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  80283. serializationObject.autoClear = scene.autoClear;
  80284. serializationObject.clearColor = scene.clearColor.asArray();
  80285. serializationObject.ambientColor = scene.ambientColor.asArray();
  80286. serializationObject.gravity = scene.gravity.asArray();
  80287. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  80288. serializationObject.workerCollisions = scene.workerCollisions;
  80289. // Fog
  80290. if (scene.fogMode && scene.fogMode !== 0) {
  80291. serializationObject.fogMode = scene.fogMode;
  80292. serializationObject.fogColor = scene.fogColor.asArray();
  80293. serializationObject.fogStart = scene.fogStart;
  80294. serializationObject.fogEnd = scene.fogEnd;
  80295. serializationObject.fogDensity = scene.fogDensity;
  80296. }
  80297. //Physics
  80298. if (scene.isPhysicsEnabled()) {
  80299. var physicEngine = scene.getPhysicsEngine();
  80300. if (physicEngine) {
  80301. serializationObject.physicsEnabled = true;
  80302. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  80303. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  80304. }
  80305. }
  80306. // Metadata
  80307. if (scene.metadata) {
  80308. serializationObject.metadata = scene.metadata;
  80309. }
  80310. // Morph targets
  80311. serializationObject.morphTargetManagers = [];
  80312. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  80313. var abstractMesh = _a[_i];
  80314. var manager = abstractMesh.morphTargetManager;
  80315. if (manager) {
  80316. serializationObject.morphTargetManagers.push(manager.serialize());
  80317. }
  80318. }
  80319. // Lights
  80320. serializationObject.lights = [];
  80321. var index;
  80322. var light;
  80323. for (index = 0; index < scene.lights.length; index++) {
  80324. light = scene.lights[index];
  80325. if (!light.doNotSerialize) {
  80326. serializationObject.lights.push(light.serialize());
  80327. }
  80328. }
  80329. // Cameras
  80330. serializationObject.cameras = [];
  80331. for (index = 0; index < scene.cameras.length; index++) {
  80332. var camera = scene.cameras[index];
  80333. if (!camera.doNotSerialize) {
  80334. serializationObject.cameras.push(camera.serialize());
  80335. }
  80336. }
  80337. if (scene.activeCamera) {
  80338. serializationObject.activeCameraID = scene.activeCamera.id;
  80339. }
  80340. // Animations
  80341. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  80342. // Materials
  80343. serializationObject.materials = [];
  80344. serializationObject.multiMaterials = [];
  80345. var material;
  80346. for (index = 0; index < scene.materials.length; index++) {
  80347. material = scene.materials[index];
  80348. if (!material.doNotSerialize) {
  80349. serializationObject.materials.push(material.serialize());
  80350. }
  80351. }
  80352. // MultiMaterials
  80353. serializationObject.multiMaterials = [];
  80354. for (index = 0; index < scene.multiMaterials.length; index++) {
  80355. var multiMaterial = scene.multiMaterials[index];
  80356. serializationObject.multiMaterials.push(multiMaterial.serialize());
  80357. }
  80358. // Environment texture
  80359. if (scene.environmentTexture) {
  80360. serializationObject.environmentTexture = scene.environmentTexture.name;
  80361. }
  80362. // Skeletons
  80363. serializationObject.skeletons = [];
  80364. for (index = 0; index < scene.skeletons.length; index++) {
  80365. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  80366. }
  80367. // Transform nodes
  80368. serializationObject.transformNodes = [];
  80369. for (index = 0; index < scene.transformNodes.length; index++) {
  80370. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  80371. }
  80372. // Geometries
  80373. serializationObject.geometries = {};
  80374. serializationObject.geometries.boxes = [];
  80375. serializationObject.geometries.spheres = [];
  80376. serializationObject.geometries.cylinders = [];
  80377. serializationObject.geometries.toruses = [];
  80378. serializationObject.geometries.grounds = [];
  80379. serializationObject.geometries.planes = [];
  80380. serializationObject.geometries.torusKnots = [];
  80381. serializationObject.geometries.vertexData = [];
  80382. serializedGeometries = [];
  80383. var geometries = scene.getGeometries();
  80384. for (index = 0; index < geometries.length; index++) {
  80385. var geometry = geometries[index];
  80386. if (geometry.isReady()) {
  80387. serializeGeometry(geometry, serializationObject.geometries);
  80388. }
  80389. }
  80390. // Meshes
  80391. serializationObject.meshes = [];
  80392. for (index = 0; index < scene.meshes.length; index++) {
  80393. var abstractMesh = scene.meshes[index];
  80394. if (abstractMesh instanceof BABYLON.Mesh) {
  80395. var mesh = abstractMesh;
  80396. if (!mesh.doNotSerialize) {
  80397. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80398. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80399. }
  80400. }
  80401. }
  80402. }
  80403. // Particles Systems
  80404. serializationObject.particleSystems = [];
  80405. for (index = 0; index < scene.particleSystems.length; index++) {
  80406. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  80407. }
  80408. // Lens flares
  80409. serializationObject.lensFlareSystems = [];
  80410. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  80411. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  80412. }
  80413. // Shadows
  80414. serializationObject.shadowGenerators = [];
  80415. for (index = 0; index < scene.lights.length; index++) {
  80416. light = scene.lights[index];
  80417. var shadowGenerator = light.getShadowGenerator();
  80418. if (shadowGenerator) {
  80419. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  80420. }
  80421. }
  80422. // Action Manager
  80423. if (scene.actionManager) {
  80424. serializationObject.actions = scene.actionManager.serialize("scene");
  80425. }
  80426. // Audio
  80427. serializationObject.sounds = [];
  80428. for (index = 0; index < scene.soundTracks.length; index++) {
  80429. var soundtrack = scene.soundTracks[index];
  80430. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  80431. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  80432. }
  80433. }
  80434. return serializationObject;
  80435. };
  80436. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  80437. if (withParents === void 0) { withParents = false; }
  80438. if (withChildren === void 0) { withChildren = false; }
  80439. var serializationObject = {};
  80440. SceneSerializer.ClearCache();
  80441. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  80442. if (withParents || withChildren) {
  80443. //deliberate for loop! not for each, appended should be processed as well.
  80444. for (var i = 0; i < toSerialize.length; ++i) {
  80445. if (withChildren) {
  80446. toSerialize[i].getDescendants().forEach(function (node) {
  80447. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  80448. toSerialize.push(node);
  80449. }
  80450. });
  80451. }
  80452. //make sure the array doesn't contain the object already
  80453. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  80454. toSerialize.push(toSerialize[i].parent);
  80455. }
  80456. }
  80457. }
  80458. toSerialize.forEach(function (mesh) {
  80459. finalizeSingleMesh(mesh, serializationObject);
  80460. });
  80461. return serializationObject;
  80462. };
  80463. return SceneSerializer;
  80464. }());
  80465. BABYLON.SceneSerializer = SceneSerializer;
  80466. })(BABYLON || (BABYLON = {}));
  80467. //# sourceMappingURL=babylon.sceneSerializer.js.map
  80468. var BABYLON;
  80469. (function (BABYLON) {
  80470. var ReflectionProbe = /** @class */ (function () {
  80471. function ReflectionProbe(name, size, scene, generateMipMaps) {
  80472. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80473. var _this = this;
  80474. this.name = name;
  80475. this._viewMatrix = BABYLON.Matrix.Identity();
  80476. this._target = BABYLON.Vector3.Zero();
  80477. this._add = BABYLON.Vector3.Zero();
  80478. this.invertYAxis = false;
  80479. this.position = BABYLON.Vector3.Zero();
  80480. this._scene = scene;
  80481. this._scene.reflectionProbes.push(this);
  80482. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  80483. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  80484. switch (faceIndex) {
  80485. case 0:
  80486. _this._add.copyFromFloats(1, 0, 0);
  80487. break;
  80488. case 1:
  80489. _this._add.copyFromFloats(-1, 0, 0);
  80490. break;
  80491. case 2:
  80492. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  80493. break;
  80494. case 3:
  80495. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  80496. break;
  80497. case 4:
  80498. _this._add.copyFromFloats(0, 0, 1);
  80499. break;
  80500. case 5:
  80501. _this._add.copyFromFloats(0, 0, -1);
  80502. break;
  80503. }
  80504. if (_this._attachedMesh) {
  80505. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  80506. }
  80507. _this.position.addToRef(_this._add, _this._target);
  80508. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  80509. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  80510. scene._forcedViewPosition = _this.position;
  80511. });
  80512. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  80513. scene._forcedViewPosition = null;
  80514. scene.updateTransformMatrix(true);
  80515. });
  80516. if (scene.activeCamera) {
  80517. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80518. }
  80519. }
  80520. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  80521. get: function () {
  80522. return this._renderTargetTexture.samples;
  80523. },
  80524. set: function (value) {
  80525. this._renderTargetTexture.samples = value;
  80526. },
  80527. enumerable: true,
  80528. configurable: true
  80529. });
  80530. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  80531. get: function () {
  80532. return this._renderTargetTexture.refreshRate;
  80533. },
  80534. set: function (value) {
  80535. this._renderTargetTexture.refreshRate = value;
  80536. },
  80537. enumerable: true,
  80538. configurable: true
  80539. });
  80540. ReflectionProbe.prototype.getScene = function () {
  80541. return this._scene;
  80542. };
  80543. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  80544. get: function () {
  80545. return this._renderTargetTexture;
  80546. },
  80547. enumerable: true,
  80548. configurable: true
  80549. });
  80550. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  80551. get: function () {
  80552. return this._renderTargetTexture.renderList;
  80553. },
  80554. enumerable: true,
  80555. configurable: true
  80556. });
  80557. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  80558. this._attachedMesh = mesh;
  80559. };
  80560. /**
  80561. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  80562. *
  80563. * @param renderingGroupId The rendering group id corresponding to its index
  80564. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  80565. */
  80566. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  80567. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  80568. };
  80569. ReflectionProbe.prototype.dispose = function () {
  80570. var index = this._scene.reflectionProbes.indexOf(this);
  80571. if (index !== -1) {
  80572. // Remove from the scene if found
  80573. this._scene.reflectionProbes.splice(index, 1);
  80574. }
  80575. if (this._renderTargetTexture) {
  80576. this._renderTargetTexture.dispose();
  80577. this._renderTargetTexture = null;
  80578. }
  80579. };
  80580. return ReflectionProbe;
  80581. }());
  80582. BABYLON.ReflectionProbe = ReflectionProbe;
  80583. })(BABYLON || (BABYLON = {}));
  80584. //# sourceMappingURL=babylon.reflectionProbe.js.map
  80585. var BABYLON;
  80586. (function (BABYLON) {
  80587. var Layer = /** @class */ (function () {
  80588. function Layer(name, imgUrl, scene, isBackground, color) {
  80589. this.name = name;
  80590. this.scale = new BABYLON.Vector2(1, 1);
  80591. this.offset = new BABYLON.Vector2(0, 0);
  80592. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  80593. this.layerMask = 0x0FFFFFFF;
  80594. this._vertexBuffers = {};
  80595. // Events
  80596. /**
  80597. * An event triggered when the layer is disposed.
  80598. * @type {BABYLON.Observable}
  80599. */
  80600. this.onDisposeObservable = new BABYLON.Observable();
  80601. /**
  80602. * An event triggered before rendering the scene
  80603. * @type {BABYLON.Observable}
  80604. */
  80605. this.onBeforeRenderObservable = new BABYLON.Observable();
  80606. /**
  80607. * An event triggered after rendering the scene
  80608. * @type {BABYLON.Observable}
  80609. */
  80610. this.onAfterRenderObservable = new BABYLON.Observable();
  80611. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  80612. this.isBackground = isBackground === undefined ? true : isBackground;
  80613. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  80614. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  80615. this._scene.layers.push(this);
  80616. var engine = this._scene.getEngine();
  80617. // VBO
  80618. var vertices = [];
  80619. vertices.push(1, 1);
  80620. vertices.push(-1, 1);
  80621. vertices.push(-1, -1);
  80622. vertices.push(1, -1);
  80623. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80624. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80625. this._createIndexBuffer();
  80626. // Effects
  80627. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  80628. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  80629. }
  80630. Object.defineProperty(Layer.prototype, "onDispose", {
  80631. set: function (callback) {
  80632. if (this._onDisposeObserver) {
  80633. this.onDisposeObservable.remove(this._onDisposeObserver);
  80634. }
  80635. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  80636. },
  80637. enumerable: true,
  80638. configurable: true
  80639. });
  80640. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  80641. set: function (callback) {
  80642. if (this._onBeforeRenderObserver) {
  80643. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  80644. }
  80645. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  80646. },
  80647. enumerable: true,
  80648. configurable: true
  80649. });
  80650. Object.defineProperty(Layer.prototype, "onAfterRender", {
  80651. set: function (callback) {
  80652. if (this._onAfterRenderObserver) {
  80653. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80654. }
  80655. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  80656. },
  80657. enumerable: true,
  80658. configurable: true
  80659. });
  80660. Layer.prototype._createIndexBuffer = function () {
  80661. var engine = this._scene.getEngine();
  80662. // Indices
  80663. var indices = [];
  80664. indices.push(0);
  80665. indices.push(1);
  80666. indices.push(2);
  80667. indices.push(0);
  80668. indices.push(2);
  80669. indices.push(3);
  80670. this._indexBuffer = engine.createIndexBuffer(indices);
  80671. };
  80672. Layer.prototype._rebuild = function () {
  80673. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80674. if (vb) {
  80675. vb._rebuild();
  80676. }
  80677. this._createIndexBuffer();
  80678. };
  80679. Layer.prototype.render = function () {
  80680. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  80681. // Check
  80682. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  80683. return;
  80684. var engine = this._scene.getEngine();
  80685. this.onBeforeRenderObservable.notifyObservers(this);
  80686. // Render
  80687. engine.enableEffect(currentEffect);
  80688. engine.setState(false);
  80689. // Texture
  80690. currentEffect.setTexture("textureSampler", this.texture);
  80691. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  80692. // Color
  80693. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  80694. // Scale / offset
  80695. currentEffect.setVector2("offset", this.offset);
  80696. currentEffect.setVector2("scale", this.scale);
  80697. // VBOs
  80698. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  80699. // Draw order
  80700. if (!this.alphaTest) {
  80701. engine.setAlphaMode(this.alphaBlendingMode);
  80702. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80703. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80704. }
  80705. else {
  80706. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80707. }
  80708. this.onAfterRenderObservable.notifyObservers(this);
  80709. };
  80710. Layer.prototype.dispose = function () {
  80711. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80712. if (vertexBuffer) {
  80713. vertexBuffer.dispose();
  80714. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80715. }
  80716. if (this._indexBuffer) {
  80717. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80718. this._indexBuffer = null;
  80719. }
  80720. if (this.texture) {
  80721. this.texture.dispose();
  80722. this.texture = null;
  80723. }
  80724. // Remove from scene
  80725. var index = this._scene.layers.indexOf(this);
  80726. this._scene.layers.splice(index, 1);
  80727. // Callback
  80728. this.onDisposeObservable.notifyObservers(this);
  80729. this.onDisposeObservable.clear();
  80730. this.onAfterRenderObservable.clear();
  80731. this.onBeforeRenderObservable.clear();
  80732. };
  80733. return Layer;
  80734. }());
  80735. BABYLON.Layer = Layer;
  80736. })(BABYLON || (BABYLON = {}));
  80737. //# sourceMappingURL=babylon.layer.js.map
  80738. var BABYLON;
  80739. (function (BABYLON) {
  80740. var TextureTools = /** @class */ (function () {
  80741. function TextureTools() {
  80742. }
  80743. /**
  80744. * Uses the GPU to create a copy texture rescaled at a given size
  80745. * @param texture Texture to copy from
  80746. * @param width Desired width
  80747. * @param height Desired height
  80748. * @return Generated texture
  80749. */
  80750. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  80751. if (useBilinearMode === void 0) { useBilinearMode = true; }
  80752. var scene = texture.getScene();
  80753. var engine = scene.getEngine();
  80754. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  80755. rtt.wrapU = texture.wrapU;
  80756. rtt.wrapV = texture.wrapV;
  80757. rtt.uOffset = texture.uOffset;
  80758. rtt.vOffset = texture.vOffset;
  80759. rtt.uScale = texture.uScale;
  80760. rtt.vScale = texture.vScale;
  80761. rtt.uAng = texture.uAng;
  80762. rtt.vAng = texture.vAng;
  80763. rtt.wAng = texture.wAng;
  80764. rtt.coordinatesIndex = texture.coordinatesIndex;
  80765. rtt.level = texture.level;
  80766. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  80767. rtt._texture.isReady = false;
  80768. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80769. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80770. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80771. passPostProcess.getEffect().executeWhenCompiled(function () {
  80772. passPostProcess.onApply = function (effect) {
  80773. effect.setTexture("textureSampler", texture);
  80774. };
  80775. var internalTexture = rtt.getInternalTexture();
  80776. if (internalTexture) {
  80777. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  80778. engine.unBindFramebuffer(internalTexture);
  80779. rtt.disposeFramebufferObjects();
  80780. passPostProcess.dispose();
  80781. internalTexture.isReady = true;
  80782. }
  80783. });
  80784. return rtt;
  80785. };
  80786. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  80787. if (!scene._environmentBRDFTexture) {
  80788. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80789. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80790. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80791. scene._environmentBRDFTexture = texture;
  80792. }
  80793. return scene._environmentBRDFTexture;
  80794. };
  80795. 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=";
  80796. return TextureTools;
  80797. }());
  80798. BABYLON.TextureTools = TextureTools;
  80799. })(BABYLON || (BABYLON = {}));
  80800. //# sourceMappingURL=babylon.textureTools.js.map
  80801. var BABYLON;
  80802. (function (BABYLON) {
  80803. var FramingBehavior = /** @class */ (function () {
  80804. function FramingBehavior() {
  80805. this._mode = FramingBehavior.FitFrustumSidesMode;
  80806. this._radiusScale = 1.0;
  80807. this._positionScale = 0.5;
  80808. this._defaultElevation = 0.3;
  80809. this._elevationReturnTime = 1500;
  80810. this._elevationReturnWaitTime = 1000;
  80811. this._zoomStopsAnimation = false;
  80812. this._framingTime = 1500;
  80813. this._isPointerDown = false;
  80814. this._lastInteractionTime = -Infinity;
  80815. // Framing control
  80816. this._animatables = new Array();
  80817. this._betaIsAnimating = false;
  80818. }
  80819. Object.defineProperty(FramingBehavior.prototype, "name", {
  80820. get: function () {
  80821. return "Framing";
  80822. },
  80823. enumerable: true,
  80824. configurable: true
  80825. });
  80826. Object.defineProperty(FramingBehavior.prototype, "mode", {
  80827. /**
  80828. * Gets current mode used by the behavior.
  80829. */
  80830. get: function () {
  80831. return this._mode;
  80832. },
  80833. /**
  80834. * Sets the current mode used by the behavior
  80835. */
  80836. set: function (mode) {
  80837. this._mode = mode;
  80838. },
  80839. enumerable: true,
  80840. configurable: true
  80841. });
  80842. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  80843. /**
  80844. * Gets the scale applied to the radius
  80845. */
  80846. get: function () {
  80847. return this._radiusScale;
  80848. },
  80849. /**
  80850. * Sets the scale applied to the radius (1 by default)
  80851. */
  80852. set: function (radius) {
  80853. this._radiusScale = radius;
  80854. },
  80855. enumerable: true,
  80856. configurable: true
  80857. });
  80858. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  80859. /**
  80860. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  80861. */
  80862. get: function () {
  80863. return this._positionScale;
  80864. },
  80865. /**
  80866. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  80867. */
  80868. set: function (scale) {
  80869. this._positionScale = scale;
  80870. },
  80871. enumerable: true,
  80872. configurable: true
  80873. });
  80874. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  80875. /**
  80876. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  80877. * behaviour is triggered, in radians.
  80878. */
  80879. get: function () {
  80880. return this._defaultElevation;
  80881. },
  80882. /**
  80883. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  80884. * behaviour is triggered, in radians.
  80885. */
  80886. set: function (elevation) {
  80887. this._defaultElevation = elevation;
  80888. },
  80889. enumerable: true,
  80890. configurable: true
  80891. });
  80892. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  80893. /**
  80894. * Gets the time (in milliseconds) taken to return to the default beta position.
  80895. * Negative value indicates camera should not return to default.
  80896. */
  80897. get: function () {
  80898. return this._elevationReturnTime;
  80899. },
  80900. /**
  80901. * Sets the time (in milliseconds) taken to return to the default beta position.
  80902. * Negative value indicates camera should not return to default.
  80903. */
  80904. set: function (speed) {
  80905. this._elevationReturnTime = speed;
  80906. },
  80907. enumerable: true,
  80908. configurable: true
  80909. });
  80910. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  80911. /**
  80912. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  80913. */
  80914. get: function () {
  80915. return this._elevationReturnWaitTime;
  80916. },
  80917. /**
  80918. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  80919. */
  80920. set: function (time) {
  80921. this._elevationReturnWaitTime = time;
  80922. },
  80923. enumerable: true,
  80924. configurable: true
  80925. });
  80926. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  80927. /**
  80928. * Gets the flag that indicates if user zooming should stop animation.
  80929. */
  80930. get: function () {
  80931. return this._zoomStopsAnimation;
  80932. },
  80933. /**
  80934. * Sets the flag that indicates if user zooming should stop animation.
  80935. */
  80936. set: function (flag) {
  80937. this._zoomStopsAnimation = flag;
  80938. },
  80939. enumerable: true,
  80940. configurable: true
  80941. });
  80942. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  80943. /**
  80944. * Gets the transition time when framing the mesh, in milliseconds
  80945. */
  80946. get: function () {
  80947. return this._framingTime;
  80948. },
  80949. /**
  80950. * Sets the transition time when framing the mesh, in milliseconds
  80951. */
  80952. set: function (time) {
  80953. this._framingTime = time;
  80954. },
  80955. enumerable: true,
  80956. configurable: true
  80957. });
  80958. FramingBehavior.prototype.init = function () {
  80959. // Do notihng
  80960. };
  80961. FramingBehavior.prototype.attach = function (camera) {
  80962. var _this = this;
  80963. this._attachedCamera = camera;
  80964. var scene = this._attachedCamera.getScene();
  80965. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  80966. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  80967. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  80968. _this._isPointerDown = true;
  80969. return;
  80970. }
  80971. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  80972. _this._isPointerDown = false;
  80973. }
  80974. });
  80975. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  80976. if (mesh) {
  80977. _this.zoomOnMesh(mesh);
  80978. }
  80979. });
  80980. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  80981. // Stop the animation if there is user interaction and the animation should stop for this interaction
  80982. _this._applyUserInteraction();
  80983. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  80984. // back to the default position after a given timeout
  80985. _this._maintainCameraAboveGround();
  80986. });
  80987. };
  80988. FramingBehavior.prototype.detach = function () {
  80989. if (!this._attachedCamera) {
  80990. return;
  80991. }
  80992. var scene = this._attachedCamera.getScene();
  80993. if (this._onPrePointerObservableObserver) {
  80994. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  80995. }
  80996. if (this._onAfterCheckInputsObserver) {
  80997. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  80998. }
  80999. if (this._onMeshTargetChangedObserver) {
  81000. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81001. }
  81002. this._attachedCamera = null;
  81003. };
  81004. /**
  81005. * Targets the given mesh and updates zoom level accordingly.
  81006. * @param mesh The mesh to target.
  81007. * @param radius Optional. If a cached radius position already exists, overrides default.
  81008. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81009. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81010. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81011. */
  81012. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81013. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81014. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81015. mesh.computeWorldMatrix(true);
  81016. var boundingBox = mesh.getBoundingInfo().boundingBox;
  81017. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  81018. };
  81019. /**
  81020. * Targets the given mesh with its children and updates zoom level accordingly.
  81021. * @param mesh The mesh to target.
  81022. * @param radius Optional. If a cached radius position already exists, overrides default.
  81023. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81024. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81025. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81026. */
  81027. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81028. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81029. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81030. mesh.computeWorldMatrix(true);
  81031. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  81032. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  81033. };
  81034. /**
  81035. * Targets the given meshes with their children and updates zoom level accordingly.
  81036. * @param meshes The mesh to target.
  81037. * @param radius Optional. If a cached radius position already exists, overrides default.
  81038. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81039. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81040. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81041. */
  81042. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  81043. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81044. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81045. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  81046. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  81047. for (var i = 0; i < meshes.length; i++) {
  81048. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  81049. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  81050. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  81051. }
  81052. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  81053. };
  81054. /**
  81055. * Targets the given mesh and updates zoom level accordingly.
  81056. * @param mesh The mesh to target.
  81057. * @param radius Optional. If a cached radius position already exists, overrides default.
  81058. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81059. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81060. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81061. */
  81062. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  81063. var _this = this;
  81064. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81065. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81066. var zoomTarget;
  81067. if (!this._attachedCamera) {
  81068. return;
  81069. }
  81070. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  81071. var bottom = minimumWorld.y;
  81072. var top = maximumWorld.y;
  81073. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  81074. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  81075. if (focusOnOriginXZ) {
  81076. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  81077. }
  81078. else {
  81079. var centerWorld = minimumWorld.add(radiusWorld);
  81080. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  81081. }
  81082. if (!this._vectorTransition) {
  81083. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  81084. }
  81085. this._betaIsAnimating = true;
  81086. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  81087. if (animatable) {
  81088. this._animatables.push(animatable);
  81089. }
  81090. // sets the radius and lower radius bounds
  81091. // Small delta ensures camera is not always at lower zoom limit.
  81092. var radius = 0;
  81093. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  81094. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81095. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  81096. radius = position;
  81097. }
  81098. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81099. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81100. if (this._attachedCamera.lowerRadiusLimit === null) {
  81101. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  81102. }
  81103. }
  81104. // Set sensibilities
  81105. var extend = maximumWorld.subtract(minimumWorld).length();
  81106. this._attachedCamera.panningSensibility = 5000 / extend;
  81107. this._attachedCamera.wheelPrecision = 100 / radius;
  81108. // transition to new radius
  81109. if (!this._radiusTransition) {
  81110. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81111. }
  81112. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  81113. if (onAnimationEnd) {
  81114. onAnimationEnd();
  81115. }
  81116. if (_this._attachedCamera) {
  81117. _this._attachedCamera.storeState();
  81118. }
  81119. });
  81120. if (animatable) {
  81121. this._animatables.push(animatable);
  81122. }
  81123. };
  81124. /**
  81125. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  81126. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  81127. * frustum width.
  81128. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  81129. * to fully enclose the mesh in the viewing frustum.
  81130. */
  81131. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  81132. var size = maximumWorld.subtract(minimumWorld);
  81133. var boxVectorGlobalDiagonal = size.length();
  81134. var frustumSlope = this._getFrustumSlope();
  81135. // Formula for setting distance
  81136. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  81137. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  81138. // Horizon distance
  81139. var radius = radiusWithoutFraming * this._radiusScale;
  81140. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  81141. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  81142. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  81143. var camera = this._attachedCamera;
  81144. if (!camera) {
  81145. return 0;
  81146. }
  81147. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81148. // Don't exceed the requested limit
  81149. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  81150. }
  81151. // Don't exceed the upper radius limit
  81152. if (camera.upperRadiusLimit) {
  81153. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  81154. }
  81155. return distance;
  81156. };
  81157. /**
  81158. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  81159. * is automatically returned to its default position (expected to be above ground plane).
  81160. */
  81161. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  81162. var _this = this;
  81163. if (this._elevationReturnTime < 0) {
  81164. return;
  81165. }
  81166. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  81167. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  81168. var limitBeta = Math.PI * 0.5;
  81169. // Bring the camera back up if below the ground plane
  81170. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  81171. this._betaIsAnimating = true;
  81172. //Transition to new position
  81173. this.stopAllAnimations();
  81174. if (!this._betaTransition) {
  81175. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81176. }
  81177. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  81178. _this._clearAnimationLocks();
  81179. _this.stopAllAnimations();
  81180. });
  81181. if (animatabe) {
  81182. this._animatables.push(animatabe);
  81183. }
  81184. }
  81185. };
  81186. /**
  81187. * Returns the frustum slope based on the canvas ratio and camera FOV
  81188. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  81189. */
  81190. FramingBehavior.prototype._getFrustumSlope = function () {
  81191. // Calculate the viewport ratio
  81192. // Aspect Ratio is Height/Width.
  81193. var camera = this._attachedCamera;
  81194. if (!camera) {
  81195. return BABYLON.Vector2.Zero();
  81196. }
  81197. var engine = camera.getScene().getEngine();
  81198. var aspectRatio = engine.getAspectRatio(camera);
  81199. // Camera FOV is the vertical field of view (top-bottom) in radians.
  81200. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  81201. var frustumSlopeY = Math.tan(camera.fov / 2);
  81202. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  81203. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  81204. // along the forward vector.
  81205. var frustumSlopeX = frustumSlopeY * aspectRatio;
  81206. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  81207. };
  81208. /**
  81209. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  81210. */
  81211. FramingBehavior.prototype._clearAnimationLocks = function () {
  81212. this._betaIsAnimating = false;
  81213. };
  81214. /**
  81215. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81216. */
  81217. FramingBehavior.prototype._applyUserInteraction = function () {
  81218. if (this.isUserIsMoving) {
  81219. this._lastInteractionTime = BABYLON.Tools.Now;
  81220. this.stopAllAnimations();
  81221. this._clearAnimationLocks();
  81222. }
  81223. };
  81224. /**
  81225. * Stops and removes all animations that have been applied to the camera
  81226. */
  81227. FramingBehavior.prototype.stopAllAnimations = function () {
  81228. if (this._attachedCamera) {
  81229. this._attachedCamera.animations = [];
  81230. }
  81231. while (this._animatables.length) {
  81232. if (this._animatables[0]) {
  81233. this._animatables[0].onAnimationEnd = null;
  81234. this._animatables[0].stop();
  81235. }
  81236. this._animatables.shift();
  81237. }
  81238. };
  81239. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  81240. /**
  81241. * Gets a value indicating if the user is moving the camera
  81242. */
  81243. get: function () {
  81244. if (!this._attachedCamera) {
  81245. return false;
  81246. }
  81247. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81248. this._attachedCamera.inertialBetaOffset !== 0 ||
  81249. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81250. this._attachedCamera.inertialPanningX !== 0 ||
  81251. this._attachedCamera.inertialPanningY !== 0 ||
  81252. this._isPointerDown;
  81253. },
  81254. enumerable: true,
  81255. configurable: true
  81256. });
  81257. /**
  81258. * The easing function used by animations
  81259. */
  81260. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  81261. /**
  81262. * The easing mode used by animations
  81263. */
  81264. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  81265. // Statics
  81266. /**
  81267. * The camera can move all the way towards the mesh.
  81268. */
  81269. FramingBehavior.IgnoreBoundsSizeMode = 0;
  81270. /**
  81271. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  81272. */
  81273. FramingBehavior.FitFrustumSidesMode = 1;
  81274. return FramingBehavior;
  81275. }());
  81276. BABYLON.FramingBehavior = FramingBehavior;
  81277. })(BABYLON || (BABYLON = {}));
  81278. //# sourceMappingURL=babylon.framingBehavior.js.map
  81279. var BABYLON;
  81280. (function (BABYLON) {
  81281. /**
  81282. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  81283. */
  81284. var BouncingBehavior = /** @class */ (function () {
  81285. function BouncingBehavior() {
  81286. /**
  81287. * The duration of the animation, in milliseconds
  81288. */
  81289. this.transitionDuration = 450;
  81290. /**
  81291. * Length of the distance animated by the transition when lower radius is reached
  81292. */
  81293. this.lowerRadiusTransitionRange = 2;
  81294. /**
  81295. * Length of the distance animated by the transition when upper radius is reached
  81296. */
  81297. this.upperRadiusTransitionRange = -2;
  81298. this._autoTransitionRange = false;
  81299. // Animations
  81300. this._radiusIsAnimating = false;
  81301. this._radiusBounceTransition = null;
  81302. this._animatables = new Array();
  81303. }
  81304. Object.defineProperty(BouncingBehavior.prototype, "name", {
  81305. get: function () {
  81306. return "Bouncing";
  81307. },
  81308. enumerable: true,
  81309. configurable: true
  81310. });
  81311. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  81312. /**
  81313. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81314. */
  81315. get: function () {
  81316. return this._autoTransitionRange;
  81317. },
  81318. /**
  81319. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81320. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  81321. */
  81322. set: function (value) {
  81323. var _this = this;
  81324. if (this._autoTransitionRange === value) {
  81325. return;
  81326. }
  81327. this._autoTransitionRange = value;
  81328. var camera = this._attachedCamera;
  81329. if (!camera) {
  81330. return;
  81331. }
  81332. if (value) {
  81333. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81334. if (!mesh) {
  81335. return;
  81336. }
  81337. mesh.computeWorldMatrix(true);
  81338. var diagonal = mesh.getBoundingInfo().diagonalLength;
  81339. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  81340. _this.upperRadiusTransitionRange = diagonal * 0.05;
  81341. });
  81342. }
  81343. else if (this._onMeshTargetChangedObserver) {
  81344. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81345. }
  81346. },
  81347. enumerable: true,
  81348. configurable: true
  81349. });
  81350. BouncingBehavior.prototype.init = function () {
  81351. // Do notihng
  81352. };
  81353. BouncingBehavior.prototype.attach = function (camera) {
  81354. var _this = this;
  81355. this._attachedCamera = camera;
  81356. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81357. if (!_this._attachedCamera) {
  81358. return;
  81359. }
  81360. // Add the bounce animation to the lower radius limit
  81361. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  81362. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  81363. }
  81364. // Add the bounce animation to the upper radius limit
  81365. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  81366. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  81367. }
  81368. });
  81369. };
  81370. BouncingBehavior.prototype.detach = function () {
  81371. if (!this._attachedCamera) {
  81372. return;
  81373. }
  81374. if (this._onAfterCheckInputsObserver) {
  81375. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81376. }
  81377. if (this._onMeshTargetChangedObserver) {
  81378. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81379. }
  81380. this._attachedCamera = null;
  81381. };
  81382. /**
  81383. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  81384. * @param radiusLimit The limit to check against.
  81385. * @return Bool to indicate if at limit.
  81386. */
  81387. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  81388. if (!this._attachedCamera) {
  81389. return false;
  81390. }
  81391. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  81392. return true;
  81393. }
  81394. return false;
  81395. };
  81396. /**
  81397. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  81398. * @param radiusDelta The delta by which to animate to. Can be negative.
  81399. */
  81400. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  81401. var _this = this;
  81402. if (!this._attachedCamera) {
  81403. return;
  81404. }
  81405. if (!this._radiusBounceTransition) {
  81406. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  81407. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  81408. }
  81409. // Prevent zoom until bounce has completed
  81410. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  81411. this._attachedCamera.wheelPrecision = Infinity;
  81412. this._attachedCamera.inertialRadiusOffset = 0;
  81413. // Animate to the radius limit
  81414. this.stopAllAnimations();
  81415. this._radiusIsAnimating = true;
  81416. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  81417. if (animatable) {
  81418. this._animatables.push(animatable);
  81419. }
  81420. };
  81421. /**
  81422. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  81423. */
  81424. BouncingBehavior.prototype._clearAnimationLocks = function () {
  81425. this._radiusIsAnimating = false;
  81426. if (this._attachedCamera) {
  81427. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  81428. }
  81429. };
  81430. /**
  81431. * Stops and removes all animations that have been applied to the camera
  81432. */
  81433. BouncingBehavior.prototype.stopAllAnimations = function () {
  81434. if (this._attachedCamera) {
  81435. this._attachedCamera.animations = [];
  81436. }
  81437. while (this._animatables.length) {
  81438. this._animatables[0].onAnimationEnd = null;
  81439. this._animatables[0].stop();
  81440. this._animatables.shift();
  81441. }
  81442. };
  81443. /**
  81444. * The easing function used by animations
  81445. */
  81446. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  81447. /**
  81448. * The easing mode used by animations
  81449. */
  81450. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  81451. return BouncingBehavior;
  81452. }());
  81453. BABYLON.BouncingBehavior = BouncingBehavior;
  81454. })(BABYLON || (BABYLON = {}));
  81455. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  81456. var BABYLON;
  81457. (function (BABYLON) {
  81458. var AutoRotationBehavior = /** @class */ (function () {
  81459. function AutoRotationBehavior() {
  81460. this._zoomStopsAnimation = false;
  81461. this._idleRotationSpeed = 0.05;
  81462. this._idleRotationWaitTime = 2000;
  81463. this._idleRotationSpinupTime = 2000;
  81464. this._isPointerDown = false;
  81465. this._lastFrameTime = null;
  81466. this._lastInteractionTime = -Infinity;
  81467. this._cameraRotationSpeed = 0;
  81468. this._lastFrameRadius = 0;
  81469. }
  81470. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  81471. get: function () {
  81472. return "AutoRotation";
  81473. },
  81474. enumerable: true,
  81475. configurable: true
  81476. });
  81477. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  81478. /**
  81479. * Gets the flag that indicates if user zooming should stop animation.
  81480. */
  81481. get: function () {
  81482. return this._zoomStopsAnimation;
  81483. },
  81484. /**
  81485. * Sets the flag that indicates if user zooming should stop animation.
  81486. */
  81487. set: function (flag) {
  81488. this._zoomStopsAnimation = flag;
  81489. },
  81490. enumerable: true,
  81491. configurable: true
  81492. });
  81493. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  81494. /**
  81495. * Gets the default speed at which the camera rotates around the model.
  81496. */
  81497. get: function () {
  81498. return this._idleRotationSpeed;
  81499. },
  81500. /**
  81501. * Sets the default speed at which the camera rotates around the model.
  81502. */
  81503. set: function (speed) {
  81504. this._idleRotationSpeed = speed;
  81505. },
  81506. enumerable: true,
  81507. configurable: true
  81508. });
  81509. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  81510. /**
  81511. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  81512. */
  81513. get: function () {
  81514. return this._idleRotationWaitTime;
  81515. },
  81516. /**
  81517. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  81518. */
  81519. set: function (time) {
  81520. this._idleRotationWaitTime = time;
  81521. },
  81522. enumerable: true,
  81523. configurable: true
  81524. });
  81525. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  81526. /**
  81527. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81528. */
  81529. get: function () {
  81530. return this._idleRotationSpinupTime;
  81531. },
  81532. /**
  81533. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81534. */
  81535. set: function (time) {
  81536. this._idleRotationSpinupTime = time;
  81537. },
  81538. enumerable: true,
  81539. configurable: true
  81540. });
  81541. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  81542. /**
  81543. * Gets a value indicating if the camera is currently rotating because of this behavior
  81544. */
  81545. get: function () {
  81546. return Math.abs(this._cameraRotationSpeed) > 0;
  81547. },
  81548. enumerable: true,
  81549. configurable: true
  81550. });
  81551. AutoRotationBehavior.prototype.init = function () {
  81552. // Do notihng
  81553. };
  81554. AutoRotationBehavior.prototype.attach = function (camera) {
  81555. var _this = this;
  81556. this._attachedCamera = camera;
  81557. var scene = this._attachedCamera.getScene();
  81558. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81559. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81560. _this._isPointerDown = true;
  81561. return;
  81562. }
  81563. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81564. _this._isPointerDown = false;
  81565. }
  81566. });
  81567. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81568. var now = BABYLON.Tools.Now;
  81569. var dt = 0;
  81570. if (_this._lastFrameTime != null) {
  81571. dt = now - _this._lastFrameTime;
  81572. }
  81573. _this._lastFrameTime = now;
  81574. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81575. _this._applyUserInteraction();
  81576. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  81577. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  81578. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  81579. // Step camera rotation by rotation speed
  81580. if (_this._attachedCamera) {
  81581. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  81582. }
  81583. });
  81584. };
  81585. AutoRotationBehavior.prototype.detach = function () {
  81586. if (!this._attachedCamera) {
  81587. return;
  81588. }
  81589. var scene = this._attachedCamera.getScene();
  81590. if (this._onPrePointerObservableObserver) {
  81591. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  81592. }
  81593. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81594. this._attachedCamera = null;
  81595. };
  81596. /**
  81597. * Returns true if user is scrolling.
  81598. * @return true if user is scrolling.
  81599. */
  81600. AutoRotationBehavior.prototype._userIsZooming = function () {
  81601. if (!this._attachedCamera) {
  81602. return false;
  81603. }
  81604. return this._attachedCamera.inertialRadiusOffset !== 0;
  81605. };
  81606. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  81607. if (!this._attachedCamera) {
  81608. return false;
  81609. }
  81610. var zoomHasHitLimit = false;
  81611. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  81612. zoomHasHitLimit = true;
  81613. }
  81614. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  81615. this._lastFrameRadius = this._attachedCamera.radius;
  81616. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  81617. };
  81618. /**
  81619. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81620. */
  81621. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  81622. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  81623. this._lastInteractionTime = BABYLON.Tools.Now;
  81624. }
  81625. };
  81626. // Tools
  81627. AutoRotationBehavior.prototype._userIsMoving = function () {
  81628. if (!this._attachedCamera) {
  81629. return false;
  81630. }
  81631. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81632. this._attachedCamera.inertialBetaOffset !== 0 ||
  81633. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81634. this._attachedCamera.inertialPanningX !== 0 ||
  81635. this._attachedCamera.inertialPanningY !== 0 ||
  81636. this._isPointerDown;
  81637. };
  81638. return AutoRotationBehavior;
  81639. }());
  81640. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  81641. })(BABYLON || (BABYLON = {}));
  81642. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  81643. var BABYLON;
  81644. (function (BABYLON) {
  81645. /**
  81646. * This class can be used to get instrumentation data from a Babylon engine
  81647. */
  81648. var EngineInstrumentation = /** @class */ (function () {
  81649. function EngineInstrumentation(engine) {
  81650. this.engine = engine;
  81651. this._captureGPUFrameTime = false;
  81652. this._gpuFrameTime = new BABYLON.PerfCounter();
  81653. this._captureShaderCompilationTime = false;
  81654. this._shaderCompilationTime = new BABYLON.PerfCounter();
  81655. // Observers
  81656. this._onBeginFrameObserver = null;
  81657. this._onEndFrameObserver = null;
  81658. this._onBeforeShaderCompilationObserver = null;
  81659. this._onAfterShaderCompilationObserver = null;
  81660. }
  81661. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  81662. // Properties
  81663. /**
  81664. * Gets the perf counter used for GPU frame time
  81665. */
  81666. get: function () {
  81667. return this._gpuFrameTime;
  81668. },
  81669. enumerable: true,
  81670. configurable: true
  81671. });
  81672. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  81673. /**
  81674. * Gets the GPU frame time capture status
  81675. */
  81676. get: function () {
  81677. return this._captureGPUFrameTime;
  81678. },
  81679. /**
  81680. * Enable or disable the GPU frame time capture
  81681. */
  81682. set: function (value) {
  81683. var _this = this;
  81684. if (value === this._captureGPUFrameTime) {
  81685. return;
  81686. }
  81687. this._captureGPUFrameTime = value;
  81688. if (value) {
  81689. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  81690. if (!_this._gpuFrameTimeToken) {
  81691. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  81692. }
  81693. });
  81694. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  81695. if (!_this._gpuFrameTimeToken) {
  81696. return;
  81697. }
  81698. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  81699. if (time > -1) {
  81700. _this._gpuFrameTimeToken = null;
  81701. _this._gpuFrameTime.fetchNewFrame();
  81702. _this._gpuFrameTime.addCount(time, true);
  81703. }
  81704. });
  81705. }
  81706. else {
  81707. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  81708. this._onBeginFrameObserver = null;
  81709. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  81710. this._onEndFrameObserver = null;
  81711. }
  81712. },
  81713. enumerable: true,
  81714. configurable: true
  81715. });
  81716. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  81717. /**
  81718. * Gets the perf counter used for shader compilation time
  81719. */
  81720. get: function () {
  81721. return this._shaderCompilationTime;
  81722. },
  81723. enumerable: true,
  81724. configurable: true
  81725. });
  81726. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  81727. /**
  81728. * Gets the shader compilation time capture status
  81729. */
  81730. get: function () {
  81731. return this._captureShaderCompilationTime;
  81732. },
  81733. /**
  81734. * Enable or disable the shader compilation time capture
  81735. */
  81736. set: function (value) {
  81737. var _this = this;
  81738. if (value === this._captureShaderCompilationTime) {
  81739. return;
  81740. }
  81741. this._captureShaderCompilationTime = value;
  81742. if (value) {
  81743. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  81744. _this._shaderCompilationTime.fetchNewFrame();
  81745. _this._shaderCompilationTime.beginMonitoring();
  81746. });
  81747. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  81748. _this._shaderCompilationTime.endMonitoring();
  81749. });
  81750. }
  81751. else {
  81752. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  81753. this._onBeforeShaderCompilationObserver = null;
  81754. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  81755. this._onAfterShaderCompilationObserver = null;
  81756. }
  81757. },
  81758. enumerable: true,
  81759. configurable: true
  81760. });
  81761. EngineInstrumentation.prototype.dispose = function () {
  81762. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  81763. this._onBeginFrameObserver = null;
  81764. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  81765. this._onEndFrameObserver = null;
  81766. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  81767. this._onBeforeShaderCompilationObserver = null;
  81768. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  81769. this._onAfterShaderCompilationObserver = null;
  81770. this.engine = null;
  81771. };
  81772. return EngineInstrumentation;
  81773. }());
  81774. BABYLON.EngineInstrumentation = EngineInstrumentation;
  81775. })(BABYLON || (BABYLON = {}));
  81776. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  81777. var BABYLON;
  81778. (function (BABYLON) {
  81779. /**
  81780. * This class can be used to get instrumentation data from a Babylon engine
  81781. */
  81782. var SceneInstrumentation = /** @class */ (function () {
  81783. function SceneInstrumentation(scene) {
  81784. var _this = this;
  81785. this.scene = scene;
  81786. this._captureActiveMeshesEvaluationTime = false;
  81787. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  81788. this._captureRenderTargetsRenderTime = false;
  81789. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  81790. this._captureFrameTime = false;
  81791. this._frameTime = new BABYLON.PerfCounter();
  81792. this._captureRenderTime = false;
  81793. this._renderTime = new BABYLON.PerfCounter();
  81794. this._captureInterFrameTime = false;
  81795. this._interFrameTime = new BABYLON.PerfCounter();
  81796. this._captureParticlesRenderTime = false;
  81797. this._particlesRenderTime = new BABYLON.PerfCounter();
  81798. this._captureSpritesRenderTime = false;
  81799. this._spritesRenderTime = new BABYLON.PerfCounter();
  81800. this._capturePhysicsTime = false;
  81801. this._physicsTime = new BABYLON.PerfCounter();
  81802. this._captureAnimationsTime = false;
  81803. this._animationsTime = new BABYLON.PerfCounter();
  81804. // Observers
  81805. this._onBeforeActiveMeshesEvaluationObserver = null;
  81806. this._onAfterActiveMeshesEvaluationObserver = null;
  81807. this._onBeforeRenderTargetsRenderObserver = null;
  81808. this._onAfterRenderTargetsRenderObserver = null;
  81809. this._onAfterRenderObserver = null;
  81810. this._onBeforeDrawPhaseObserver = null;
  81811. this._onAfterDrawPhaseObserver = null;
  81812. this._onBeforeAnimationsObserver = null;
  81813. this._onBeforeParticlesRenderingObserver = null;
  81814. this._onAfterParticlesRenderingObserver = null;
  81815. this._onBeforeSpritesRenderingObserver = null;
  81816. this._onAfterSpritesRenderingObserver = null;
  81817. this._onBeforePhysicsObserver = null;
  81818. this._onAfterPhysicsObserver = null;
  81819. this._onAfterAnimationsObserver = null;
  81820. // Before render
  81821. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  81822. if (_this._captureActiveMeshesEvaluationTime) {
  81823. _this._activeMeshesEvaluationTime.fetchNewFrame();
  81824. }
  81825. if (_this._captureRenderTargetsRenderTime) {
  81826. _this._renderTargetsRenderTime.fetchNewFrame();
  81827. }
  81828. if (_this._captureFrameTime) {
  81829. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  81830. _this._frameTime.beginMonitoring();
  81831. }
  81832. if (_this._captureInterFrameTime) {
  81833. _this._interFrameTime.endMonitoring();
  81834. }
  81835. if (_this._captureParticlesRenderTime) {
  81836. _this._particlesRenderTime.fetchNewFrame();
  81837. }
  81838. if (_this._captureSpritesRenderTime) {
  81839. _this._spritesRenderTime.fetchNewFrame();
  81840. }
  81841. if (_this._captureAnimationsTime) {
  81842. _this._animationsTime.beginMonitoring();
  81843. }
  81844. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  81845. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  81846. });
  81847. // After render
  81848. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  81849. if (_this._captureFrameTime) {
  81850. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  81851. _this._frameTime.endMonitoring();
  81852. }
  81853. if (_this._captureRenderTime) {
  81854. _this._renderTime.endMonitoring(false);
  81855. }
  81856. if (_this._captureInterFrameTime) {
  81857. _this._interFrameTime.beginMonitoring();
  81858. }
  81859. });
  81860. }
  81861. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  81862. // Properties
  81863. /**
  81864. * Gets the perf counter used for active meshes evaluation time
  81865. */
  81866. get: function () {
  81867. return this._activeMeshesEvaluationTime;
  81868. },
  81869. enumerable: true,
  81870. configurable: true
  81871. });
  81872. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  81873. /**
  81874. * Gets the active meshes evaluation time capture status
  81875. */
  81876. get: function () {
  81877. return this._captureActiveMeshesEvaluationTime;
  81878. },
  81879. /**
  81880. * Enable or disable the active meshes evaluation time capture
  81881. */
  81882. set: function (value) {
  81883. var _this = this;
  81884. if (value === this._captureActiveMeshesEvaluationTime) {
  81885. return;
  81886. }
  81887. this._captureActiveMeshesEvaluationTime = value;
  81888. if (value) {
  81889. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  81890. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  81891. _this._activeMeshesEvaluationTime.beginMonitoring();
  81892. });
  81893. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  81894. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  81895. _this._activeMeshesEvaluationTime.endMonitoring();
  81896. });
  81897. }
  81898. else {
  81899. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  81900. this._onBeforeActiveMeshesEvaluationObserver = null;
  81901. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  81902. this._onAfterActiveMeshesEvaluationObserver = null;
  81903. }
  81904. },
  81905. enumerable: true,
  81906. configurable: true
  81907. });
  81908. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  81909. /**
  81910. * Gets the perf counter used for render targets render time
  81911. */
  81912. get: function () {
  81913. return this._renderTargetsRenderTime;
  81914. },
  81915. enumerable: true,
  81916. configurable: true
  81917. });
  81918. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  81919. /**
  81920. * Gets the render targets render time capture status
  81921. */
  81922. get: function () {
  81923. return this._captureRenderTargetsRenderTime;
  81924. },
  81925. /**
  81926. * Enable or disable the render targets render time capture
  81927. */
  81928. set: function (value) {
  81929. var _this = this;
  81930. if (value === this._captureRenderTargetsRenderTime) {
  81931. return;
  81932. }
  81933. this._captureRenderTargetsRenderTime = value;
  81934. if (value) {
  81935. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  81936. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  81937. _this._renderTargetsRenderTime.beginMonitoring();
  81938. });
  81939. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  81940. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  81941. _this._renderTargetsRenderTime.endMonitoring(false);
  81942. });
  81943. }
  81944. else {
  81945. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  81946. this._onBeforeRenderTargetsRenderObserver = null;
  81947. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  81948. this._onAfterRenderTargetsRenderObserver = null;
  81949. }
  81950. },
  81951. enumerable: true,
  81952. configurable: true
  81953. });
  81954. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  81955. /**
  81956. * Gets the perf counter used for particles render time
  81957. */
  81958. get: function () {
  81959. return this._particlesRenderTime;
  81960. },
  81961. enumerable: true,
  81962. configurable: true
  81963. });
  81964. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  81965. /**
  81966. * Gets the particles render time capture status
  81967. */
  81968. get: function () {
  81969. return this._captureParticlesRenderTime;
  81970. },
  81971. /**
  81972. * Enable or disable the particles render time capture
  81973. */
  81974. set: function (value) {
  81975. var _this = this;
  81976. if (value === this._captureParticlesRenderTime) {
  81977. return;
  81978. }
  81979. this._captureParticlesRenderTime = value;
  81980. if (value) {
  81981. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  81982. BABYLON.Tools.StartPerformanceCounter("Particles");
  81983. _this._particlesRenderTime.beginMonitoring();
  81984. });
  81985. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  81986. BABYLON.Tools.EndPerformanceCounter("Particles");
  81987. _this._particlesRenderTime.endMonitoring(false);
  81988. });
  81989. }
  81990. else {
  81991. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  81992. this._onBeforeParticlesRenderingObserver = null;
  81993. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  81994. this._onAfterParticlesRenderingObserver = null;
  81995. }
  81996. },
  81997. enumerable: true,
  81998. configurable: true
  81999. });
  82000. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  82001. /**
  82002. * Gets the perf counter used for sprites render time
  82003. */
  82004. get: function () {
  82005. return this._spritesRenderTime;
  82006. },
  82007. enumerable: true,
  82008. configurable: true
  82009. });
  82010. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  82011. /**
  82012. * Gets the sprites render time capture status
  82013. */
  82014. get: function () {
  82015. return this._captureSpritesRenderTime;
  82016. },
  82017. /**
  82018. * Enable or disable the sprites render time capture
  82019. */
  82020. set: function (value) {
  82021. var _this = this;
  82022. if (value === this._captureSpritesRenderTime) {
  82023. return;
  82024. }
  82025. this._captureSpritesRenderTime = value;
  82026. if (value) {
  82027. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  82028. BABYLON.Tools.StartPerformanceCounter("Sprites");
  82029. _this._spritesRenderTime.beginMonitoring();
  82030. });
  82031. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  82032. BABYLON.Tools.EndPerformanceCounter("Sprites");
  82033. _this._spritesRenderTime.endMonitoring(false);
  82034. });
  82035. }
  82036. else {
  82037. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82038. this._onBeforeSpritesRenderingObserver = null;
  82039. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82040. this._onAfterSpritesRenderingObserver = null;
  82041. }
  82042. },
  82043. enumerable: true,
  82044. configurable: true
  82045. });
  82046. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  82047. /**
  82048. * Gets the perf counter used for physics time
  82049. */
  82050. get: function () {
  82051. return this._physicsTime;
  82052. },
  82053. enumerable: true,
  82054. configurable: true
  82055. });
  82056. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  82057. /**
  82058. * Gets the physics time capture status
  82059. */
  82060. get: function () {
  82061. return this._capturePhysicsTime;
  82062. },
  82063. /**
  82064. * Enable or disable the physics time capture
  82065. */
  82066. set: function (value) {
  82067. var _this = this;
  82068. if (value === this._capturePhysicsTime) {
  82069. return;
  82070. }
  82071. this._capturePhysicsTime = value;
  82072. if (value) {
  82073. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  82074. BABYLON.Tools.StartPerformanceCounter("Physics");
  82075. _this._physicsTime.beginMonitoring();
  82076. });
  82077. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  82078. BABYLON.Tools.EndPerformanceCounter("Physics");
  82079. _this._physicsTime.endMonitoring();
  82080. });
  82081. }
  82082. else {
  82083. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82084. this._onBeforePhysicsObserver = null;
  82085. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82086. this._onAfterPhysicsObserver = null;
  82087. }
  82088. },
  82089. enumerable: true,
  82090. configurable: true
  82091. });
  82092. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  82093. /**
  82094. * Gets the perf counter used for animations time
  82095. */
  82096. get: function () {
  82097. return this._animationsTime;
  82098. },
  82099. enumerable: true,
  82100. configurable: true
  82101. });
  82102. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  82103. /**
  82104. * Gets the animations time capture status
  82105. */
  82106. get: function () {
  82107. return this._captureAnimationsTime;
  82108. },
  82109. /**
  82110. * Enable or disable the animations time capture
  82111. */
  82112. set: function (value) {
  82113. var _this = this;
  82114. if (value === this._captureAnimationsTime) {
  82115. return;
  82116. }
  82117. this._captureAnimationsTime = value;
  82118. if (value) {
  82119. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  82120. _this._animationsTime.endMonitoring();
  82121. });
  82122. }
  82123. else {
  82124. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82125. this._onAfterAnimationsObserver = null;
  82126. }
  82127. },
  82128. enumerable: true,
  82129. configurable: true
  82130. });
  82131. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  82132. /**
  82133. * Gets the perf counter used for frame time capture
  82134. */
  82135. get: function () {
  82136. return this._frameTime;
  82137. },
  82138. enumerable: true,
  82139. configurable: true
  82140. });
  82141. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  82142. /**
  82143. * Gets the frame time capture status
  82144. */
  82145. get: function () {
  82146. return this._captureFrameTime;
  82147. },
  82148. /**
  82149. * Enable or disable the frame time capture
  82150. */
  82151. set: function (value) {
  82152. this._captureFrameTime = value;
  82153. },
  82154. enumerable: true,
  82155. configurable: true
  82156. });
  82157. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  82158. /**
  82159. * Gets the perf counter used for inter-frames time capture
  82160. */
  82161. get: function () {
  82162. return this._interFrameTime;
  82163. },
  82164. enumerable: true,
  82165. configurable: true
  82166. });
  82167. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  82168. /**
  82169. * Gets the inter-frames time capture status
  82170. */
  82171. get: function () {
  82172. return this._captureInterFrameTime;
  82173. },
  82174. /**
  82175. * Enable or disable the inter-frames time capture
  82176. */
  82177. set: function (value) {
  82178. this._captureInterFrameTime = value;
  82179. },
  82180. enumerable: true,
  82181. configurable: true
  82182. });
  82183. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  82184. /**
  82185. * Gets the perf counter used for render time capture
  82186. */
  82187. get: function () {
  82188. return this._renderTime;
  82189. },
  82190. enumerable: true,
  82191. configurable: true
  82192. });
  82193. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  82194. /**
  82195. * Gets the render time capture status
  82196. */
  82197. get: function () {
  82198. return this._captureRenderTime;
  82199. },
  82200. /**
  82201. * Enable or disable the render time capture
  82202. */
  82203. set: function (value) {
  82204. var _this = this;
  82205. if (value === this._captureRenderTime) {
  82206. return;
  82207. }
  82208. this._captureRenderTime = value;
  82209. if (value) {
  82210. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  82211. _this._renderTime.beginMonitoring();
  82212. BABYLON.Tools.StartPerformanceCounter("Main render");
  82213. });
  82214. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  82215. _this._renderTime.endMonitoring(false);
  82216. BABYLON.Tools.EndPerformanceCounter("Main render");
  82217. });
  82218. }
  82219. else {
  82220. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82221. this._onBeforeDrawPhaseObserver = null;
  82222. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82223. this._onAfterDrawPhaseObserver = null;
  82224. }
  82225. },
  82226. enumerable: true,
  82227. configurable: true
  82228. });
  82229. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  82230. /**
  82231. * Gets the perf counter used for draw calls
  82232. */
  82233. get: function () {
  82234. return this.scene.getEngine()._drawCalls;
  82235. },
  82236. enumerable: true,
  82237. configurable: true
  82238. });
  82239. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  82240. /**
  82241. * Gets the perf counter used for texture collisions
  82242. */
  82243. get: function () {
  82244. return this.scene.getEngine()._textureCollisions;
  82245. },
  82246. enumerable: true,
  82247. configurable: true
  82248. });
  82249. SceneInstrumentation.prototype.dispose = function () {
  82250. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  82251. this._onAfterRenderObserver = null;
  82252. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  82253. this._onBeforeActiveMeshesEvaluationObserver = null;
  82254. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  82255. this._onAfterActiveMeshesEvaluationObserver = null;
  82256. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  82257. this._onBeforeRenderTargetsRenderObserver = null;
  82258. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  82259. this._onAfterRenderTargetsRenderObserver = null;
  82260. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  82261. this._onBeforeAnimationsObserver = null;
  82262. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82263. this._onBeforeParticlesRenderingObserver = null;
  82264. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82265. this._onAfterParticlesRenderingObserver = null;
  82266. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82267. this._onBeforeSpritesRenderingObserver = null;
  82268. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82269. this._onAfterSpritesRenderingObserver = null;
  82270. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82271. this._onBeforeDrawPhaseObserver = null;
  82272. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82273. this._onAfterDrawPhaseObserver = null;
  82274. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82275. this._onBeforePhysicsObserver = null;
  82276. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82277. this._onAfterPhysicsObserver = null;
  82278. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82279. this._onAfterAnimationsObserver = null;
  82280. this.scene = null;
  82281. };
  82282. return SceneInstrumentation;
  82283. }());
  82284. BABYLON.SceneInstrumentation = SceneInstrumentation;
  82285. })(BABYLON || (BABYLON = {}));
  82286. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  82287. var BABYLON;
  82288. (function (BABYLON) {
  82289. var _TimeToken = /** @class */ (function () {
  82290. function _TimeToken() {
  82291. this._timeElapsedQueryEnded = false;
  82292. }
  82293. return _TimeToken;
  82294. }());
  82295. BABYLON._TimeToken = _TimeToken;
  82296. })(BABYLON || (BABYLON = {}));
  82297. //# sourceMappingURL=babylon.timeToken.js.map
  82298. var BABYLON;
  82299. (function (BABYLON) {
  82300. /**
  82301. * Background material defines definition.
  82302. */
  82303. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  82304. __extends(BackgroundMaterialDefines, _super);
  82305. /**
  82306. * Constructor of the defines.
  82307. */
  82308. function BackgroundMaterialDefines() {
  82309. var _this = _super.call(this) || this;
  82310. /**
  82311. * True if the diffuse texture is in use.
  82312. */
  82313. _this.DIFFUSE = false;
  82314. /**
  82315. * The direct UV channel to use.
  82316. */
  82317. _this.DIFFUSEDIRECTUV = 0;
  82318. /**
  82319. * True if the diffuse texture is in gamma space.
  82320. */
  82321. _this.GAMMADIFFUSE = false;
  82322. /**
  82323. * True if the diffuse texture has opacity in the alpha channel.
  82324. */
  82325. _this.DIFFUSEHASALPHA = false;
  82326. /**
  82327. * True if you want the material to fade to transparent at grazing angle.
  82328. */
  82329. _this.OPACITYFRESNEL = false;
  82330. /**
  82331. * True if an extra blur needs to be added in the reflection.
  82332. */
  82333. _this.REFLECTIONBLUR = false;
  82334. /**
  82335. * True if you want the material to fade to reflection at grazing angle.
  82336. */
  82337. _this.REFLECTIONFRESNEL = false;
  82338. /**
  82339. * True if you want the material to falloff as far as you move away from the scene center.
  82340. */
  82341. _this.REFLECTIONFALLOFF = false;
  82342. /**
  82343. * False if the current Webgl implementation does not support the texture lod extension.
  82344. */
  82345. _this.TEXTURELODSUPPORT = false;
  82346. /**
  82347. * True to ensure the data are premultiplied.
  82348. */
  82349. _this.PREMULTIPLYALPHA = false;
  82350. /**
  82351. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  82352. */
  82353. _this.USERGBCOLOR = false;
  82354. /**
  82355. * True to add noise in order to reduce the banding effect.
  82356. */
  82357. _this.NOISE = false;
  82358. // Image Processing Configuration.
  82359. _this.IMAGEPROCESSING = false;
  82360. _this.VIGNETTE = false;
  82361. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  82362. _this.VIGNETTEBLENDMODEOPAQUE = false;
  82363. _this.TONEMAPPING = false;
  82364. _this.CONTRAST = false;
  82365. _this.COLORCURVES = false;
  82366. _this.COLORGRADING = false;
  82367. _this.COLORGRADING3D = false;
  82368. _this.SAMPLER3DGREENDEPTH = false;
  82369. _this.SAMPLER3DBGRMAP = false;
  82370. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  82371. _this.EXPOSURE = false;
  82372. // Reflection.
  82373. _this.REFLECTION = false;
  82374. _this.REFLECTIONMAP_3D = false;
  82375. _this.REFLECTIONMAP_SPHERICAL = false;
  82376. _this.REFLECTIONMAP_PLANAR = false;
  82377. _this.REFLECTIONMAP_CUBIC = false;
  82378. _this.REFLECTIONMAP_PROJECTION = false;
  82379. _this.REFLECTIONMAP_SKYBOX = false;
  82380. _this.REFLECTIONMAP_EXPLICIT = false;
  82381. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  82382. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  82383. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  82384. _this.INVERTCUBICMAP = false;
  82385. _this.REFLECTIONMAP_OPPOSITEZ = false;
  82386. _this.LODINREFLECTIONALPHA = false;
  82387. _this.GAMMAREFLECTION = false;
  82388. // Default BJS.
  82389. _this.MAINUV1 = false;
  82390. _this.MAINUV2 = false;
  82391. _this.UV1 = false;
  82392. _this.UV2 = false;
  82393. _this.CLIPPLANE = false;
  82394. _this.POINTSIZE = false;
  82395. _this.FOG = false;
  82396. _this.NORMAL = false;
  82397. _this.NUM_BONE_INFLUENCERS = 0;
  82398. _this.BonesPerMesh = 0;
  82399. _this.INSTANCES = false;
  82400. _this.SHADOWFLOAT = false;
  82401. _this.rebuild();
  82402. return _this;
  82403. }
  82404. return BackgroundMaterialDefines;
  82405. }(BABYLON.MaterialDefines));
  82406. /**
  82407. * Background material used to create an efficient environement around your scene.
  82408. */
  82409. var BackgroundMaterial = /** @class */ (function (_super) {
  82410. __extends(BackgroundMaterial, _super);
  82411. /**
  82412. * constructor
  82413. * @param name The name of the material
  82414. * @param scene The scene to add the material to
  82415. */
  82416. function BackgroundMaterial(name, scene) {
  82417. var _this = _super.call(this, name, scene) || this;
  82418. _this.primaryColor = BABYLON.Color3.White();
  82419. _this.primaryLevel = 1;
  82420. _this.secondaryColor = BABYLON.Color3.Gray();
  82421. _this.secondaryLevel = 1;
  82422. _this.tertiaryColor = BABYLON.Color3.Black();
  82423. _this.tertiaryLevel = 1;
  82424. _this.reflectionTexture = null;
  82425. _this.reflectionBlur = 0;
  82426. _this.diffuseTexture = null;
  82427. /**
  82428. * Specify the list of lights casting shadow on the material.
  82429. * All scene shadow lights will be included if null.
  82430. */
  82431. _this._shadowLights = null;
  82432. _this.shadowLights = null;
  82433. _this.shadowBlurScale = 1;
  82434. _this.shadowLevel = 0;
  82435. _this.sceneCenter = BABYLON.Vector3.Zero();
  82436. _this.opacityFresnel = true;
  82437. _this.reflectionFresnel = false;
  82438. _this.reflectionFalloffDistance = 0.0;
  82439. _this.reflectionAmount = 1.0;
  82440. _this.reflectionReflectance0 = 0.05;
  82441. _this.reflectionReflectance90 = 0.5;
  82442. _this.useRGBColor = true;
  82443. _this.enableNoise = false;
  82444. /**
  82445. * Number of Simultaneous lights allowed on the material.
  82446. */
  82447. _this._maxSimultaneousLights = 4;
  82448. _this.maxSimultaneousLights = 4;
  82449. /**
  82450. * Keep track of the image processing observer to allow dispose and replace.
  82451. */
  82452. _this._imageProcessingObserver = null;
  82453. // Temp values kept as cache in the material.
  82454. _this._renderTargets = new BABYLON.SmartArray(16);
  82455. _this._reflectionControls = BABYLON.Vector4.Zero();
  82456. // Setup the default processing configuration to the scene.
  82457. _this._attachImageProcessingConfiguration(null);
  82458. _this.getRenderTargetTextures = function () {
  82459. _this._renderTargets.reset();
  82460. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  82461. _this._renderTargets.push(_this._diffuseTexture);
  82462. }
  82463. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  82464. _this._renderTargets.push(_this._reflectionTexture);
  82465. }
  82466. return _this._renderTargets;
  82467. };
  82468. return _this;
  82469. }
  82470. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  82471. /**
  82472. * Sets the reflection reflectance fresnel values according to the default standard
  82473. * empirically know to work well :-)
  82474. */
  82475. set: function (value) {
  82476. var reflectionWeight = value;
  82477. if (reflectionWeight < 0.5) {
  82478. reflectionWeight = reflectionWeight * 2.0;
  82479. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  82480. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  82481. }
  82482. else {
  82483. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  82484. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  82485. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  82486. }
  82487. },
  82488. enumerable: true,
  82489. configurable: true
  82490. });
  82491. /**
  82492. * Attaches a new image processing configuration to the PBR Material.
  82493. * @param configuration (if null the scene configuration will be use)
  82494. */
  82495. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  82496. var _this = this;
  82497. if (configuration === this._imageProcessingConfiguration) {
  82498. return;
  82499. }
  82500. // Detaches observer.
  82501. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82502. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82503. }
  82504. // Pick the scene configuration if needed.
  82505. if (!configuration) {
  82506. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  82507. }
  82508. else {
  82509. this._imageProcessingConfiguration = configuration;
  82510. }
  82511. // Attaches observer.
  82512. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82513. _this._markAllSubMeshesAsImageProcessingDirty();
  82514. });
  82515. };
  82516. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  82517. /**
  82518. * Gets the image processing configuration used either in this material.
  82519. */
  82520. get: function () {
  82521. return this._imageProcessingConfiguration;
  82522. },
  82523. /**
  82524. * Sets the Default image processing configuration used either in the this material.
  82525. *
  82526. * If sets to null, the scene one is in use.
  82527. */
  82528. set: function (value) {
  82529. this._attachImageProcessingConfiguration(value);
  82530. // Ensure the effect will be rebuilt.
  82531. this._markAllSubMeshesAsTexturesDirty();
  82532. },
  82533. enumerable: true,
  82534. configurable: true
  82535. });
  82536. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  82537. /**
  82538. * Gets wether the color curves effect is enabled.
  82539. */
  82540. get: function () {
  82541. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82542. },
  82543. /**
  82544. * Sets wether the color curves effect is enabled.
  82545. */
  82546. set: function (value) {
  82547. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82548. },
  82549. enumerable: true,
  82550. configurable: true
  82551. });
  82552. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  82553. /**
  82554. * Gets wether the color grading effect is enabled.
  82555. */
  82556. get: function () {
  82557. return this.imageProcessingConfiguration.colorGradingEnabled;
  82558. },
  82559. /**
  82560. * Gets wether the color grading effect is enabled.
  82561. */
  82562. set: function (value) {
  82563. this.imageProcessingConfiguration.colorGradingEnabled = value;
  82564. },
  82565. enumerable: true,
  82566. configurable: true
  82567. });
  82568. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  82569. /**
  82570. * Gets wether tonemapping is enabled or not.
  82571. */
  82572. get: function () {
  82573. return this._imageProcessingConfiguration.toneMappingEnabled;
  82574. },
  82575. /**
  82576. * Sets wether tonemapping is enabled or not
  82577. */
  82578. set: function (value) {
  82579. this._imageProcessingConfiguration.toneMappingEnabled = value;
  82580. },
  82581. enumerable: true,
  82582. configurable: true
  82583. });
  82584. ;
  82585. ;
  82586. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  82587. /**
  82588. * The camera exposure used on this material.
  82589. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  82590. * This corresponds to a photographic exposure.
  82591. */
  82592. get: function () {
  82593. return this._imageProcessingConfiguration.exposure;
  82594. },
  82595. /**
  82596. * The camera exposure used on this material.
  82597. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  82598. * This corresponds to a photographic exposure.
  82599. */
  82600. set: function (value) {
  82601. this._imageProcessingConfiguration.exposure = value;
  82602. },
  82603. enumerable: true,
  82604. configurable: true
  82605. });
  82606. ;
  82607. ;
  82608. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  82609. /**
  82610. * Gets The camera contrast used on this material.
  82611. */
  82612. get: function () {
  82613. return this._imageProcessingConfiguration.contrast;
  82614. },
  82615. /**
  82616. * Sets The camera contrast used on this material.
  82617. */
  82618. set: function (value) {
  82619. this._imageProcessingConfiguration.contrast = value;
  82620. },
  82621. enumerable: true,
  82622. configurable: true
  82623. });
  82624. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  82625. /**
  82626. * Gets the Color Grading 2D Lookup Texture.
  82627. */
  82628. get: function () {
  82629. return this._imageProcessingConfiguration.colorGradingTexture;
  82630. },
  82631. /**
  82632. * Sets the Color Grading 2D Lookup Texture.
  82633. */
  82634. set: function (value) {
  82635. this.imageProcessingConfiguration.colorGradingTexture = value;
  82636. },
  82637. enumerable: true,
  82638. configurable: true
  82639. });
  82640. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  82641. /**
  82642. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82643. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82644. * 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;
  82645. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82646. */
  82647. get: function () {
  82648. return this.imageProcessingConfiguration.colorCurves;
  82649. },
  82650. /**
  82651. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82652. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82653. * 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;
  82654. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82655. */
  82656. set: function (value) {
  82657. this.imageProcessingConfiguration.colorCurves = value;
  82658. },
  82659. enumerable: true,
  82660. configurable: true
  82661. });
  82662. /**
  82663. * The entire material has been created in order to prevent overdraw.
  82664. * @returns false
  82665. */
  82666. BackgroundMaterial.prototype.needAlphaTesting = function () {
  82667. return true;
  82668. };
  82669. /**
  82670. * The entire material has been created in order to prevent overdraw.
  82671. * @returns true if blending is enable
  82672. */
  82673. BackgroundMaterial.prototype.needAlphaBlending = function () {
  82674. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  82675. };
  82676. /**
  82677. * Checks wether the material is ready to be rendered for a given mesh.
  82678. * @param mesh The mesh to render
  82679. * @param subMesh The submesh to check against
  82680. * @param useInstances Specify wether or not the material is used with instances
  82681. */
  82682. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  82683. var _this = this;
  82684. if (useInstances === void 0) { useInstances = false; }
  82685. if (subMesh.effect && this.isFrozen) {
  82686. if (this._wasPreviouslyReady) {
  82687. return true;
  82688. }
  82689. }
  82690. if (!subMesh._materialDefines) {
  82691. subMesh._materialDefines = new BackgroundMaterialDefines();
  82692. }
  82693. var scene = this.getScene();
  82694. var defines = subMesh._materialDefines;
  82695. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  82696. if (defines._renderId === scene.getRenderId()) {
  82697. return true;
  82698. }
  82699. }
  82700. var engine = scene.getEngine();
  82701. // Lights
  82702. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  82703. defines._needNormals = true;
  82704. // Textures
  82705. if (defines._areTexturesDirty) {
  82706. defines._needUVs = false;
  82707. if (scene.texturesEnabled) {
  82708. if (scene.getEngine().getCaps().textureLOD) {
  82709. defines.TEXTURELODSUPPORT = true;
  82710. }
  82711. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  82712. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  82713. return false;
  82714. }
  82715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  82716. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  82717. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  82718. defines.OPACITYFRESNEL = this._opacityFresnel;
  82719. }
  82720. else {
  82721. defines.DIFFUSE = false;
  82722. defines.DIFFUSEHASALPHA = false;
  82723. defines.GAMMADIFFUSE = false;
  82724. defines.OPACITYFRESNEL = false;
  82725. }
  82726. var reflectionTexture = this._reflectionTexture;
  82727. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  82728. if (!reflectionTexture.isReadyOrNotBlocking()) {
  82729. return false;
  82730. }
  82731. defines.REFLECTION = true;
  82732. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  82733. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  82734. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  82735. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  82736. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  82737. defines.INVERTCUBICMAP = true;
  82738. }
  82739. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  82740. switch (reflectionTexture.coordinatesMode) {
  82741. case BABYLON.Texture.CUBIC_MODE:
  82742. case BABYLON.Texture.INVCUBIC_MODE:
  82743. defines.REFLECTIONMAP_CUBIC = true;
  82744. break;
  82745. case BABYLON.Texture.EXPLICIT_MODE:
  82746. defines.REFLECTIONMAP_EXPLICIT = true;
  82747. break;
  82748. case BABYLON.Texture.PLANAR_MODE:
  82749. defines.REFLECTIONMAP_PLANAR = true;
  82750. break;
  82751. case BABYLON.Texture.PROJECTION_MODE:
  82752. defines.REFLECTIONMAP_PROJECTION = true;
  82753. break;
  82754. case BABYLON.Texture.SKYBOX_MODE:
  82755. defines.REFLECTIONMAP_SKYBOX = true;
  82756. break;
  82757. case BABYLON.Texture.SPHERICAL_MODE:
  82758. defines.REFLECTIONMAP_SPHERICAL = true;
  82759. break;
  82760. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  82761. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  82762. break;
  82763. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  82764. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  82765. break;
  82766. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  82767. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  82768. break;
  82769. }
  82770. if (this.reflectionFresnel) {
  82771. defines.REFLECTIONFRESNEL = true;
  82772. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  82773. this._reflectionControls.x = this.reflectionAmount;
  82774. this._reflectionControls.y = this.reflectionReflectance0;
  82775. this._reflectionControls.z = this.reflectionReflectance90;
  82776. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  82777. }
  82778. else {
  82779. defines.REFLECTIONFRESNEL = false;
  82780. defines.REFLECTIONFALLOFF = false;
  82781. }
  82782. }
  82783. else {
  82784. defines.REFLECTION = false;
  82785. defines.REFLECTIONFALLOFF = false;
  82786. defines.REFLECTIONBLUR = false;
  82787. defines.REFLECTIONMAP_3D = false;
  82788. defines.REFLECTIONMAP_SPHERICAL = false;
  82789. defines.REFLECTIONMAP_PLANAR = false;
  82790. defines.REFLECTIONMAP_CUBIC = false;
  82791. defines.REFLECTIONMAP_PROJECTION = false;
  82792. defines.REFLECTIONMAP_SKYBOX = false;
  82793. defines.REFLECTIONMAP_EXPLICIT = false;
  82794. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  82795. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  82796. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  82797. defines.INVERTCUBICMAP = false;
  82798. defines.REFLECTIONMAP_OPPOSITEZ = false;
  82799. defines.LODINREFLECTIONALPHA = false;
  82800. defines.GAMMAREFLECTION = false;
  82801. }
  82802. }
  82803. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  82804. defines.USERGBCOLOR = this._useRGBColor;
  82805. defines.NOISE = this._enableNoise;
  82806. }
  82807. if (defines._areImageProcessingDirty) {
  82808. if (!this._imageProcessingConfiguration.isReady()) {
  82809. return false;
  82810. }
  82811. this._imageProcessingConfiguration.prepareDefines(defines);
  82812. }
  82813. // Misc.
  82814. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  82815. // Values that need to be evaluated on every frame
  82816. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  82817. // Attribs
  82818. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  82819. if (mesh) {
  82820. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  82821. mesh.createNormals(true);
  82822. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  82823. }
  82824. }
  82825. }
  82826. // Get correct effect
  82827. if (defines.isDirty) {
  82828. defines.markAsProcessed();
  82829. scene.resetCachedMaterial();
  82830. // Fallbacks
  82831. var fallbacks = new BABYLON.EffectFallbacks();
  82832. if (defines.FOG) {
  82833. fallbacks.addFallback(0, "FOG");
  82834. }
  82835. if (defines.POINTSIZE) {
  82836. fallbacks.addFallback(1, "POINTSIZE");
  82837. }
  82838. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  82839. if (defines.NUM_BONE_INFLUENCERS > 0) {
  82840. fallbacks.addCPUSkinningFallback(0, mesh);
  82841. }
  82842. //Attributes
  82843. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82844. if (defines.NORMAL) {
  82845. attribs.push(BABYLON.VertexBuffer.NormalKind);
  82846. }
  82847. if (defines.UV1) {
  82848. attribs.push(BABYLON.VertexBuffer.UVKind);
  82849. }
  82850. if (defines.UV2) {
  82851. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82852. }
  82853. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  82854. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  82855. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  82856. "vFogInfos", "vFogColor", "pointSize",
  82857. "vClipPlane", "mBones",
  82858. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  82859. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  82860. "shadowLevel", "alpha",
  82861. "vBackgroundCenter", "vReflectionControl",
  82862. "vDiffuseInfos", "diffuseMatrix",
  82863. ];
  82864. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  82865. var uniformBuffers = ["Material", "Scene"];
  82866. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  82867. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  82868. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  82869. uniformsNames: uniforms,
  82870. uniformBuffersNames: uniformBuffers,
  82871. samplers: samplers,
  82872. defines: defines,
  82873. maxSimultaneousLights: this._maxSimultaneousLights
  82874. });
  82875. var onCompiled = function (effect) {
  82876. if (_this.onCompiled) {
  82877. _this.onCompiled(effect);
  82878. }
  82879. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  82880. };
  82881. var join = defines.toString();
  82882. subMesh.setEffect(scene.getEngine().createEffect("background", {
  82883. attributes: attribs,
  82884. uniformsNames: uniforms,
  82885. uniformBuffersNames: uniformBuffers,
  82886. samplers: samplers,
  82887. defines: join,
  82888. fallbacks: fallbacks,
  82889. onCompiled: onCompiled,
  82890. onError: this.onError,
  82891. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  82892. }, engine), defines);
  82893. this.buildUniformLayout();
  82894. }
  82895. if (!subMesh.effect || !subMesh.effect.isReady()) {
  82896. return false;
  82897. }
  82898. defines._renderId = scene.getRenderId();
  82899. this._wasPreviouslyReady = true;
  82900. return true;
  82901. };
  82902. /**
  82903. * Build the uniform buffer used in the material.
  82904. */
  82905. BackgroundMaterial.prototype.buildUniformLayout = function () {
  82906. // Order is important !
  82907. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  82908. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  82909. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  82910. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  82911. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  82912. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  82913. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  82914. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  82915. this._uniformBuffer.addUniform("pointSize", 1);
  82916. this._uniformBuffer.addUniform("shadowLevel", 1);
  82917. this._uniformBuffer.addUniform("alpha", 1);
  82918. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  82919. this._uniformBuffer.addUniform("vReflectionControl", 4);
  82920. this._uniformBuffer.create();
  82921. };
  82922. /**
  82923. * Unbind the material.
  82924. */
  82925. BackgroundMaterial.prototype.unbind = function () {
  82926. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  82927. this._uniformBuffer.setTexture("diffuseSampler", null);
  82928. }
  82929. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  82930. this._uniformBuffer.setTexture("reflectionSampler", null);
  82931. }
  82932. _super.prototype.unbind.call(this);
  82933. };
  82934. /**
  82935. * Bind only the world matrix to the material.
  82936. * @param world The world matrix to bind.
  82937. */
  82938. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  82939. this._activeEffect.setMatrix("world", world);
  82940. };
  82941. /**
  82942. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  82943. * @param world The world matrix to bind.
  82944. * @param subMesh The submesh to bind for.
  82945. */
  82946. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  82947. var scene = this.getScene();
  82948. var defines = subMesh._materialDefines;
  82949. if (!defines) {
  82950. return;
  82951. }
  82952. var effect = subMesh.effect;
  82953. if (!effect) {
  82954. return;
  82955. }
  82956. this._activeEffect = effect;
  82957. // Matrices
  82958. this.bindOnlyWorldMatrix(world);
  82959. // Bones
  82960. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  82961. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  82962. if (mustRebind) {
  82963. this._uniformBuffer.bindToEffect(effect, "Material");
  82964. this.bindViewProjection(effect);
  82965. var reflectionTexture = this._reflectionTexture;
  82966. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  82967. // Texture uniforms
  82968. if (scene.texturesEnabled) {
  82969. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  82970. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  82971. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  82972. }
  82973. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  82974. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  82975. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  82976. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  82977. }
  82978. }
  82979. if (this.shadowLevel > 0) {
  82980. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  82981. }
  82982. this._uniformBuffer.updateFloat("alpha", this.alpha);
  82983. // Point size
  82984. if (this.pointsCloud) {
  82985. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  82986. }
  82987. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  82988. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  82989. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  82990. }
  82991. // Textures
  82992. if (scene.texturesEnabled) {
  82993. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  82994. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  82995. }
  82996. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  82997. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  82998. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  82999. }
  83000. else if (!defines.REFLECTIONBLUR) {
  83001. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83002. }
  83003. else {
  83004. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  83005. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  83006. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  83007. }
  83008. if (defines.REFLECTIONFRESNEL) {
  83009. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  83010. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  83011. }
  83012. }
  83013. }
  83014. // Clip plane
  83015. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  83016. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  83017. }
  83018. if (mustRebind || !this.isFrozen) {
  83019. if (scene.lightsEnabled) {
  83020. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  83021. }
  83022. // View
  83023. this.bindView(effect);
  83024. // Fog
  83025. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  83026. // image processing
  83027. this._imageProcessingConfiguration.bind(this._activeEffect);
  83028. }
  83029. this._uniformBuffer.update();
  83030. this._afterBind(mesh);
  83031. };
  83032. /**
  83033. * Dispose the material.
  83034. * @forceDisposeEffect Force disposal of the associated effect.
  83035. * @forceDisposeTextures Force disposal of the associated textures.
  83036. */
  83037. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  83038. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  83039. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  83040. if (forceDisposeTextures) {
  83041. if (this.diffuseTexture) {
  83042. this.diffuseTexture.dispose();
  83043. }
  83044. if (this.reflectionTexture) {
  83045. this.reflectionTexture.dispose();
  83046. }
  83047. }
  83048. this._renderTargets.dispose();
  83049. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83050. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83051. }
  83052. _super.prototype.dispose.call(this, forceDisposeEffect);
  83053. };
  83054. /**
  83055. * Clones the material.
  83056. * @name The cloned name.
  83057. * @returns The cloned material.
  83058. */
  83059. BackgroundMaterial.prototype.clone = function (name) {
  83060. var _this = this;
  83061. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  83062. };
  83063. /**
  83064. * Serializes the current material to its JSON representation.
  83065. * @returns The JSON representation.
  83066. */
  83067. BackgroundMaterial.prototype.serialize = function () {
  83068. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83069. serializationObject.customType = "BABYLON.BackgroundMaterial";
  83070. return serializationObject;
  83071. };
  83072. /**
  83073. * Gets the class name of the material
  83074. * @returns "BackgroundMaterial"
  83075. */
  83076. BackgroundMaterial.prototype.getClassName = function () {
  83077. return "BackgroundMaterial";
  83078. };
  83079. /**
  83080. * Parse a JSON input to create back a background material.
  83081. * @param source
  83082. * @param scene
  83083. * @param rootUrl
  83084. * @returns the instantiated BackgroundMaterial.
  83085. */
  83086. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  83087. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  83088. };
  83089. /**
  83090. * Standard reflectance value at parallel view angle.
  83091. */
  83092. BackgroundMaterial.standardReflectance0 = 0.05;
  83093. /**
  83094. * Standard reflectance value at grazing angle.
  83095. */
  83096. BackgroundMaterial.standardReflectance90 = 0.5;
  83097. __decorate([
  83098. BABYLON.serializeAsColor3()
  83099. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  83100. __decorate([
  83101. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83102. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  83103. __decorate([
  83104. BABYLON.serialize()
  83105. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  83106. __decorate([
  83107. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83108. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  83109. __decorate([
  83110. BABYLON.serializeAsColor3()
  83111. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  83112. __decorate([
  83113. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83114. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  83115. __decorate([
  83116. BABYLON.serialize()
  83117. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  83118. __decorate([
  83119. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83120. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  83121. __decorate([
  83122. BABYLON.serializeAsColor3()
  83123. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  83124. __decorate([
  83125. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83126. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  83127. __decorate([
  83128. BABYLON.serialize()
  83129. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  83130. __decorate([
  83131. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83132. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  83133. __decorate([
  83134. BABYLON.serializeAsTexture()
  83135. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  83136. __decorate([
  83137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83138. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  83139. __decorate([
  83140. BABYLON.serialize()
  83141. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  83142. __decorate([
  83143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83144. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  83145. __decorate([
  83146. BABYLON.serializeAsTexture()
  83147. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  83148. __decorate([
  83149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83150. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  83151. __decorate([
  83152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83153. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  83154. __decorate([
  83155. BABYLON.serialize()
  83156. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  83157. __decorate([
  83158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83159. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  83160. __decorate([
  83161. BABYLON.serialize()
  83162. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  83163. __decorate([
  83164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83165. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  83166. __decorate([
  83167. BABYLON.serializeAsVector3()
  83168. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  83169. __decorate([
  83170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83171. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  83172. __decorate([
  83173. BABYLON.serialize()
  83174. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  83175. __decorate([
  83176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83177. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  83178. __decorate([
  83179. BABYLON.serialize()
  83180. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  83181. __decorate([
  83182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83183. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  83184. __decorate([
  83185. BABYLON.serialize()
  83186. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  83187. __decorate([
  83188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83189. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  83190. __decorate([
  83191. BABYLON.serialize()
  83192. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  83193. __decorate([
  83194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83195. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  83196. __decorate([
  83197. BABYLON.serialize()
  83198. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  83199. __decorate([
  83200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83201. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  83202. __decorate([
  83203. BABYLON.serialize()
  83204. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  83205. __decorate([
  83206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83207. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  83208. __decorate([
  83209. BABYLON.serialize()
  83210. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  83211. __decorate([
  83212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83213. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  83214. __decorate([
  83215. BABYLON.serialize()
  83216. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  83217. __decorate([
  83218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83219. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  83220. __decorate([
  83221. BABYLON.serialize()
  83222. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  83223. __decorate([
  83224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83225. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  83226. __decorate([
  83227. BABYLON.serializeAsImageProcessingConfiguration()
  83228. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  83229. return BackgroundMaterial;
  83230. }(BABYLON.PushMaterial));
  83231. BABYLON.BackgroundMaterial = BackgroundMaterial;
  83232. })(BABYLON || (BABYLON = {}));
  83233. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  83234. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83235. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83236. s = arguments[i];
  83237. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83238. t[p] = s[p];
  83239. }
  83240. return t;
  83241. };
  83242. var BABYLON;
  83243. (function (BABYLON) {
  83244. /**
  83245. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  83246. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  83247. * It also helps with the default setup of your imageProcessing configuration.
  83248. */
  83249. var EnvironmentHelper = /** @class */ (function () {
  83250. /**
  83251. * constructor
  83252. * @param options
  83253. * @param scene The scene to add the material to
  83254. */
  83255. function EnvironmentHelper(options, scene) {
  83256. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  83257. this._scene = scene;
  83258. this._setupBackground();
  83259. this._setupImageProcessing();
  83260. }
  83261. /**
  83262. * Creates the default options for the helper.
  83263. */
  83264. EnvironmentHelper._getDefaultOptions = function () {
  83265. return {
  83266. createGround: true,
  83267. groundSize: 15,
  83268. groundTexture: this._groundTextureCDNUrl,
  83269. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  83270. groundOpacity: 0.9,
  83271. enableGroundShadow: true,
  83272. groundShadowLevel: 0.5,
  83273. enableGroundMirror: false,
  83274. groundMirrorSizeRatio: 0.3,
  83275. groundMirrorBlurKernel: 64,
  83276. groundMirrorAmount: 1,
  83277. groundMirrorFresnelWeight: 1,
  83278. groundMirrorFallOffDistance: 0,
  83279. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  83280. groundYBias: 0.00001,
  83281. createSkybox: true,
  83282. skyboxSize: 20,
  83283. skyboxTexture: this._skyboxTextureCDNUrl,
  83284. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  83285. backgroundYRotation: 0,
  83286. sizeAuto: true,
  83287. rootPosition: BABYLON.Vector3.Zero(),
  83288. setupImageProcessing: true,
  83289. environmentTexture: this._environmentTextureCDNUrl,
  83290. cameraExposure: 0.8,
  83291. cameraContrast: 1.2,
  83292. toneMappingEnabled: true,
  83293. };
  83294. };
  83295. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  83296. /**
  83297. * Gets the root mesh created by the helper.
  83298. */
  83299. get: function () {
  83300. return this._rootMesh;
  83301. },
  83302. enumerable: true,
  83303. configurable: true
  83304. });
  83305. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  83306. /**
  83307. * Gets the skybox created by the helper.
  83308. */
  83309. get: function () {
  83310. return this._skybox;
  83311. },
  83312. enumerable: true,
  83313. configurable: true
  83314. });
  83315. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  83316. /**
  83317. * Gets the skybox texture created by the helper.
  83318. */
  83319. get: function () {
  83320. return this._skyboxTexture;
  83321. },
  83322. enumerable: true,
  83323. configurable: true
  83324. });
  83325. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  83326. /**
  83327. * Gets the skybox material created by the helper.
  83328. */
  83329. get: function () {
  83330. return this._skyboxMaterial;
  83331. },
  83332. enumerable: true,
  83333. configurable: true
  83334. });
  83335. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  83336. /**
  83337. * Gets the ground mesh created by the helper.
  83338. */
  83339. get: function () {
  83340. return this._ground;
  83341. },
  83342. enumerable: true,
  83343. configurable: true
  83344. });
  83345. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  83346. /**
  83347. * Gets the ground texture created by the helper.
  83348. */
  83349. get: function () {
  83350. return this._groundTexture;
  83351. },
  83352. enumerable: true,
  83353. configurable: true
  83354. });
  83355. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  83356. /**
  83357. * Gets the ground mirror created by the helper.
  83358. */
  83359. get: function () {
  83360. return this._groundMirror;
  83361. },
  83362. enumerable: true,
  83363. configurable: true
  83364. });
  83365. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  83366. /**
  83367. * Gets the ground mirror render list to helps pushing the meshes
  83368. * you wish in the ground reflection.
  83369. */
  83370. get: function () {
  83371. if (this._groundMirror) {
  83372. return this._groundMirror.renderList;
  83373. }
  83374. return null;
  83375. },
  83376. enumerable: true,
  83377. configurable: true
  83378. });
  83379. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  83380. /**
  83381. * Gets the ground material created by the helper.
  83382. */
  83383. get: function () {
  83384. return this._groundMaterial;
  83385. },
  83386. enumerable: true,
  83387. configurable: true
  83388. });
  83389. /**
  83390. * Updates the background according to the new options
  83391. * @param options
  83392. */
  83393. EnvironmentHelper.prototype.updateOptions = function (options) {
  83394. var newOptions = __assign({}, this._options, options);
  83395. if (this._ground && !newOptions.createGround) {
  83396. this._ground.dispose();
  83397. this._ground = null;
  83398. }
  83399. if (this._groundMaterial && !newOptions.createGround) {
  83400. this._groundMaterial.dispose();
  83401. this._groundMaterial = null;
  83402. }
  83403. if (this._groundTexture) {
  83404. if (this._options.groundTexture != newOptions.groundTexture) {
  83405. this._groundTexture.dispose();
  83406. this._groundTexture = null;
  83407. }
  83408. }
  83409. if (this._skybox && !newOptions.createSkybox) {
  83410. this._skybox.dispose();
  83411. this._skybox = null;
  83412. }
  83413. if (this._skyboxMaterial && !newOptions.createSkybox) {
  83414. this._skyboxMaterial.dispose();
  83415. this._skyboxMaterial = null;
  83416. }
  83417. if (this._skyboxTexture) {
  83418. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  83419. this._skyboxTexture.dispose();
  83420. this._skyboxTexture = null;
  83421. }
  83422. }
  83423. if (this._groundMirror && !newOptions.enableGroundMirror) {
  83424. this._groundMirror.dispose();
  83425. this._groundMirror = null;
  83426. }
  83427. if (this._scene.environmentTexture) {
  83428. if (this._options.environmentTexture != newOptions.environmentTexture) {
  83429. this._scene.environmentTexture.dispose();
  83430. }
  83431. }
  83432. this._options = newOptions;
  83433. this._setupBackground();
  83434. this._setupImageProcessing();
  83435. };
  83436. /**
  83437. * Sets the primary color of all the available elements.
  83438. * @param color
  83439. */
  83440. EnvironmentHelper.prototype.setMainColor = function (color) {
  83441. if (this.groundMaterial) {
  83442. this.groundMaterial.primaryColor = color;
  83443. }
  83444. if (this.skyboxMaterial) {
  83445. this.skyboxMaterial.primaryColor = color;
  83446. }
  83447. if (this.groundMirror) {
  83448. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  83449. }
  83450. };
  83451. /**
  83452. * Setup the image processing according to the specified options.
  83453. */
  83454. EnvironmentHelper.prototype._setupImageProcessing = function () {
  83455. if (this._options.setupImageProcessing) {
  83456. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  83457. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  83458. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  83459. this._setupEnvironmentTexture();
  83460. }
  83461. };
  83462. /**
  83463. * Setup the environment texture according to the specified options.
  83464. */
  83465. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  83466. if (this._scene.environmentTexture) {
  83467. return;
  83468. }
  83469. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  83470. this._scene.environmentTexture = this._options.environmentTexture;
  83471. return;
  83472. }
  83473. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  83474. this._scene.environmentTexture = environmentTexture;
  83475. };
  83476. /**
  83477. * Setup the background according to the specified options.
  83478. */
  83479. EnvironmentHelper.prototype._setupBackground = function () {
  83480. if (!this._rootMesh) {
  83481. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  83482. }
  83483. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  83484. var sceneSize = this._getSceneSize();
  83485. if (this._options.createGround) {
  83486. this._setupGround(sceneSize);
  83487. this._setupGroundMaterial();
  83488. this._setupGroundDiffuseTexture();
  83489. if (this._options.enableGroundMirror) {
  83490. this._setupGroundMirrorTexture(sceneSize);
  83491. }
  83492. this._setupMirrorInGroundMaterial();
  83493. }
  83494. if (this._options.createSkybox) {
  83495. this._setupSkybox(sceneSize);
  83496. this._setupSkyboxMaterial();
  83497. this._setupSkyboxReflectionTexture();
  83498. }
  83499. this._rootMesh.position.x = sceneSize.rootPosition.x;
  83500. this._rootMesh.position.z = sceneSize.rootPosition.z;
  83501. this._rootMesh.position.y = sceneSize.rootPosition.y;
  83502. };
  83503. /**
  83504. * Get the scene sizes according to the setup.
  83505. */
  83506. EnvironmentHelper.prototype._getSceneSize = function () {
  83507. var groundSize = this._options.groundSize;
  83508. var skyboxSize = this._options.skyboxSize;
  83509. var rootPosition = this._options.rootPosition;
  83510. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  83511. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  83512. }
  83513. var sceneExtends = this._scene.getWorldExtends();
  83514. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  83515. if (this._options.sizeAuto) {
  83516. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  83517. this._scene.activeCamera.upperRadiusLimit) {
  83518. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  83519. skyboxSize = groundSize;
  83520. }
  83521. var sceneDiagonalLenght = sceneDiagonal.length();
  83522. if (sceneDiagonalLenght > groundSize) {
  83523. groundSize = sceneDiagonalLenght * 2;
  83524. skyboxSize = groundSize;
  83525. }
  83526. // 10 % bigger.
  83527. groundSize *= 1.1;
  83528. skyboxSize *= 1.5;
  83529. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  83530. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  83531. }
  83532. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  83533. };
  83534. /**
  83535. * Setup the ground according to the specified options.
  83536. */
  83537. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  83538. var _this = this;
  83539. if (!this._ground) {
  83540. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  83541. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  83542. this._ground.parent = this._rootMesh;
  83543. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  83544. }
  83545. this._ground.receiveShadows = this._options.enableGroundShadow;
  83546. };
  83547. /**
  83548. * Setup the ground material according to the specified options.
  83549. */
  83550. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  83551. if (!this._groundMaterial) {
  83552. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  83553. }
  83554. this._groundMaterial.alpha = this._options.groundOpacity;
  83555. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  83556. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  83557. this._groundMaterial.primaryLevel = 1;
  83558. this._groundMaterial.primaryColor = this._options.groundColor;
  83559. this._groundMaterial.secondaryLevel = 0;
  83560. this._groundMaterial.tertiaryLevel = 0;
  83561. this._groundMaterial.useRGBColor = false;
  83562. this._groundMaterial.enableNoise = true;
  83563. if (this._ground) {
  83564. this._ground.material = this._groundMaterial;
  83565. }
  83566. };
  83567. /**
  83568. * Setup the ground diffuse texture according to the specified options.
  83569. */
  83570. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  83571. if (!this._groundMaterial) {
  83572. return;
  83573. }
  83574. if (this._groundTexture) {
  83575. return;
  83576. }
  83577. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  83578. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  83579. return;
  83580. }
  83581. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  83582. diffuseTexture.gammaSpace = false;
  83583. diffuseTexture.hasAlpha = true;
  83584. this._groundMaterial.diffuseTexture = diffuseTexture;
  83585. };
  83586. /**
  83587. * Setup the ground mirror texture according to the specified options.
  83588. */
  83589. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  83590. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83591. if (!this._groundMirror) {
  83592. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  83593. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  83594. this._groundMirror.anisotropicFilteringLevel = 1;
  83595. this._groundMirror.wrapU = wrapping;
  83596. this._groundMirror.wrapV = wrapping;
  83597. this._groundMirror.gammaSpace = false;
  83598. if (this._groundMirror.renderList) {
  83599. for (var i = 0; i < this._scene.meshes.length; i++) {
  83600. var mesh = this._scene.meshes[i];
  83601. if (mesh !== this._ground &&
  83602. mesh !== this._skybox &&
  83603. mesh !== this._rootMesh) {
  83604. this._groundMirror.renderList.push(mesh);
  83605. }
  83606. }
  83607. }
  83608. }
  83609. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  83610. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  83611. };
  83612. /**
  83613. * Setup the ground to receive the mirror texture.
  83614. */
  83615. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  83616. if (this._groundMaterial) {
  83617. this._groundMaterial.reflectionTexture = this._groundMirror;
  83618. this._groundMaterial.reflectionFresnel = true;
  83619. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  83620. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  83621. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  83622. }
  83623. };
  83624. /**
  83625. * Setup the skybox according to the specified options.
  83626. */
  83627. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  83628. var _this = this;
  83629. if (!this._skybox) {
  83630. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  83631. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  83632. }
  83633. this._skybox.parent = this._rootMesh;
  83634. };
  83635. /**
  83636. * Setup the skybox material according to the specified options.
  83637. */
  83638. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  83639. if (!this._skybox) {
  83640. return;
  83641. }
  83642. if (!this._skyboxMaterial) {
  83643. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  83644. }
  83645. this._skyboxMaterial.useRGBColor = false;
  83646. this._skyboxMaterial.primaryLevel = 1;
  83647. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  83648. this._skyboxMaterial.secondaryLevel = 0;
  83649. this._skyboxMaterial.tertiaryLevel = 0;
  83650. this._skyboxMaterial.enableNoise = true;
  83651. this._skybox.material = this._skyboxMaterial;
  83652. };
  83653. /**
  83654. * Setup the skybox reflection texture according to the specified options.
  83655. */
  83656. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  83657. if (!this._skyboxMaterial) {
  83658. return;
  83659. }
  83660. if (this._skyboxTexture) {
  83661. return;
  83662. }
  83663. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  83664. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  83665. return;
  83666. }
  83667. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  83668. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  83669. this._skyboxTexture.gammaSpace = false;
  83670. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  83671. };
  83672. /**
  83673. * Dispose all the elements created by the Helper.
  83674. */
  83675. EnvironmentHelper.prototype.dispose = function () {
  83676. if (this._groundMaterial) {
  83677. this._groundMaterial.dispose(true, true);
  83678. }
  83679. if (this._skyboxMaterial) {
  83680. this._skyboxMaterial.dispose(true, true);
  83681. }
  83682. this._rootMesh.dispose(false);
  83683. };
  83684. /**
  83685. * Default ground texture URL.
  83686. */
  83687. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  83688. /**
  83689. * Default skybox texture URL.
  83690. */
  83691. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  83692. /**
  83693. * Default environment texture URL.
  83694. */
  83695. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  83696. return EnvironmentHelper;
  83697. }());
  83698. BABYLON.EnvironmentHelper = EnvironmentHelper;
  83699. })(BABYLON || (BABYLON = {}));
  83700. //# sourceMappingURL=babylon.environmentHelper.js.map
  83701. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","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);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  83702. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  83703. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  83704. var BABYLON;
  83705. (function (BABYLON) {
  83706. var GridMaterialDefines = /** @class */ (function (_super) {
  83707. __extends(GridMaterialDefines, _super);
  83708. function GridMaterialDefines() {
  83709. var _this = _super.call(this) || this;
  83710. _this.TRANSPARENT = false;
  83711. _this.FOG = false;
  83712. _this.PREMULTIPLYALPHA = false;
  83713. _this.rebuild();
  83714. return _this;
  83715. }
  83716. return GridMaterialDefines;
  83717. }(BABYLON.MaterialDefines));
  83718. /**
  83719. * The grid materials allows you to wrap any shape with a grid.
  83720. * Colors are customizable.
  83721. */
  83722. var GridMaterial = /** @class */ (function (_super) {
  83723. __extends(GridMaterial, _super);
  83724. /**
  83725. * constructor
  83726. * @param name The name given to the material in order to identify it afterwards.
  83727. * @param scene The scene the material is used in.
  83728. */
  83729. function GridMaterial(name, scene) {
  83730. var _this = _super.call(this, name, scene) || this;
  83731. /**
  83732. * Main color of the grid (e.g. between lines)
  83733. */
  83734. _this.mainColor = BABYLON.Color3.Black();
  83735. /**
  83736. * Color of the grid lines.
  83737. */
  83738. _this.lineColor = BABYLON.Color3.Teal();
  83739. /**
  83740. * The scale of the grid compared to unit.
  83741. */
  83742. _this.gridRatio = 1.0;
  83743. /**
  83744. * Allows setting an offset for the grid lines.
  83745. */
  83746. _this.gridOffset = BABYLON.Vector3.Zero();
  83747. /**
  83748. * The frequency of thicker lines.
  83749. */
  83750. _this.majorUnitFrequency = 10;
  83751. /**
  83752. * The visibility of minor units in the grid.
  83753. */
  83754. _this.minorUnitVisibility = 0.33;
  83755. /**
  83756. * The grid opacity outside of the lines.
  83757. */
  83758. _this.opacity = 1.0;
  83759. /**
  83760. * Determine RBG output is premultiplied by alpha value.
  83761. */
  83762. _this.preMultiplyAlpha = false;
  83763. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  83764. return _this;
  83765. }
  83766. /**
  83767. * Returns wehter or not the grid requires alpha blending.
  83768. */
  83769. GridMaterial.prototype.needAlphaBlending = function () {
  83770. return this.opacity < 1.0;
  83771. };
  83772. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  83773. return this.needAlphaBlending();
  83774. };
  83775. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  83776. if (this.isFrozen) {
  83777. if (this._wasPreviouslyReady && subMesh.effect) {
  83778. return true;
  83779. }
  83780. }
  83781. if (!subMesh._materialDefines) {
  83782. subMesh._materialDefines = new GridMaterialDefines();
  83783. }
  83784. var defines = subMesh._materialDefines;
  83785. var scene = this.getScene();
  83786. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  83787. if (this._renderId === scene.getRenderId()) {
  83788. return true;
  83789. }
  83790. }
  83791. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  83792. defines.TRANSPARENT = !defines.TRANSPARENT;
  83793. defines.markAsUnprocessed();
  83794. }
  83795. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  83796. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  83797. defines.markAsUnprocessed();
  83798. }
  83799. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  83800. // Get correct effect
  83801. if (defines.isDirty) {
  83802. defines.markAsProcessed();
  83803. scene.resetCachedMaterial();
  83804. // Attributes
  83805. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83806. // Defines
  83807. var join = defines.toString();
  83808. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  83809. }
  83810. if (!subMesh.effect || !subMesh.effect.isReady()) {
  83811. return false;
  83812. }
  83813. this._renderId = scene.getRenderId();
  83814. this._wasPreviouslyReady = true;
  83815. return true;
  83816. };
  83817. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  83818. var scene = this.getScene();
  83819. var defines = subMesh._materialDefines;
  83820. if (!defines) {
  83821. return;
  83822. }
  83823. var effect = subMesh.effect;
  83824. if (!effect) {
  83825. return;
  83826. }
  83827. this._activeEffect = effect;
  83828. // Matrices
  83829. this.bindOnlyWorldMatrix(world);
  83830. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  83831. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  83832. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  83833. // Uniforms
  83834. if (this._mustRebind(scene, effect)) {
  83835. this._activeEffect.setColor3("mainColor", this.mainColor);
  83836. this._activeEffect.setColor3("lineColor", this.lineColor);
  83837. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  83838. this._gridControl.x = this.gridRatio;
  83839. this._gridControl.y = Math.round(this.majorUnitFrequency);
  83840. this._gridControl.z = this.minorUnitVisibility;
  83841. this._gridControl.w = this.opacity;
  83842. this._activeEffect.setVector4("gridControl", this._gridControl);
  83843. }
  83844. // Fog
  83845. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  83846. this._afterBind(mesh, this._activeEffect);
  83847. };
  83848. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  83849. _super.prototype.dispose.call(this, forceDisposeEffect);
  83850. };
  83851. GridMaterial.prototype.clone = function (name) {
  83852. var _this = this;
  83853. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  83854. };
  83855. GridMaterial.prototype.serialize = function () {
  83856. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83857. serializationObject.customType = "BABYLON.GridMaterial";
  83858. return serializationObject;
  83859. };
  83860. GridMaterial.prototype.getClassName = function () {
  83861. return "GridMaterial";
  83862. };
  83863. GridMaterial.Parse = function (source, scene, rootUrl) {
  83864. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  83865. };
  83866. __decorate([
  83867. BABYLON.serializeAsColor3()
  83868. ], GridMaterial.prototype, "mainColor", void 0);
  83869. __decorate([
  83870. BABYLON.serializeAsColor3()
  83871. ], GridMaterial.prototype, "lineColor", void 0);
  83872. __decorate([
  83873. BABYLON.serialize()
  83874. ], GridMaterial.prototype, "gridRatio", void 0);
  83875. __decorate([
  83876. BABYLON.serializeAsColor3()
  83877. ], GridMaterial.prototype, "gridOffset", void 0);
  83878. __decorate([
  83879. BABYLON.serialize()
  83880. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  83881. __decorate([
  83882. BABYLON.serialize()
  83883. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  83884. __decorate([
  83885. BABYLON.serialize()
  83886. ], GridMaterial.prototype, "opacity", void 0);
  83887. __decorate([
  83888. BABYLON.serialize()
  83889. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  83890. return GridMaterial;
  83891. }(BABYLON.PushMaterial));
  83892. BABYLON.GridMaterial = GridMaterial;
  83893. })(BABYLON || (BABYLON = {}));
  83894. //# sourceMappingURL=babylon.gridmaterial.js.map
  83895. 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}";
  83896. 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}";
  83897. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  83898. var BABYLON;
  83899. (function (BABYLON) {
  83900. var GLTFLoaderCoordinateSystemMode;
  83901. (function (GLTFLoaderCoordinateSystemMode) {
  83902. /**
  83903. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  83904. */
  83905. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  83906. /**
  83907. * Sets the useRightHandedSystem flag on the scene.
  83908. */
  83909. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  83910. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  83911. var GLTFLoaderAnimationStartMode;
  83912. (function (GLTFLoaderAnimationStartMode) {
  83913. /**
  83914. * No animation will start.
  83915. */
  83916. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  83917. /**
  83918. * The first animation will start.
  83919. */
  83920. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  83921. /**
  83922. * All animations will start.
  83923. */
  83924. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  83925. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  83926. var GLTFFileLoader = /** @class */ (function () {
  83927. function GLTFFileLoader() {
  83928. // #region Common options
  83929. /**
  83930. * Raised when the asset has been parsed.
  83931. * The data.json property stores the glTF JSON.
  83932. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  83933. */
  83934. this.onParsedObservable = new BABYLON.Observable();
  83935. // #endregion
  83936. // #region V2 options
  83937. /**
  83938. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  83939. */
  83940. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  83941. /**
  83942. * The animation start mode (NONE, FIRST, ALL).
  83943. */
  83944. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  83945. /**
  83946. * Set to true to compile materials before raising the success callback.
  83947. */
  83948. this.compileMaterials = false;
  83949. /**
  83950. * Set to true to also compile materials with clip planes.
  83951. */
  83952. this.useClipPlane = false;
  83953. /**
  83954. * Set to true to compile shadow generators before raising the success callback.
  83955. */
  83956. this.compileShadowGenerators = false;
  83957. /**
  83958. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  83959. */
  83960. this.onMeshLoadedObservable = new BABYLON.Observable();
  83961. /**
  83962. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  83963. */
  83964. this.onTextureLoadedObservable = new BABYLON.Observable();
  83965. /**
  83966. * Raised when the loader creates a material after parsing the glTF properties of the material.
  83967. */
  83968. this.onMaterialLoadedObservable = new BABYLON.Observable();
  83969. /**
  83970. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  83971. * For assets with LODs, raised when all of the LODs are complete.
  83972. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  83973. */
  83974. this.onCompleteObservable = new BABYLON.Observable();
  83975. /**
  83976. * Raised when the loader is disposed.
  83977. */
  83978. this.onDisposeObservable = new BABYLON.Observable();
  83979. // #endregion
  83980. this._loader = null;
  83981. this.name = "gltf";
  83982. this.extensions = {
  83983. ".gltf": { isBinary: false },
  83984. ".glb": { isBinary: true }
  83985. };
  83986. }
  83987. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  83988. set: function (callback) {
  83989. if (this._onParsedObserver) {
  83990. this.onParsedObservable.remove(this._onParsedObserver);
  83991. }
  83992. this._onParsedObserver = this.onParsedObservable.add(callback);
  83993. },
  83994. enumerable: true,
  83995. configurable: true
  83996. });
  83997. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  83998. set: function (callback) {
  83999. if (this._onMeshLoadedObserver) {
  84000. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  84001. }
  84002. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  84003. },
  84004. enumerable: true,
  84005. configurable: true
  84006. });
  84007. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  84008. set: function (callback) {
  84009. if (this._onTextureLoadedObserver) {
  84010. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  84011. }
  84012. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  84013. },
  84014. enumerable: true,
  84015. configurable: true
  84016. });
  84017. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  84018. set: function (callback) {
  84019. if (this._onMaterialLoadedObserver) {
  84020. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  84021. }
  84022. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  84023. },
  84024. enumerable: true,
  84025. configurable: true
  84026. });
  84027. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  84028. set: function (callback) {
  84029. if (this._onCompleteObserver) {
  84030. this.onCompleteObservable.remove(this._onCompleteObserver);
  84031. }
  84032. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  84033. },
  84034. enumerable: true,
  84035. configurable: true
  84036. });
  84037. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  84038. set: function (callback) {
  84039. if (this._onDisposeObserver) {
  84040. this.onDisposeObservable.remove(this._onDisposeObserver);
  84041. }
  84042. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84043. },
  84044. enumerable: true,
  84045. configurable: true
  84046. });
  84047. /**
  84048. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  84049. */
  84050. GLTFFileLoader.prototype.dispose = function () {
  84051. if (this._loader) {
  84052. this._loader.dispose();
  84053. this._loader = null;
  84054. }
  84055. this.onParsedObservable.clear();
  84056. this.onMeshLoadedObservable.clear();
  84057. this.onTextureLoadedObservable.clear();
  84058. this.onMaterialLoadedObservable.clear();
  84059. this.onCompleteObservable.clear();
  84060. this.onDisposeObservable.notifyObservers(this);
  84061. this.onDisposeObservable.clear();
  84062. };
  84063. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84064. try {
  84065. var loaderData = this._parse(data);
  84066. this._loader = this._getLoader(loaderData);
  84067. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  84068. }
  84069. catch (e) {
  84070. if (onError) {
  84071. onError(e.message, e);
  84072. }
  84073. else {
  84074. BABYLON.Tools.Error(e.message);
  84075. }
  84076. }
  84077. };
  84078. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84079. try {
  84080. var loaderData = this._parse(data);
  84081. this._loader = this._getLoader(loaderData);
  84082. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  84083. }
  84084. catch (e) {
  84085. if (onError) {
  84086. onError(e.message, e);
  84087. }
  84088. else {
  84089. BABYLON.Tools.Error(e.message);
  84090. }
  84091. }
  84092. };
  84093. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84094. try {
  84095. var loaderData = this._parse(data);
  84096. this._loader = this._getLoader(loaderData);
  84097. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  84098. var container = new BABYLON.AssetContainer(scene);
  84099. Array.prototype.push.apply(container.meshes, meshes);
  84100. Array.prototype.push.apply(container.particleSystems, particleSystems);
  84101. Array.prototype.push.apply(container.skeletons, skeletons);
  84102. container.removeAllFromScene();
  84103. onSuccess(container);
  84104. }, onProgress, onError);
  84105. }
  84106. catch (e) {
  84107. if (onError) {
  84108. onError(e.message, e);
  84109. }
  84110. else {
  84111. BABYLON.Tools.Error(e.message);
  84112. }
  84113. }
  84114. };
  84115. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  84116. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  84117. };
  84118. GLTFFileLoader.prototype.createPlugin = function () {
  84119. return new GLTFFileLoader();
  84120. };
  84121. GLTFFileLoader.prototype._parse = function (data) {
  84122. var parsedData;
  84123. if (data instanceof ArrayBuffer) {
  84124. parsedData = GLTFFileLoader._parseBinary(data);
  84125. }
  84126. else {
  84127. parsedData = {
  84128. json: JSON.parse(data),
  84129. bin: null
  84130. };
  84131. }
  84132. this.onParsedObservable.notifyObservers(parsedData);
  84133. return parsedData;
  84134. };
  84135. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  84136. var _this = this;
  84137. var loaderVersion = { major: 2, minor: 0 };
  84138. var asset = loaderData.json.asset || {};
  84139. var version = GLTFFileLoader._parseVersion(asset.version);
  84140. if (!version) {
  84141. throw new Error("Invalid version: " + asset.version);
  84142. }
  84143. if (asset.minVersion !== undefined) {
  84144. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  84145. if (!minVersion) {
  84146. throw new Error("Invalid minimum version: " + asset.minVersion);
  84147. }
  84148. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  84149. throw new Error("Incompatible minimum version: " + asset.minVersion);
  84150. }
  84151. }
  84152. var createLoaders = {
  84153. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  84154. 2: GLTFFileLoader.CreateGLTFLoaderV2
  84155. };
  84156. var createLoader = createLoaders[version.major];
  84157. if (!createLoader) {
  84158. throw new Error("Unsupported version: " + asset.version);
  84159. }
  84160. var loader = createLoader();
  84161. loader.coordinateSystemMode = this.coordinateSystemMode;
  84162. loader.animationStartMode = this.animationStartMode;
  84163. loader.compileMaterials = this.compileMaterials;
  84164. loader.useClipPlane = this.useClipPlane;
  84165. loader.compileShadowGenerators = this.compileShadowGenerators;
  84166. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  84167. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  84168. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  84169. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  84170. return loader;
  84171. };
  84172. GLTFFileLoader._parseBinary = function (data) {
  84173. var Binary = {
  84174. Magic: 0x46546C67
  84175. };
  84176. var binaryReader = new BinaryReader(data);
  84177. var magic = binaryReader.readUint32();
  84178. if (magic !== Binary.Magic) {
  84179. throw new Error("Unexpected magic: " + magic);
  84180. }
  84181. var version = binaryReader.readUint32();
  84182. switch (version) {
  84183. case 1: return GLTFFileLoader._parseV1(binaryReader);
  84184. case 2: return GLTFFileLoader._parseV2(binaryReader);
  84185. }
  84186. throw new Error("Unsupported version: " + version);
  84187. };
  84188. GLTFFileLoader._parseV1 = function (binaryReader) {
  84189. var ContentFormat = {
  84190. JSON: 0
  84191. };
  84192. var length = binaryReader.readUint32();
  84193. if (length != binaryReader.getLength()) {
  84194. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  84195. }
  84196. var contentLength = binaryReader.readUint32();
  84197. var contentFormat = binaryReader.readUint32();
  84198. var content;
  84199. switch (contentFormat) {
  84200. case ContentFormat.JSON: {
  84201. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  84202. break;
  84203. }
  84204. default: {
  84205. throw new Error("Unexpected content format: " + contentFormat);
  84206. }
  84207. }
  84208. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  84209. var body = binaryReader.readUint8Array(bytesRemaining);
  84210. return {
  84211. json: content,
  84212. bin: body
  84213. };
  84214. };
  84215. GLTFFileLoader._parseV2 = function (binaryReader) {
  84216. var ChunkFormat = {
  84217. JSON: 0x4E4F534A,
  84218. BIN: 0x004E4942
  84219. };
  84220. var length = binaryReader.readUint32();
  84221. if (length !== binaryReader.getLength()) {
  84222. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  84223. }
  84224. // JSON chunk
  84225. var chunkLength = binaryReader.readUint32();
  84226. var chunkFormat = binaryReader.readUint32();
  84227. if (chunkFormat !== ChunkFormat.JSON) {
  84228. throw new Error("First chunk format is not JSON");
  84229. }
  84230. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  84231. // Look for BIN chunk
  84232. var bin = null;
  84233. while (binaryReader.getPosition() < binaryReader.getLength()) {
  84234. var chunkLength_1 = binaryReader.readUint32();
  84235. var chunkFormat_1 = binaryReader.readUint32();
  84236. switch (chunkFormat_1) {
  84237. case ChunkFormat.JSON: {
  84238. throw new Error("Unexpected JSON chunk");
  84239. }
  84240. case ChunkFormat.BIN: {
  84241. bin = binaryReader.readUint8Array(chunkLength_1);
  84242. break;
  84243. }
  84244. default: {
  84245. // ignore unrecognized chunkFormat
  84246. binaryReader.skipBytes(chunkLength_1);
  84247. break;
  84248. }
  84249. }
  84250. }
  84251. return {
  84252. json: json,
  84253. bin: bin
  84254. };
  84255. };
  84256. GLTFFileLoader._parseVersion = function (version) {
  84257. if (version === "1.0" || version === "1.0.1") {
  84258. return {
  84259. major: 1,
  84260. minor: 0
  84261. };
  84262. }
  84263. var match = (version + "").match(/^(\d+)\.(\d+)/);
  84264. if (!match) {
  84265. return null;
  84266. }
  84267. return {
  84268. major: parseInt(match[1]),
  84269. minor: parseInt(match[2])
  84270. };
  84271. };
  84272. GLTFFileLoader._compareVersion = function (a, b) {
  84273. if (a.major > b.major)
  84274. return 1;
  84275. if (a.major < b.major)
  84276. return -1;
  84277. if (a.minor > b.minor)
  84278. return 1;
  84279. if (a.minor < b.minor)
  84280. return -1;
  84281. return 0;
  84282. };
  84283. GLTFFileLoader._decodeBufferToText = function (buffer) {
  84284. var result = "";
  84285. var length = buffer.byteLength;
  84286. for (var i = 0; i < length; i++) {
  84287. result += String.fromCharCode(buffer[i]);
  84288. }
  84289. return result;
  84290. };
  84291. // #endregion
  84292. // #region V1 options
  84293. GLTFFileLoader.IncrementalLoading = true;
  84294. GLTFFileLoader.HomogeneousCoordinates = false;
  84295. return GLTFFileLoader;
  84296. }());
  84297. BABYLON.GLTFFileLoader = GLTFFileLoader;
  84298. var BinaryReader = /** @class */ (function () {
  84299. function BinaryReader(arrayBuffer) {
  84300. this._arrayBuffer = arrayBuffer;
  84301. this._dataView = new DataView(arrayBuffer);
  84302. this._byteOffset = 0;
  84303. }
  84304. BinaryReader.prototype.getPosition = function () {
  84305. return this._byteOffset;
  84306. };
  84307. BinaryReader.prototype.getLength = function () {
  84308. return this._arrayBuffer.byteLength;
  84309. };
  84310. BinaryReader.prototype.readUint32 = function () {
  84311. var value = this._dataView.getUint32(this._byteOffset, true);
  84312. this._byteOffset += 4;
  84313. return value;
  84314. };
  84315. BinaryReader.prototype.readUint8Array = function (length) {
  84316. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  84317. this._byteOffset += length;
  84318. return value;
  84319. };
  84320. BinaryReader.prototype.skipBytes = function (length) {
  84321. this._byteOffset += length;
  84322. };
  84323. return BinaryReader;
  84324. }());
  84325. if (BABYLON.SceneLoader) {
  84326. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  84327. }
  84328. })(BABYLON || (BABYLON = {}));
  84329. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  84330. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84331. var BABYLON;
  84332. (function (BABYLON) {
  84333. var GLTF1;
  84334. (function (GLTF1) {
  84335. /**
  84336. * Enums
  84337. */
  84338. var EComponentType;
  84339. (function (EComponentType) {
  84340. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  84341. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84342. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  84343. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84344. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  84345. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  84346. var EShaderType;
  84347. (function (EShaderType) {
  84348. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  84349. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  84350. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  84351. var EParameterType;
  84352. (function (EParameterType) {
  84353. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  84354. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84355. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  84356. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84357. EParameterType[EParameterType["INT"] = 5124] = "INT";
  84358. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  84359. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  84360. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  84361. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  84362. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  84363. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  84364. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  84365. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  84366. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  84367. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  84368. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  84369. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  84370. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  84371. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  84372. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  84373. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  84374. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  84375. var ETextureWrapMode;
  84376. (function (ETextureWrapMode) {
  84377. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  84378. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  84379. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  84380. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  84381. var ETextureFilterType;
  84382. (function (ETextureFilterType) {
  84383. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  84384. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  84385. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  84386. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  84387. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  84388. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  84389. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  84390. var ETextureFormat;
  84391. (function (ETextureFormat) {
  84392. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  84393. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  84394. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  84395. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  84396. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  84397. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  84398. var ECullingType;
  84399. (function (ECullingType) {
  84400. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  84401. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  84402. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  84403. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  84404. var EBlendingFunction;
  84405. (function (EBlendingFunction) {
  84406. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  84407. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  84408. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  84409. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  84410. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  84411. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  84412. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  84413. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  84414. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  84415. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  84416. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  84417. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  84418. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  84419. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  84420. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  84421. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  84422. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84423. })(BABYLON || (BABYLON = {}));
  84424. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  84425. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84426. var BABYLON;
  84427. (function (BABYLON) {
  84428. var GLTF1;
  84429. (function (GLTF1) {
  84430. /**
  84431. * Tokenizer. Used for shaders compatibility
  84432. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  84433. */
  84434. var ETokenType;
  84435. (function (ETokenType) {
  84436. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  84437. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  84438. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  84439. })(ETokenType || (ETokenType = {}));
  84440. var Tokenizer = /** @class */ (function () {
  84441. function Tokenizer(toParse) {
  84442. this._pos = 0;
  84443. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  84444. this._toParse = toParse;
  84445. this._maxPos = toParse.length;
  84446. }
  84447. Tokenizer.prototype.getNextToken = function () {
  84448. if (this.isEnd())
  84449. return ETokenType.END_OF_INPUT;
  84450. this.currentString = this.read();
  84451. this.currentToken = ETokenType.UNKNOWN;
  84452. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  84453. this.currentToken = ETokenType.IDENTIFIER;
  84454. this.currentIdentifier = this.currentString;
  84455. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  84456. this.currentIdentifier += this.currentString;
  84457. this.forward();
  84458. }
  84459. }
  84460. return this.currentToken;
  84461. };
  84462. Tokenizer.prototype.peek = function () {
  84463. return this._toParse[this._pos];
  84464. };
  84465. Tokenizer.prototype.read = function () {
  84466. return this._toParse[this._pos++];
  84467. };
  84468. Tokenizer.prototype.forward = function () {
  84469. this._pos++;
  84470. };
  84471. Tokenizer.prototype.isEnd = function () {
  84472. return this._pos >= this._maxPos;
  84473. };
  84474. return Tokenizer;
  84475. }());
  84476. /**
  84477. * Values
  84478. */
  84479. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  84480. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  84481. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  84482. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  84483. /**
  84484. * Parse
  84485. */
  84486. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  84487. for (var buf in parsedBuffers) {
  84488. var parsedBuffer = parsedBuffers[buf];
  84489. gltfRuntime.buffers[buf] = parsedBuffer;
  84490. gltfRuntime.buffersCount++;
  84491. }
  84492. };
  84493. var parseShaders = function (parsedShaders, gltfRuntime) {
  84494. for (var sha in parsedShaders) {
  84495. var parsedShader = parsedShaders[sha];
  84496. gltfRuntime.shaders[sha] = parsedShader;
  84497. gltfRuntime.shaderscount++;
  84498. }
  84499. };
  84500. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  84501. for (var object in parsedObjects) {
  84502. var parsedObject = parsedObjects[object];
  84503. gltfRuntime[runtimeProperty][object] = parsedObject;
  84504. }
  84505. };
  84506. /**
  84507. * Utils
  84508. */
  84509. var normalizeUVs = function (buffer) {
  84510. if (!buffer) {
  84511. return;
  84512. }
  84513. for (var i = 0; i < buffer.length / 2; i++) {
  84514. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  84515. }
  84516. };
  84517. var getAttribute = function (attributeParameter) {
  84518. if (attributeParameter.semantic === "NORMAL") {
  84519. return "normal";
  84520. }
  84521. else if (attributeParameter.semantic === "POSITION") {
  84522. return "position";
  84523. }
  84524. else if (attributeParameter.semantic === "JOINT") {
  84525. return "matricesIndices";
  84526. }
  84527. else if (attributeParameter.semantic === "WEIGHT") {
  84528. return "matricesWeights";
  84529. }
  84530. else if (attributeParameter.semantic === "COLOR") {
  84531. return "color";
  84532. }
  84533. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  84534. var channel = Number(attributeParameter.semantic.split("_")[1]);
  84535. return "uv" + (channel === 0 ? "" : channel + 1);
  84536. }
  84537. return null;
  84538. };
  84539. /**
  84540. * Loads and creates animations
  84541. */
  84542. var loadAnimations = function (gltfRuntime) {
  84543. for (var anim in gltfRuntime.animations) {
  84544. var animation = gltfRuntime.animations[anim];
  84545. if (!animation.channels || !animation.samplers) {
  84546. continue;
  84547. }
  84548. var lastAnimation = null;
  84549. for (var i = 0; i < animation.channels.length; i++) {
  84550. // Get parameters and load buffers
  84551. var channel = animation.channels[i];
  84552. var sampler = animation.samplers[channel.sampler];
  84553. if (!sampler) {
  84554. continue;
  84555. }
  84556. var inputData = null;
  84557. var outputData = null;
  84558. if (animation.parameters) {
  84559. inputData = animation.parameters[sampler.input];
  84560. outputData = animation.parameters[sampler.output];
  84561. }
  84562. else {
  84563. inputData = sampler.input;
  84564. outputData = sampler.output;
  84565. }
  84566. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  84567. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  84568. var targetID = channel.target.id;
  84569. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  84570. if (targetNode === null) {
  84571. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  84572. }
  84573. if (targetNode === null) {
  84574. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  84575. continue;
  84576. }
  84577. var isBone = targetNode instanceof BABYLON.Bone;
  84578. // Get target path (position, rotation or scaling)
  84579. var targetPath = channel.target.path;
  84580. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  84581. if (targetPathIndex !== -1) {
  84582. targetPath = babylonAnimationPaths[targetPathIndex];
  84583. }
  84584. // Determine animation type
  84585. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  84586. if (!isBone) {
  84587. if (targetPath === "rotationQuaternion") {
  84588. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  84589. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  84590. }
  84591. else {
  84592. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  84593. }
  84594. }
  84595. // Create animation and key frames
  84596. var babylonAnimation = null;
  84597. var keys = [];
  84598. var arrayOffset = 0;
  84599. var modifyKey = false;
  84600. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  84601. babylonAnimation = lastAnimation;
  84602. modifyKey = true;
  84603. }
  84604. if (!modifyKey) {
  84605. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  84606. }
  84607. // For each frame
  84608. for (var j = 0; j < bufferInput.length; j++) {
  84609. var value = null;
  84610. if (targetPath === "rotationQuaternion") {
  84611. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  84612. arrayOffset += 4;
  84613. }
  84614. else {
  84615. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  84616. arrayOffset += 3;
  84617. }
  84618. if (isBone) {
  84619. var bone = targetNode;
  84620. var translation = BABYLON.Vector3.Zero();
  84621. var rotationQuaternion = new BABYLON.Quaternion();
  84622. var scaling = BABYLON.Vector3.Zero();
  84623. // Warning on decompose
  84624. var mat = bone.getBaseMatrix();
  84625. if (modifyKey && lastAnimation) {
  84626. mat = lastAnimation.getKeys()[j].value;
  84627. }
  84628. mat.decompose(scaling, rotationQuaternion, translation);
  84629. if (targetPath === "position") {
  84630. translation = value;
  84631. }
  84632. else if (targetPath === "rotationQuaternion") {
  84633. rotationQuaternion = value;
  84634. }
  84635. else {
  84636. scaling = value;
  84637. }
  84638. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  84639. }
  84640. if (!modifyKey) {
  84641. keys.push({
  84642. frame: bufferInput[j],
  84643. value: value
  84644. });
  84645. }
  84646. else if (lastAnimation) {
  84647. lastAnimation.getKeys()[j].value = value;
  84648. }
  84649. }
  84650. // Finish
  84651. if (!modifyKey && babylonAnimation) {
  84652. babylonAnimation.setKeys(keys);
  84653. targetNode.animations.push(babylonAnimation);
  84654. }
  84655. lastAnimation = babylonAnimation;
  84656. gltfRuntime.scene.stopAnimation(targetNode);
  84657. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  84658. }
  84659. }
  84660. };
  84661. /**
  84662. * Returns the bones transformation matrix
  84663. */
  84664. var configureBoneTransformation = function (node) {
  84665. var mat = null;
  84666. if (node.translation || node.rotation || node.scale) {
  84667. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  84668. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  84669. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  84670. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  84671. }
  84672. else {
  84673. mat = BABYLON.Matrix.FromArray(node.matrix);
  84674. }
  84675. return mat;
  84676. };
  84677. /**
  84678. * Returns the parent bone
  84679. */
  84680. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  84681. // Try to find
  84682. for (var i = 0; i < newSkeleton.bones.length; i++) {
  84683. if (newSkeleton.bones[i].name === jointName) {
  84684. return newSkeleton.bones[i];
  84685. }
  84686. }
  84687. // Not found, search in gltf nodes
  84688. var nodes = gltfRuntime.nodes;
  84689. for (var nde in nodes) {
  84690. var node = nodes[nde];
  84691. if (!node.jointName) {
  84692. continue;
  84693. }
  84694. var children = node.children;
  84695. for (var i = 0; i < children.length; i++) {
  84696. var child = gltfRuntime.nodes[children[i]];
  84697. if (!child.jointName) {
  84698. continue;
  84699. }
  84700. if (child.jointName === jointName) {
  84701. var mat = configureBoneTransformation(node);
  84702. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  84703. bone.id = nde;
  84704. return bone;
  84705. }
  84706. }
  84707. }
  84708. return null;
  84709. };
  84710. /**
  84711. * Returns the appropriate root node
  84712. */
  84713. var getNodeToRoot = function (nodesToRoot, id) {
  84714. for (var i = 0; i < nodesToRoot.length; i++) {
  84715. var nodeToRoot = nodesToRoot[i];
  84716. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  84717. var child = nodeToRoot.node.children[j];
  84718. if (child === id) {
  84719. return nodeToRoot.bone;
  84720. }
  84721. }
  84722. }
  84723. return null;
  84724. };
  84725. /**
  84726. * Returns the node with the joint name
  84727. */
  84728. var getJointNode = function (gltfRuntime, jointName) {
  84729. var nodes = gltfRuntime.nodes;
  84730. var node = nodes[jointName];
  84731. if (node) {
  84732. return {
  84733. node: node,
  84734. id: jointName
  84735. };
  84736. }
  84737. for (var nde in nodes) {
  84738. node = nodes[nde];
  84739. if (node.jointName === jointName) {
  84740. return {
  84741. node: node,
  84742. id: nde
  84743. };
  84744. }
  84745. }
  84746. return null;
  84747. };
  84748. /**
  84749. * Checks if a nodes is in joints
  84750. */
  84751. var nodeIsInJoints = function (skins, id) {
  84752. for (var i = 0; i < skins.jointNames.length; i++) {
  84753. if (skins.jointNames[i] === id) {
  84754. return true;
  84755. }
  84756. }
  84757. return false;
  84758. };
  84759. /**
  84760. * Fills the nodes to root for bones and builds hierarchy
  84761. */
  84762. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  84763. // Creates nodes for root
  84764. for (var nde in gltfRuntime.nodes) {
  84765. var node = gltfRuntime.nodes[nde];
  84766. var id = nde;
  84767. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  84768. continue;
  84769. }
  84770. // Create node to root bone
  84771. var mat = configureBoneTransformation(node);
  84772. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  84773. bone.id = id;
  84774. nodesToRoot.push({ bone: bone, node: node, id: id });
  84775. }
  84776. // Parenting
  84777. for (var i = 0; i < nodesToRoot.length; i++) {
  84778. var nodeToRoot = nodesToRoot[i];
  84779. var children = nodeToRoot.node.children;
  84780. for (var j = 0; j < children.length; j++) {
  84781. var child = null;
  84782. for (var k = 0; k < nodesToRoot.length; k++) {
  84783. if (nodesToRoot[k].id === children[j]) {
  84784. child = nodesToRoot[k];
  84785. break;
  84786. }
  84787. }
  84788. if (child) {
  84789. child.bone._parent = nodeToRoot.bone;
  84790. nodeToRoot.bone.children.push(child.bone);
  84791. }
  84792. }
  84793. }
  84794. };
  84795. /**
  84796. * Imports a skeleton
  84797. */
  84798. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  84799. if (!newSkeleton) {
  84800. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  84801. }
  84802. if (!skins.babylonSkeleton) {
  84803. return newSkeleton;
  84804. }
  84805. // Find the root bones
  84806. var nodesToRoot = [];
  84807. var nodesToRootToAdd = [];
  84808. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  84809. newSkeleton.bones = [];
  84810. // Joints
  84811. for (var i = 0; i < skins.jointNames.length; i++) {
  84812. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  84813. if (!jointNode) {
  84814. continue;
  84815. }
  84816. var node = jointNode.node;
  84817. if (!node) {
  84818. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  84819. continue;
  84820. }
  84821. var id = jointNode.id;
  84822. // Optimize, if the bone already exists...
  84823. var existingBone = gltfRuntime.scene.getBoneByID(id);
  84824. if (existingBone) {
  84825. newSkeleton.bones.push(existingBone);
  84826. continue;
  84827. }
  84828. // Search for parent bone
  84829. var foundBone = false;
  84830. var parentBone = null;
  84831. for (var j = 0; j < i; j++) {
  84832. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  84833. if (!jointNode_1) {
  84834. continue;
  84835. }
  84836. var joint = jointNode_1.node;
  84837. if (!joint) {
  84838. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  84839. continue;
  84840. }
  84841. var children = joint.children;
  84842. if (!children) {
  84843. continue;
  84844. }
  84845. foundBone = false;
  84846. for (var k = 0; k < children.length; k++) {
  84847. if (children[k] === id) {
  84848. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  84849. foundBone = true;
  84850. break;
  84851. }
  84852. }
  84853. if (foundBone) {
  84854. break;
  84855. }
  84856. }
  84857. // Create bone
  84858. var mat = configureBoneTransformation(node);
  84859. if (!parentBone && nodesToRoot.length > 0) {
  84860. parentBone = getNodeToRoot(nodesToRoot, id);
  84861. if (parentBone) {
  84862. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  84863. nodesToRootToAdd.push(parentBone);
  84864. }
  84865. }
  84866. }
  84867. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  84868. bone.id = id;
  84869. }
  84870. // Polish
  84871. var bones = newSkeleton.bones;
  84872. newSkeleton.bones = [];
  84873. for (var i = 0; i < skins.jointNames.length; i++) {
  84874. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  84875. if (!jointNode) {
  84876. continue;
  84877. }
  84878. for (var j = 0; j < bones.length; j++) {
  84879. if (bones[j].id === jointNode.id) {
  84880. newSkeleton.bones.push(bones[j]);
  84881. break;
  84882. }
  84883. }
  84884. }
  84885. newSkeleton.prepare();
  84886. // Finish
  84887. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  84888. newSkeleton.bones.push(nodesToRootToAdd[i]);
  84889. }
  84890. return newSkeleton;
  84891. };
  84892. /**
  84893. * Imports a mesh and its geometries
  84894. */
  84895. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  84896. if (!newMesh) {
  84897. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  84898. newMesh.id = id;
  84899. }
  84900. if (!node.babylonNode) {
  84901. return newMesh;
  84902. }
  84903. var subMaterials = [];
  84904. var vertexData = new BABYLON.VertexData();
  84905. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  84906. var verticesStarts = new Array();
  84907. var verticesCounts = new Array();
  84908. var indexStarts = new Array();
  84909. var indexCounts = new Array();
  84910. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  84911. var meshID = meshes[meshIndex];
  84912. var mesh = gltfRuntime.meshes[meshID];
  84913. if (!mesh) {
  84914. continue;
  84915. }
  84916. // Positions, normals and UVs
  84917. for (var i = 0; i < mesh.primitives.length; i++) {
  84918. // Temporary vertex data
  84919. var tempVertexData = new BABYLON.VertexData();
  84920. var primitive = mesh.primitives[i];
  84921. if (primitive.mode !== 4) {
  84922. // continue;
  84923. }
  84924. var attributes = primitive.attributes;
  84925. var accessor = null;
  84926. var buffer = null;
  84927. // Set positions, normal and uvs
  84928. for (var semantic in attributes) {
  84929. // Link accessor and buffer view
  84930. accessor = gltfRuntime.accessors[attributes[semantic]];
  84931. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  84932. if (semantic === "NORMAL") {
  84933. tempVertexData.normals = new Float32Array(buffer.length);
  84934. tempVertexData.normals.set(buffer);
  84935. }
  84936. else if (semantic === "POSITION") {
  84937. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  84938. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  84939. for (var j = 0; j < buffer.length; j += 4) {
  84940. tempVertexData.positions[j] = buffer[j];
  84941. tempVertexData.positions[j + 1] = buffer[j + 1];
  84942. tempVertexData.positions[j + 2] = buffer[j + 2];
  84943. }
  84944. }
  84945. else {
  84946. tempVertexData.positions = new Float32Array(buffer.length);
  84947. tempVertexData.positions.set(buffer);
  84948. }
  84949. verticesCounts.push(tempVertexData.positions.length);
  84950. }
  84951. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  84952. var channel = Number(semantic.split("_")[1]);
  84953. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  84954. var uvs = new Float32Array(buffer.length);
  84955. uvs.set(buffer);
  84956. normalizeUVs(uvs);
  84957. tempVertexData.set(uvs, uvKind);
  84958. }
  84959. else if (semantic === "JOINT") {
  84960. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  84961. tempVertexData.matricesIndices.set(buffer);
  84962. }
  84963. else if (semantic === "WEIGHT") {
  84964. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  84965. tempVertexData.matricesWeights.set(buffer);
  84966. }
  84967. else if (semantic === "COLOR") {
  84968. tempVertexData.colors = new Float32Array(buffer.length);
  84969. tempVertexData.colors.set(buffer);
  84970. }
  84971. }
  84972. // Indices
  84973. accessor = gltfRuntime.accessors[primitive.indices];
  84974. if (accessor) {
  84975. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  84976. tempVertexData.indices = new Int32Array(buffer.length);
  84977. tempVertexData.indices.set(buffer);
  84978. indexCounts.push(tempVertexData.indices.length);
  84979. }
  84980. else {
  84981. // Set indices on the fly
  84982. var indices = [];
  84983. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  84984. indices.push(j);
  84985. }
  84986. tempVertexData.indices = new Int32Array(indices);
  84987. indexCounts.push(tempVertexData.indices.length);
  84988. }
  84989. vertexData.merge(tempVertexData);
  84990. // Sub material
  84991. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  84992. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  84993. // Update vertices start and index start
  84994. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  84995. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  84996. }
  84997. }
  84998. var material;
  84999. if (subMaterials.length > 1) {
  85000. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  85001. material.subMaterials = subMaterials;
  85002. }
  85003. else {
  85004. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  85005. }
  85006. if (subMaterials.length === 1) {
  85007. material = subMaterials[0];
  85008. }
  85009. if (!newMesh.material) {
  85010. newMesh.material = material;
  85011. }
  85012. // Apply geometry
  85013. geometry.setAllVerticesData(vertexData, false);
  85014. newMesh.computeWorldMatrix(true);
  85015. // Apply submeshes
  85016. newMesh.subMeshes = [];
  85017. var index = 0;
  85018. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  85019. var meshID = meshes[meshIndex];
  85020. var mesh = gltfRuntime.meshes[meshID];
  85021. if (!mesh) {
  85022. continue;
  85023. }
  85024. for (var i = 0; i < mesh.primitives.length; i++) {
  85025. if (mesh.primitives[i].mode !== 4) {
  85026. //continue;
  85027. }
  85028. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  85029. index++;
  85030. }
  85031. }
  85032. // Finish
  85033. return newMesh;
  85034. };
  85035. /**
  85036. * Configure node transformation from position, rotation and scaling
  85037. */
  85038. var configureNode = function (newNode, position, rotation, scaling) {
  85039. if (newNode.position) {
  85040. newNode.position = position;
  85041. }
  85042. if (newNode.rotationQuaternion || newNode.rotation) {
  85043. newNode.rotationQuaternion = rotation;
  85044. }
  85045. if (newNode.scaling) {
  85046. newNode.scaling = scaling;
  85047. }
  85048. };
  85049. /**
  85050. * Configures node from transformation matrix
  85051. */
  85052. var configureNodeFromMatrix = function (newNode, node, parent) {
  85053. if (node.matrix) {
  85054. var position = new BABYLON.Vector3(0, 0, 0);
  85055. var rotation = new BABYLON.Quaternion();
  85056. var scaling = new BABYLON.Vector3(0, 0, 0);
  85057. var mat = BABYLON.Matrix.FromArray(node.matrix);
  85058. mat.decompose(scaling, rotation, position);
  85059. configureNode(newNode, position, rotation, scaling);
  85060. }
  85061. else if (node.translation && node.rotation && node.scale) {
  85062. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  85063. }
  85064. newNode.computeWorldMatrix(true);
  85065. };
  85066. /**
  85067. * Imports a node
  85068. */
  85069. var importNode = function (gltfRuntime, node, id, parent) {
  85070. var lastNode = null;
  85071. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  85072. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  85073. return null;
  85074. }
  85075. }
  85076. // Meshes
  85077. if (node.skin) {
  85078. if (node.meshes) {
  85079. var skin = gltfRuntime.skins[node.skin];
  85080. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  85081. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  85082. if (newMesh.skeleton === null) {
  85083. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  85084. if (!skin.babylonSkeleton) {
  85085. skin.babylonSkeleton = newMesh.skeleton;
  85086. }
  85087. }
  85088. lastNode = newMesh;
  85089. }
  85090. }
  85091. else if (node.meshes) {
  85092. /**
  85093. * Improve meshes property
  85094. */
  85095. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  85096. lastNode = newMesh;
  85097. }
  85098. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  85099. var light = gltfRuntime.lights[node.light];
  85100. if (light) {
  85101. if (light.type === "ambient") {
  85102. var ambienLight = light[light.type];
  85103. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85104. hemiLight.name = node.name || "";
  85105. if (ambienLight.color) {
  85106. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  85107. }
  85108. lastNode = hemiLight;
  85109. }
  85110. else if (light.type === "directional") {
  85111. var directionalLight = light[light.type];
  85112. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85113. dirLight.name = node.name || "";
  85114. if (directionalLight.color) {
  85115. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  85116. }
  85117. lastNode = dirLight;
  85118. }
  85119. else if (light.type === "point") {
  85120. var pointLight = light[light.type];
  85121. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85122. ptLight.name = node.name || "";
  85123. if (pointLight.color) {
  85124. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  85125. }
  85126. lastNode = ptLight;
  85127. }
  85128. else if (light.type === "spot") {
  85129. var spotLight = light[light.type];
  85130. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  85131. spLight.name = node.name || "";
  85132. if (spotLight.color) {
  85133. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  85134. }
  85135. if (spotLight.fallOfAngle) {
  85136. spLight.angle = spotLight.fallOfAngle;
  85137. }
  85138. if (spotLight.fallOffExponent) {
  85139. spLight.exponent = spotLight.fallOffExponent;
  85140. }
  85141. lastNode = spLight;
  85142. }
  85143. }
  85144. }
  85145. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  85146. var camera = gltfRuntime.cameras[node.camera];
  85147. if (camera) {
  85148. if (camera.type === "orthographic") {
  85149. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85150. orthoCamera.name = node.name || "";
  85151. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  85152. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  85153. lastNode = orthoCamera;
  85154. }
  85155. else if (camera.type === "perspective") {
  85156. var perspectiveCamera = camera[camera.type];
  85157. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85158. persCamera.name = node.name || "";
  85159. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  85160. if (!perspectiveCamera.aspectRatio) {
  85161. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  85162. }
  85163. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  85164. persCamera.maxZ = perspectiveCamera.zfar;
  85165. persCamera.minZ = perspectiveCamera.znear;
  85166. }
  85167. lastNode = persCamera;
  85168. }
  85169. }
  85170. }
  85171. // Empty node
  85172. if (!node.jointName) {
  85173. if (node.babylonNode) {
  85174. return node.babylonNode;
  85175. }
  85176. else if (lastNode === null) {
  85177. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  85178. node.babylonNode = dummy;
  85179. lastNode = dummy;
  85180. }
  85181. }
  85182. if (lastNode !== null) {
  85183. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  85184. configureNodeFromMatrix(lastNode, node, parent);
  85185. }
  85186. else {
  85187. var translation = node.translation || [0, 0, 0];
  85188. var rotation = node.rotation || [0, 0, 0, 1];
  85189. var scale = node.scale || [1, 1, 1];
  85190. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  85191. }
  85192. lastNode.updateCache(true);
  85193. node.babylonNode = lastNode;
  85194. }
  85195. return lastNode;
  85196. };
  85197. /**
  85198. * Traverses nodes and creates them
  85199. */
  85200. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  85201. if (meshIncluded === void 0) { meshIncluded = false; }
  85202. var node = gltfRuntime.nodes[id];
  85203. var newNode = null;
  85204. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  85205. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  85206. meshIncluded = true;
  85207. }
  85208. else {
  85209. meshIncluded = false;
  85210. }
  85211. }
  85212. else {
  85213. meshIncluded = true;
  85214. }
  85215. if (!node.jointName && meshIncluded) {
  85216. newNode = importNode(gltfRuntime, node, id, parent);
  85217. if (newNode !== null) {
  85218. newNode.id = id;
  85219. newNode.parent = parent;
  85220. }
  85221. }
  85222. if (node.children) {
  85223. for (var i = 0; i < node.children.length; i++) {
  85224. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  85225. }
  85226. }
  85227. };
  85228. /**
  85229. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  85230. */
  85231. var postLoad = function (gltfRuntime) {
  85232. // Nodes
  85233. var currentScene = gltfRuntime.currentScene;
  85234. if (currentScene) {
  85235. for (var i = 0; i < currentScene.nodes.length; i++) {
  85236. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85237. }
  85238. }
  85239. else {
  85240. for (var thing in gltfRuntime.scenes) {
  85241. currentScene = gltfRuntime.scenes[thing];
  85242. for (var i = 0; i < currentScene.nodes.length; i++) {
  85243. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85244. }
  85245. }
  85246. }
  85247. // Set animations
  85248. loadAnimations(gltfRuntime);
  85249. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  85250. var skeleton = gltfRuntime.scene.skeletons[i];
  85251. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  85252. }
  85253. };
  85254. /**
  85255. * onBind shaderrs callback to set uniforms and matrices
  85256. */
  85257. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  85258. var materialValues = material.values || technique.parameters;
  85259. for (var unif in unTreatedUniforms) {
  85260. var uniform = unTreatedUniforms[unif];
  85261. var type = uniform.type;
  85262. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  85263. if (uniform.semantic && !uniform.source && !uniform.node) {
  85264. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  85265. }
  85266. else if (uniform.semantic && (uniform.source || uniform.node)) {
  85267. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  85268. if (source === null) {
  85269. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  85270. }
  85271. if (source === null) {
  85272. continue;
  85273. }
  85274. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  85275. }
  85276. }
  85277. else {
  85278. var value = materialValues[technique.uniforms[unif]];
  85279. if (!value) {
  85280. continue;
  85281. }
  85282. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  85283. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  85284. if (texture === null || texture === undefined) {
  85285. continue;
  85286. }
  85287. shaderMaterial.getEffect().setTexture(unif, texture);
  85288. }
  85289. else {
  85290. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  85291. }
  85292. }
  85293. }
  85294. onSuccess(shaderMaterial);
  85295. };
  85296. /**
  85297. * Prepare uniforms to send the only one time
  85298. * Loads the appropriate textures
  85299. */
  85300. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  85301. var materialValues = material.values || technique.parameters;
  85302. var techniqueUniforms = technique.uniforms;
  85303. /**
  85304. * Prepare values here (not matrices)
  85305. */
  85306. for (var unif in unTreatedUniforms) {
  85307. var uniform = unTreatedUniforms[unif];
  85308. var type = uniform.type;
  85309. var value = materialValues[techniqueUniforms[unif]];
  85310. if (value === undefined) {
  85311. // In case the value is the same for all materials
  85312. value = uniform.value;
  85313. }
  85314. if (!value) {
  85315. continue;
  85316. }
  85317. var onLoadTexture = function (uniformName) {
  85318. return function (texture) {
  85319. if (uniform.value && uniformName) {
  85320. // Static uniform
  85321. shaderMaterial.setTexture(uniformName, texture);
  85322. delete unTreatedUniforms[uniformName];
  85323. }
  85324. };
  85325. };
  85326. // Texture (sampler2D)
  85327. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  85328. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  85329. }
  85330. else {
  85331. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  85332. // Static uniform
  85333. delete unTreatedUniforms[unif];
  85334. }
  85335. }
  85336. }
  85337. };
  85338. /**
  85339. * Shader compilation failed
  85340. */
  85341. var onShaderCompileError = function (program, shaderMaterial, onError) {
  85342. return function (effect, error) {
  85343. shaderMaterial.dispose(true);
  85344. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  85345. };
  85346. };
  85347. /**
  85348. * Shader compilation success
  85349. */
  85350. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  85351. return function (_) {
  85352. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  85353. shaderMaterial.onBind = function (mesh) {
  85354. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  85355. };
  85356. };
  85357. };
  85358. /**
  85359. * Returns the appropriate uniform if already handled by babylon
  85360. */
  85361. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  85362. for (var unif in technique.uniforms) {
  85363. var uniform = technique.uniforms[unif];
  85364. var uniformParameter = technique.parameters[uniform];
  85365. if (tokenizer.currentIdentifier === unif) {
  85366. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  85367. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  85368. if (transformIndex !== -1) {
  85369. delete unTreatedUniforms[unif];
  85370. return babylonTransforms[transformIndex];
  85371. }
  85372. }
  85373. }
  85374. }
  85375. return tokenizer.currentIdentifier;
  85376. };
  85377. /**
  85378. * All shaders loaded. Create materials one by one
  85379. */
  85380. var importMaterials = function (gltfRuntime) {
  85381. // Create materials
  85382. for (var mat in gltfRuntime.materials) {
  85383. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  85384. }
  85385. };
  85386. /**
  85387. * Implementation of the base glTF spec
  85388. */
  85389. var GLTFLoaderBase = /** @class */ (function () {
  85390. function GLTFLoaderBase() {
  85391. }
  85392. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  85393. var gltfRuntime = {
  85394. extensions: {},
  85395. accessors: {},
  85396. buffers: {},
  85397. bufferViews: {},
  85398. meshes: {},
  85399. lights: {},
  85400. cameras: {},
  85401. nodes: {},
  85402. images: {},
  85403. textures: {},
  85404. shaders: {},
  85405. programs: {},
  85406. samplers: {},
  85407. techniques: {},
  85408. materials: {},
  85409. animations: {},
  85410. skins: {},
  85411. extensionsUsed: [],
  85412. scenes: {},
  85413. buffersCount: 0,
  85414. shaderscount: 0,
  85415. scene: scene,
  85416. rootUrl: rootUrl,
  85417. loadedBufferCount: 0,
  85418. loadedBufferViews: {},
  85419. loadedShaderCount: 0,
  85420. importOnlyMeshes: false,
  85421. dummyNodes: []
  85422. };
  85423. // Parse
  85424. if (parsedData.extensions) {
  85425. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  85426. }
  85427. if (parsedData.extensionsUsed) {
  85428. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  85429. }
  85430. if (parsedData.buffers) {
  85431. parseBuffers(parsedData.buffers, gltfRuntime);
  85432. }
  85433. if (parsedData.bufferViews) {
  85434. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  85435. }
  85436. if (parsedData.accessors) {
  85437. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  85438. }
  85439. if (parsedData.meshes) {
  85440. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  85441. }
  85442. if (parsedData.lights) {
  85443. parseObject(parsedData.lights, "lights", gltfRuntime);
  85444. }
  85445. if (parsedData.cameras) {
  85446. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  85447. }
  85448. if (parsedData.nodes) {
  85449. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  85450. }
  85451. if (parsedData.images) {
  85452. parseObject(parsedData.images, "images", gltfRuntime);
  85453. }
  85454. if (parsedData.textures) {
  85455. parseObject(parsedData.textures, "textures", gltfRuntime);
  85456. }
  85457. if (parsedData.shaders) {
  85458. parseShaders(parsedData.shaders, gltfRuntime);
  85459. }
  85460. if (parsedData.programs) {
  85461. parseObject(parsedData.programs, "programs", gltfRuntime);
  85462. }
  85463. if (parsedData.samplers) {
  85464. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  85465. }
  85466. if (parsedData.techniques) {
  85467. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  85468. }
  85469. if (parsedData.materials) {
  85470. parseObject(parsedData.materials, "materials", gltfRuntime);
  85471. }
  85472. if (parsedData.animations) {
  85473. parseObject(parsedData.animations, "animations", gltfRuntime);
  85474. }
  85475. if (parsedData.skins) {
  85476. parseObject(parsedData.skins, "skins", gltfRuntime);
  85477. }
  85478. if (parsedData.scenes) {
  85479. gltfRuntime.scenes = parsedData.scenes;
  85480. }
  85481. if (parsedData.scene && parsedData.scenes) {
  85482. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  85483. }
  85484. return gltfRuntime;
  85485. };
  85486. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  85487. var buffer = gltfRuntime.buffers[id];
  85488. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  85489. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  85490. }
  85491. else {
  85492. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  85493. if (request) {
  85494. onError(request.status + " " + request.statusText);
  85495. }
  85496. });
  85497. }
  85498. };
  85499. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  85500. var texture = gltfRuntime.textures[id];
  85501. if (!texture || !texture.source) {
  85502. onError("");
  85503. return;
  85504. }
  85505. if (texture.babylonTexture) {
  85506. onSuccess(null);
  85507. return;
  85508. }
  85509. var source = gltfRuntime.images[texture.source];
  85510. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  85511. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  85512. }
  85513. else {
  85514. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  85515. if (request) {
  85516. onError(request.status + " " + request.statusText);
  85517. }
  85518. });
  85519. }
  85520. };
  85521. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  85522. var texture = gltfRuntime.textures[id];
  85523. if (texture.babylonTexture) {
  85524. onSuccess(texture.babylonTexture);
  85525. return;
  85526. }
  85527. var sampler = gltfRuntime.samplers[texture.sampler];
  85528. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  85529. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  85530. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  85531. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  85532. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  85533. var blob = new Blob([buffer]);
  85534. var blobURL = URL.createObjectURL(blob);
  85535. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  85536. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  85537. if (sampler.wrapS !== undefined) {
  85538. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  85539. }
  85540. if (sampler.wrapT !== undefined) {
  85541. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  85542. }
  85543. newTexture.name = id;
  85544. texture.babylonTexture = newTexture;
  85545. onSuccess(newTexture);
  85546. };
  85547. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  85548. var shader = gltfRuntime.shaders[id];
  85549. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  85550. var shaderString = atob(shader.uri.split(",")[1]);
  85551. onSuccess(shaderString);
  85552. }
  85553. else {
  85554. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  85555. if (request) {
  85556. onError(request.status + " " + request.statusText);
  85557. }
  85558. });
  85559. }
  85560. };
  85561. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  85562. var material = gltfRuntime.materials[id];
  85563. if (!material.technique) {
  85564. if (onError) {
  85565. onError("No technique found.");
  85566. }
  85567. return;
  85568. }
  85569. var technique = gltfRuntime.techniques[material.technique];
  85570. if (!technique) {
  85571. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  85572. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  85573. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  85574. onSuccess(defaultMaterial);
  85575. return;
  85576. }
  85577. var program = gltfRuntime.programs[technique.program];
  85578. var states = technique.states;
  85579. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  85580. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  85581. var newVertexShader = "";
  85582. var newPixelShader = "";
  85583. var vertexTokenizer = new Tokenizer(vertexShader);
  85584. var pixelTokenizer = new Tokenizer(pixelShader);
  85585. var unTreatedUniforms = {};
  85586. var uniforms = [];
  85587. var attributes = [];
  85588. var samplers = [];
  85589. // Fill uniform, sampler2D and attributes
  85590. for (var unif in technique.uniforms) {
  85591. var uniform = technique.uniforms[unif];
  85592. var uniformParameter = technique.parameters[uniform];
  85593. unTreatedUniforms[unif] = uniformParameter;
  85594. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  85595. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  85596. if (transformIndex !== -1) {
  85597. uniforms.push(babylonTransforms[transformIndex]);
  85598. delete unTreatedUniforms[unif];
  85599. }
  85600. else {
  85601. uniforms.push(unif);
  85602. }
  85603. }
  85604. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  85605. samplers.push(unif);
  85606. }
  85607. else {
  85608. uniforms.push(unif);
  85609. }
  85610. }
  85611. for (var attr in technique.attributes) {
  85612. var attribute = technique.attributes[attr];
  85613. var attributeParameter = technique.parameters[attribute];
  85614. if (attributeParameter.semantic) {
  85615. attributes.push(getAttribute(attributeParameter));
  85616. }
  85617. }
  85618. // Configure vertex shader
  85619. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  85620. var tokenType = vertexTokenizer.currentToken;
  85621. if (tokenType !== ETokenType.IDENTIFIER) {
  85622. newVertexShader += vertexTokenizer.currentString;
  85623. continue;
  85624. }
  85625. var foundAttribute = false;
  85626. for (var attr in technique.attributes) {
  85627. var attribute = technique.attributes[attr];
  85628. var attributeParameter = technique.parameters[attribute];
  85629. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  85630. newVertexShader += getAttribute(attributeParameter);
  85631. foundAttribute = true;
  85632. break;
  85633. }
  85634. }
  85635. if (foundAttribute) {
  85636. continue;
  85637. }
  85638. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  85639. }
  85640. // Configure pixel shader
  85641. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  85642. var tokenType = pixelTokenizer.currentToken;
  85643. if (tokenType !== ETokenType.IDENTIFIER) {
  85644. newPixelShader += pixelTokenizer.currentString;
  85645. continue;
  85646. }
  85647. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  85648. }
  85649. // Create shader material
  85650. var shaderPath = {
  85651. vertex: program.vertexShader + id,
  85652. fragment: program.fragmentShader + id
  85653. };
  85654. var options = {
  85655. attributes: attributes,
  85656. uniforms: uniforms,
  85657. samplers: samplers,
  85658. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  85659. };
  85660. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  85661. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  85662. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  85663. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  85664. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  85665. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  85666. if (states && states.functions) {
  85667. var functions = states.functions;
  85668. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  85669. shaderMaterial.backFaceCulling = false;
  85670. }
  85671. var blendFunc = functions.blendFuncSeparate;
  85672. if (blendFunc) {
  85673. 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) {
  85674. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  85675. }
  85676. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  85677. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  85678. }
  85679. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  85680. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  85681. }
  85682. 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) {
  85683. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  85684. }
  85685. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  85686. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  85687. }
  85688. 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) {
  85689. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  85690. }
  85691. }
  85692. }
  85693. };
  85694. return GLTFLoaderBase;
  85695. }());
  85696. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  85697. /**
  85698. * glTF V1 Loader
  85699. */
  85700. var GLTFLoader = /** @class */ (function () {
  85701. function GLTFLoader() {
  85702. // #region Stubs for IGLTFLoader interface
  85703. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  85704. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  85705. this.compileMaterials = false;
  85706. this.useClipPlane = false;
  85707. this.compileShadowGenerators = false;
  85708. this.onDisposeObservable = new BABYLON.Observable();
  85709. this.onMeshLoadedObservable = new BABYLON.Observable();
  85710. this.onTextureLoadedObservable = new BABYLON.Observable();
  85711. this.onMaterialLoadedObservable = new BABYLON.Observable();
  85712. this.onCompleteObservable = new BABYLON.Observable();
  85713. }
  85714. GLTFLoader.RegisterExtension = function (extension) {
  85715. if (GLTFLoader.Extensions[extension.name]) {
  85716. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  85717. return;
  85718. }
  85719. GLTFLoader.Extensions[extension.name] = extension;
  85720. };
  85721. GLTFLoader.prototype.dispose = function () { };
  85722. // #endregion
  85723. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  85724. var _this = this;
  85725. scene.useRightHandedSystem = true;
  85726. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  85727. gltfRuntime.importOnlyMeshes = true;
  85728. if (meshesNames === "") {
  85729. gltfRuntime.importMeshesNames = [];
  85730. }
  85731. else if (typeof meshesNames === "string") {
  85732. gltfRuntime.importMeshesNames = [meshesNames];
  85733. }
  85734. else if (meshesNames && !(meshesNames instanceof Array)) {
  85735. gltfRuntime.importMeshesNames = [meshesNames];
  85736. }
  85737. else {
  85738. gltfRuntime.importMeshesNames = [];
  85739. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  85740. }
  85741. // Create nodes
  85742. _this._createNodes(gltfRuntime);
  85743. var meshes = new Array();
  85744. var skeletons = new Array();
  85745. // Fill arrays of meshes and skeletons
  85746. for (var nde in gltfRuntime.nodes) {
  85747. var node = gltfRuntime.nodes[nde];
  85748. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  85749. meshes.push(node.babylonNode);
  85750. }
  85751. }
  85752. for (var skl in gltfRuntime.skins) {
  85753. var skin = gltfRuntime.skins[skl];
  85754. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  85755. skeletons.push(skin.babylonSkeleton);
  85756. }
  85757. }
  85758. // Load buffers, shaders, materials, etc.
  85759. _this._loadBuffersAsync(gltfRuntime, function () {
  85760. _this._loadShadersAsync(gltfRuntime, function () {
  85761. importMaterials(gltfRuntime);
  85762. postLoad(gltfRuntime);
  85763. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  85764. onSuccess(meshes, [], skeletons);
  85765. }
  85766. });
  85767. }, onProgress);
  85768. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  85769. onSuccess(meshes, [], skeletons);
  85770. }
  85771. }, onError);
  85772. return true;
  85773. };
  85774. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85775. var _this = this;
  85776. scene.useRightHandedSystem = true;
  85777. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  85778. // Load runtime extensios
  85779. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  85780. // Create nodes
  85781. _this._createNodes(gltfRuntime);
  85782. // Load buffers, shaders, materials, etc.
  85783. _this._loadBuffersAsync(gltfRuntime, function () {
  85784. _this._loadShadersAsync(gltfRuntime, function () {
  85785. importMaterials(gltfRuntime);
  85786. postLoad(gltfRuntime);
  85787. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  85788. onSuccess();
  85789. }
  85790. });
  85791. });
  85792. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  85793. onSuccess();
  85794. }
  85795. }, onError);
  85796. }, onError);
  85797. };
  85798. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  85799. var hasShaders = false;
  85800. var processShader = function (sha, shader) {
  85801. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  85802. gltfRuntime.loadedShaderCount++;
  85803. if (shaderString) {
  85804. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  85805. }
  85806. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  85807. onload();
  85808. }
  85809. }, function () {
  85810. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  85811. });
  85812. };
  85813. for (var sha in gltfRuntime.shaders) {
  85814. hasShaders = true;
  85815. var shader = gltfRuntime.shaders[sha];
  85816. if (shader) {
  85817. processShader.bind(this, sha, shader)();
  85818. }
  85819. else {
  85820. BABYLON.Tools.Error("No shader named: " + sha);
  85821. }
  85822. }
  85823. if (!hasShaders) {
  85824. onload();
  85825. }
  85826. };
  85827. ;
  85828. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  85829. var hasBuffers = false;
  85830. var processBuffer = function (buf, buffer) {
  85831. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  85832. gltfRuntime.loadedBufferCount++;
  85833. if (bufferView) {
  85834. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  85835. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  85836. }
  85837. gltfRuntime.loadedBufferViews[buf] = bufferView;
  85838. }
  85839. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  85840. onLoad();
  85841. }
  85842. }, function () {
  85843. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  85844. });
  85845. };
  85846. for (var buf in gltfRuntime.buffers) {
  85847. hasBuffers = true;
  85848. var buffer = gltfRuntime.buffers[buf];
  85849. if (buffer) {
  85850. processBuffer.bind(this, buf, buffer)();
  85851. }
  85852. else {
  85853. BABYLON.Tools.Error("No buffer named: " + buf);
  85854. }
  85855. }
  85856. if (!hasBuffers) {
  85857. onLoad();
  85858. }
  85859. };
  85860. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  85861. var currentScene = gltfRuntime.currentScene;
  85862. if (currentScene) {
  85863. // Only one scene even if multiple scenes are defined
  85864. for (var i = 0; i < currentScene.nodes.length; i++) {
  85865. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85866. }
  85867. }
  85868. else {
  85869. // Load all scenes
  85870. for (var thing in gltfRuntime.scenes) {
  85871. currentScene = gltfRuntime.scenes[thing];
  85872. for (var i = 0; i < currentScene.nodes.length; i++) {
  85873. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85874. }
  85875. }
  85876. }
  85877. };
  85878. GLTFLoader.Extensions = {};
  85879. return GLTFLoader;
  85880. }());
  85881. GLTF1.GLTFLoader = GLTFLoader;
  85882. ;
  85883. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  85884. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  85885. })(BABYLON || (BABYLON = {}));
  85886. //# sourceMappingURL=babylon.glTFLoader.js.map
  85887. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85888. var BABYLON;
  85889. (function (BABYLON) {
  85890. var GLTF1;
  85891. (function (GLTF1) {
  85892. /**
  85893. * Utils functions for GLTF
  85894. */
  85895. var GLTFUtils = /** @class */ (function () {
  85896. function GLTFUtils() {
  85897. }
  85898. /**
  85899. * Sets the given "parameter" matrix
  85900. * @param scene: the {BABYLON.Scene} object
  85901. * @param source: the source node where to pick the matrix
  85902. * @param parameter: the GLTF technique parameter
  85903. * @param uniformName: the name of the shader's uniform
  85904. * @param shaderMaterial: the shader material
  85905. */
  85906. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  85907. var mat = null;
  85908. if (parameter.semantic === "MODEL") {
  85909. mat = source.getWorldMatrix();
  85910. }
  85911. else if (parameter.semantic === "PROJECTION") {
  85912. mat = scene.getProjectionMatrix();
  85913. }
  85914. else if (parameter.semantic === "VIEW") {
  85915. mat = scene.getViewMatrix();
  85916. }
  85917. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  85918. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  85919. }
  85920. else if (parameter.semantic === "MODELVIEW") {
  85921. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  85922. }
  85923. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  85924. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  85925. }
  85926. else if (parameter.semantic === "MODELINVERSE") {
  85927. mat = source.getWorldMatrix().invert();
  85928. }
  85929. else if (parameter.semantic === "VIEWINVERSE") {
  85930. mat = scene.getViewMatrix().invert();
  85931. }
  85932. else if (parameter.semantic === "PROJECTIONINVERSE") {
  85933. mat = scene.getProjectionMatrix().invert();
  85934. }
  85935. else if (parameter.semantic === "MODELVIEWINVERSE") {
  85936. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  85937. }
  85938. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  85939. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  85940. }
  85941. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  85942. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  85943. }
  85944. else {
  85945. debugger;
  85946. }
  85947. if (mat) {
  85948. switch (parameter.type) {
  85949. case GLTF1.EParameterType.FLOAT_MAT2:
  85950. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  85951. break;
  85952. case GLTF1.EParameterType.FLOAT_MAT3:
  85953. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  85954. break;
  85955. case GLTF1.EParameterType.FLOAT_MAT4:
  85956. shaderMaterial.setMatrix(uniformName, mat);
  85957. break;
  85958. default: break;
  85959. }
  85960. }
  85961. };
  85962. /**
  85963. * Sets the given "parameter" matrix
  85964. * @param shaderMaterial: the shader material
  85965. * @param uniform: the name of the shader's uniform
  85966. * @param value: the value of the uniform
  85967. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  85968. */
  85969. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  85970. switch (type) {
  85971. case GLTF1.EParameterType.FLOAT:
  85972. shaderMaterial.setFloat(uniform, value);
  85973. return true;
  85974. case GLTF1.EParameterType.FLOAT_VEC2:
  85975. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  85976. return true;
  85977. case GLTF1.EParameterType.FLOAT_VEC3:
  85978. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  85979. return true;
  85980. case GLTF1.EParameterType.FLOAT_VEC4:
  85981. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  85982. return true;
  85983. default: return false;
  85984. }
  85985. };
  85986. /**
  85987. * If the uri is a base64 string
  85988. * @param uri: the uri to test
  85989. */
  85990. GLTFUtils.IsBase64 = function (uri) {
  85991. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  85992. };
  85993. /**
  85994. * Decode the base64 uri
  85995. * @param uri: the uri to decode
  85996. */
  85997. GLTFUtils.DecodeBase64 = function (uri) {
  85998. var decodedString = atob(uri.split(",")[1]);
  85999. var bufferLength = decodedString.length;
  86000. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  86001. for (var i = 0; i < bufferLength; i++) {
  86002. bufferView[i] = decodedString.charCodeAt(i);
  86003. }
  86004. return bufferView.buffer;
  86005. };
  86006. /**
  86007. * Returns the wrap mode of the texture
  86008. * @param mode: the mode value
  86009. */
  86010. GLTFUtils.GetWrapMode = function (mode) {
  86011. switch (mode) {
  86012. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  86013. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  86014. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  86015. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  86016. }
  86017. };
  86018. /**
  86019. * Returns the byte stride giving an accessor
  86020. * @param accessor: the GLTF accessor objet
  86021. */
  86022. GLTFUtils.GetByteStrideFromType = function (accessor) {
  86023. // Needs this function since "byteStride" isn't requiered in glTF format
  86024. var type = accessor.type;
  86025. switch (type) {
  86026. case "VEC2": return 2;
  86027. case "VEC3": return 3;
  86028. case "VEC4": return 4;
  86029. case "MAT2": return 4;
  86030. case "MAT3": return 9;
  86031. case "MAT4": return 16;
  86032. default: return 1;
  86033. }
  86034. };
  86035. /**
  86036. * Returns the texture filter mode giving a mode value
  86037. * @param mode: the filter mode value
  86038. */
  86039. GLTFUtils.GetTextureFilterMode = function (mode) {
  86040. switch (mode) {
  86041. case GLTF1.ETextureFilterType.LINEAR:
  86042. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  86043. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  86044. case GLTF1.ETextureFilterType.NEAREST:
  86045. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  86046. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  86047. }
  86048. };
  86049. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  86050. var byteOffset = bufferView.byteOffset + byteOffset;
  86051. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  86052. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  86053. throw new Error("Buffer access is out of range");
  86054. }
  86055. var buffer = loadedBufferView.buffer;
  86056. byteOffset += loadedBufferView.byteOffset;
  86057. switch (componentType) {
  86058. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  86059. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  86060. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  86061. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  86062. default: return new Float32Array(buffer, byteOffset, byteLength);
  86063. }
  86064. };
  86065. /**
  86066. * Returns a buffer from its accessor
  86067. * @param gltfRuntime: the GLTF runtime
  86068. * @param accessor: the GLTF accessor
  86069. */
  86070. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  86071. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  86072. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  86073. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  86074. };
  86075. /**
  86076. * Decodes a buffer view into a string
  86077. * @param view: the buffer view
  86078. */
  86079. GLTFUtils.DecodeBufferToText = function (view) {
  86080. var result = "";
  86081. var length = view.byteLength;
  86082. for (var i = 0; i < length; ++i) {
  86083. result += String.fromCharCode(view[i]);
  86084. }
  86085. return result;
  86086. };
  86087. /**
  86088. * Returns the default material of gltf. Related to
  86089. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  86090. * @param scene: the Babylon.js scene
  86091. */
  86092. GLTFUtils.GetDefaultMaterial = function (scene) {
  86093. if (!GLTFUtils._DefaultMaterial) {
  86094. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  86095. "precision highp float;",
  86096. "",
  86097. "uniform mat4 worldView;",
  86098. "uniform mat4 projection;",
  86099. "",
  86100. "attribute vec3 position;",
  86101. "",
  86102. "void main(void)",
  86103. "{",
  86104. " gl_Position = projection * worldView * vec4(position, 1.0);",
  86105. "}"
  86106. ].join("\n");
  86107. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  86108. "precision highp float;",
  86109. "",
  86110. "uniform vec4 u_emission;",
  86111. "",
  86112. "void main(void)",
  86113. "{",
  86114. " gl_FragColor = u_emission;",
  86115. "}"
  86116. ].join("\n");
  86117. var shaderPath = {
  86118. vertex: "GLTFDefaultMaterial",
  86119. fragment: "GLTFDefaultMaterial"
  86120. };
  86121. var options = {
  86122. attributes: ["position"],
  86123. uniforms: ["worldView", "projection", "u_emission"],
  86124. samplers: new Array(),
  86125. needAlphaBlending: false
  86126. };
  86127. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  86128. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  86129. }
  86130. return GLTFUtils._DefaultMaterial;
  86131. };
  86132. // The GLTF default material
  86133. GLTFUtils._DefaultMaterial = null;
  86134. return GLTFUtils;
  86135. }());
  86136. GLTF1.GLTFUtils = GLTFUtils;
  86137. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86138. })(BABYLON || (BABYLON = {}));
  86139. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  86140. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86141. var BABYLON;
  86142. (function (BABYLON) {
  86143. var GLTF1;
  86144. (function (GLTF1) {
  86145. var GLTFLoaderExtension = /** @class */ (function () {
  86146. function GLTFLoaderExtension(name) {
  86147. this._name = name;
  86148. }
  86149. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  86150. get: function () {
  86151. return this._name;
  86152. },
  86153. enumerable: true,
  86154. configurable: true
  86155. });
  86156. /**
  86157. * Defines an override for loading the runtime
  86158. * Return true to stop further extensions from loading the runtime
  86159. */
  86160. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  86161. return false;
  86162. };
  86163. /**
  86164. * Defines an onverride for creating gltf runtime
  86165. * Return true to stop further extensions from creating the runtime
  86166. */
  86167. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  86168. return false;
  86169. };
  86170. /**
  86171. * Defines an override for loading buffers
  86172. * Return true to stop further extensions from loading this buffer
  86173. */
  86174. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  86175. return false;
  86176. };
  86177. /**
  86178. * Defines an override for loading texture buffers
  86179. * Return true to stop further extensions from loading this texture data
  86180. */
  86181. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86182. return false;
  86183. };
  86184. /**
  86185. * Defines an override for creating textures
  86186. * Return true to stop further extensions from loading this texture
  86187. */
  86188. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  86189. return false;
  86190. };
  86191. /**
  86192. * Defines an override for loading shader strings
  86193. * Return true to stop further extensions from loading this shader data
  86194. */
  86195. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86196. return false;
  86197. };
  86198. /**
  86199. * Defines an override for loading materials
  86200. * Return true to stop further extensions from loading this material
  86201. */
  86202. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86203. return false;
  86204. };
  86205. // ---------
  86206. // Utilities
  86207. // ---------
  86208. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  86209. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86210. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  86211. }, function () {
  86212. setTimeout(function () {
  86213. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  86214. });
  86215. });
  86216. };
  86217. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  86218. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86219. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  86220. }, function () {
  86221. setTimeout(function () {
  86222. onSuccess();
  86223. });
  86224. });
  86225. };
  86226. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  86227. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86228. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  86229. }, function () {
  86230. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  86231. });
  86232. };
  86233. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  86234. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  86235. };
  86236. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86237. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86238. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  86239. }, function () {
  86240. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  86241. });
  86242. };
  86243. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86244. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86245. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  86246. }, function () {
  86247. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  86248. });
  86249. };
  86250. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86251. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86252. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  86253. }, function () {
  86254. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  86255. });
  86256. };
  86257. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  86258. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86259. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  86260. }, function () {
  86261. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  86262. });
  86263. };
  86264. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  86265. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  86266. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  86267. if (func(loaderExtension)) {
  86268. return;
  86269. }
  86270. }
  86271. defaultFunc();
  86272. };
  86273. return GLTFLoaderExtension;
  86274. }());
  86275. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  86276. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86277. })(BABYLON || (BABYLON = {}));
  86278. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  86279. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86280. var BABYLON;
  86281. (function (BABYLON) {
  86282. var GLTF1;
  86283. (function (GLTF1) {
  86284. var BinaryExtensionBufferName = "binary_glTF";
  86285. ;
  86286. ;
  86287. var GLTFBinaryExtension = /** @class */ (function (_super) {
  86288. __extends(GLTFBinaryExtension, _super);
  86289. function GLTFBinaryExtension() {
  86290. return _super.call(this, "KHR_binary_glTF") || this;
  86291. }
  86292. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  86293. var extensionsUsed = data.json.extensionsUsed;
  86294. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  86295. return false;
  86296. }
  86297. this._bin = data.bin;
  86298. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  86299. return true;
  86300. };
  86301. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86302. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  86303. return false;
  86304. }
  86305. if (id !== BinaryExtensionBufferName) {
  86306. return false;
  86307. }
  86308. onSuccess(this._bin);
  86309. return true;
  86310. };
  86311. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86312. var texture = gltfRuntime.textures[id];
  86313. var source = gltfRuntime.images[texture.source];
  86314. if (!source.extensions || !(this.name in source.extensions)) {
  86315. return false;
  86316. }
  86317. var sourceExt = source.extensions[this.name];
  86318. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  86319. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  86320. onSuccess(buffer);
  86321. return true;
  86322. };
  86323. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86324. var shader = gltfRuntime.shaders[id];
  86325. if (!shader.extensions || !(this.name in shader.extensions)) {
  86326. return false;
  86327. }
  86328. var binaryExtensionShader = shader.extensions[this.name];
  86329. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  86330. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  86331. setTimeout(function () {
  86332. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  86333. onSuccess(shaderString);
  86334. });
  86335. return true;
  86336. };
  86337. return GLTFBinaryExtension;
  86338. }(GLTF1.GLTFLoaderExtension));
  86339. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  86340. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  86341. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86342. })(BABYLON || (BABYLON = {}));
  86343. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  86344. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86345. var BABYLON;
  86346. (function (BABYLON) {
  86347. var GLTF1;
  86348. (function (GLTF1) {
  86349. ;
  86350. ;
  86351. ;
  86352. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  86353. __extends(GLTFMaterialsCommonExtension, _super);
  86354. function GLTFMaterialsCommonExtension() {
  86355. return _super.call(this, "KHR_materials_common") || this;
  86356. }
  86357. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  86358. if (!gltfRuntime.extensions)
  86359. return false;
  86360. var extension = gltfRuntime.extensions[this.name];
  86361. if (!extension)
  86362. return false;
  86363. // Create lights
  86364. var lights = extension.lights;
  86365. if (lights) {
  86366. for (var thing in lights) {
  86367. var light = lights[thing];
  86368. switch (light.type) {
  86369. case "ambient":
  86370. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  86371. var ambient = light.ambient;
  86372. if (ambient) {
  86373. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  86374. }
  86375. break;
  86376. case "point":
  86377. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  86378. var point = light.point;
  86379. if (point) {
  86380. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  86381. }
  86382. break;
  86383. case "directional":
  86384. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  86385. var directional = light.directional;
  86386. if (directional) {
  86387. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  86388. }
  86389. break;
  86390. case "spot":
  86391. var spot = light.spot;
  86392. if (spot) {
  86393. 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);
  86394. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  86395. }
  86396. break;
  86397. default:
  86398. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  86399. break;
  86400. }
  86401. }
  86402. }
  86403. return false;
  86404. };
  86405. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86406. var material = gltfRuntime.materials[id];
  86407. if (!material || !material.extensions)
  86408. return false;
  86409. var extension = material.extensions[this.name];
  86410. if (!extension)
  86411. return false;
  86412. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  86413. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86414. if (extension.technique === "CONSTANT") {
  86415. standardMaterial.disableLighting = true;
  86416. }
  86417. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  86418. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  86419. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  86420. // Ambient
  86421. if (typeof extension.values.ambient === "string") {
  86422. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  86423. }
  86424. else {
  86425. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  86426. }
  86427. // Diffuse
  86428. if (typeof extension.values.diffuse === "string") {
  86429. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  86430. }
  86431. else {
  86432. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  86433. }
  86434. // Emission
  86435. if (typeof extension.values.emission === "string") {
  86436. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  86437. }
  86438. else {
  86439. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  86440. }
  86441. // Specular
  86442. if (typeof extension.values.specular === "string") {
  86443. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  86444. }
  86445. else {
  86446. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  86447. }
  86448. return true;
  86449. };
  86450. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  86451. // Create buffer from texture url
  86452. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  86453. // Create texture from buffer
  86454. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  86455. }, onError);
  86456. };
  86457. return GLTFMaterialsCommonExtension;
  86458. }(GLTF1.GLTFLoaderExtension));
  86459. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  86460. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  86461. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86462. })(BABYLON || (BABYLON = {}));
  86463. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  86464. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86465. var BABYLON;
  86466. (function (BABYLON) {
  86467. var GLTF2;
  86468. (function (GLTF2) {
  86469. /**
  86470. * Enums
  86471. */
  86472. var EComponentType;
  86473. (function (EComponentType) {
  86474. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  86475. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  86476. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  86477. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  86478. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  86479. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  86480. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  86481. var EMeshPrimitiveMode;
  86482. (function (EMeshPrimitiveMode) {
  86483. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  86484. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  86485. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  86486. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  86487. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  86488. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  86489. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  86490. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  86491. var ETextureMagFilter;
  86492. (function (ETextureMagFilter) {
  86493. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  86494. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  86495. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  86496. var ETextureMinFilter;
  86497. (function (ETextureMinFilter) {
  86498. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  86499. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  86500. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  86501. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  86502. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  86503. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  86504. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  86505. var ETextureWrapMode;
  86506. (function (ETextureWrapMode) {
  86507. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  86508. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  86509. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  86510. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  86511. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86512. })(BABYLON || (BABYLON = {}));
  86513. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  86514. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86515. var BABYLON;
  86516. (function (BABYLON) {
  86517. var GLTF2;
  86518. (function (GLTF2) {
  86519. var GLTFLoaderTracker = /** @class */ (function () {
  86520. function GLTFLoaderTracker(onComplete) {
  86521. this._pendingCount = 0;
  86522. this._callback = onComplete;
  86523. }
  86524. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  86525. this._pendingCount++;
  86526. };
  86527. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  86528. if (--this._pendingCount === 0) {
  86529. this._callback();
  86530. }
  86531. };
  86532. return GLTFLoaderTracker;
  86533. }());
  86534. var GLTFLoader = /** @class */ (function () {
  86535. function GLTFLoader() {
  86536. this._disposed = false;
  86537. this._defaultSampler = {};
  86538. this._renderReady = false;
  86539. this._requests = new Array();
  86540. this._renderReadyObservable = new BABYLON.Observable();
  86541. // Count of pending work that needs to complete before the asset is rendered.
  86542. this._renderPendingCount = 0;
  86543. // Count of pending work that needs to complete before the loader is disposed.
  86544. this._loaderPendingCount = 0;
  86545. this._loaderTrackers = new Array();
  86546. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  86547. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  86548. this.compileMaterials = false;
  86549. this.useClipPlane = false;
  86550. this.compileShadowGenerators = false;
  86551. this.onDisposeObservable = new BABYLON.Observable();
  86552. this.onMeshLoadedObservable = new BABYLON.Observable();
  86553. this.onTextureLoadedObservable = new BABYLON.Observable();
  86554. this.onMaterialLoadedObservable = new BABYLON.Observable();
  86555. this.onCompleteObservable = new BABYLON.Observable();
  86556. }
  86557. GLTFLoader.RegisterExtension = function (extension) {
  86558. if (GLTFLoader.Extensions[extension.name]) {
  86559. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  86560. return;
  86561. }
  86562. GLTFLoader.Extensions[extension.name] = extension;
  86563. // Keep the order of registration so that extensions registered first are called first.
  86564. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  86565. };
  86566. GLTFLoader.prototype.dispose = function () {
  86567. if (this._disposed) {
  86568. return;
  86569. }
  86570. this._disposed = true;
  86571. this._abortRequests();
  86572. this._releaseResources();
  86573. this.onDisposeObservable.notifyObservers(this);
  86574. };
  86575. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  86576. var _this = this;
  86577. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  86578. if (onSuccess) {
  86579. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  86580. }
  86581. }, onProgress, onError);
  86582. };
  86583. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  86584. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  86585. };
  86586. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  86587. var _this = this;
  86588. this._babylonScene = scene;
  86589. this._rootUrl = rootUrl;
  86590. this._successCallback = onSuccess;
  86591. this._progressCallback = onProgress;
  86592. this._errorCallback = onError;
  86593. this._tryCatchOnError(function () {
  86594. _this._loadData(data);
  86595. _this._addPendingData(_this);
  86596. _this._loadDefaultScene(nodeNames);
  86597. _this._loadAnimations();
  86598. _this._removePendingData(_this);
  86599. });
  86600. };
  86601. GLTFLoader.prototype._onProgress = function () {
  86602. if (!this._progressCallback) {
  86603. return;
  86604. }
  86605. var lengthComputable = true;
  86606. var loaded = 0;
  86607. var total = 0;
  86608. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  86609. var request = _a[_i];
  86610. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  86611. return;
  86612. }
  86613. lengthComputable = lengthComputable && request._lengthComputable;
  86614. loaded += request._loaded;
  86615. total += request._total;
  86616. }
  86617. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  86618. };
  86619. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  86620. if (this._renderReady) {
  86621. func();
  86622. }
  86623. else {
  86624. this._renderReadyObservable.add(func);
  86625. }
  86626. };
  86627. GLTFLoader.prototype._onRenderReady = function () {
  86628. this._rootNode.babylonMesh.setEnabled(true);
  86629. this._startAnimations();
  86630. if (this._successCallback) {
  86631. this._successCallback();
  86632. }
  86633. this._renderReadyObservable.notifyObservers(this);
  86634. };
  86635. GLTFLoader.prototype._onComplete = function () {
  86636. this._abortRequests();
  86637. this._releaseResources();
  86638. this.onCompleteObservable.notifyObservers(this);
  86639. };
  86640. GLTFLoader.prototype._loadData = function (data) {
  86641. this._gltf = data.json;
  86642. // Assign the index of each object for convinience.
  86643. GLTFLoader._AssignIndices(this._gltf.accessors);
  86644. GLTFLoader._AssignIndices(this._gltf.animations);
  86645. GLTFLoader._AssignIndices(this._gltf.buffers);
  86646. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  86647. GLTFLoader._AssignIndices(this._gltf.images);
  86648. GLTFLoader._AssignIndices(this._gltf.materials);
  86649. GLTFLoader._AssignIndices(this._gltf.meshes);
  86650. GLTFLoader._AssignIndices(this._gltf.nodes);
  86651. GLTFLoader._AssignIndices(this._gltf.samplers);
  86652. GLTFLoader._AssignIndices(this._gltf.scenes);
  86653. GLTFLoader._AssignIndices(this._gltf.skins);
  86654. GLTFLoader._AssignIndices(this._gltf.textures);
  86655. if (data.bin) {
  86656. var buffers = this._gltf.buffers;
  86657. if (buffers && buffers[0] && !buffers[0].uri) {
  86658. var binaryBuffer = buffers[0];
  86659. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  86660. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  86661. }
  86662. binaryBuffer.loadedData = data.bin;
  86663. }
  86664. else {
  86665. BABYLON.Tools.Warn("Unexpected BIN chunk");
  86666. }
  86667. }
  86668. };
  86669. GLTFLoader.prototype._getMeshes = function () {
  86670. var meshes = new Array();
  86671. // Root mesh is always first.
  86672. meshes.push(this._rootNode.babylonMesh);
  86673. var nodes = this._gltf.nodes;
  86674. if (nodes) {
  86675. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  86676. var node = nodes_1[_i];
  86677. if (node.babylonMesh) {
  86678. meshes.push(node.babylonMesh);
  86679. }
  86680. }
  86681. }
  86682. return meshes;
  86683. };
  86684. GLTFLoader.prototype._getSkeletons = function () {
  86685. var skeletons = new Array();
  86686. var skins = this._gltf.skins;
  86687. if (skins) {
  86688. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  86689. var skin = skins_1[_i];
  86690. if (skin.babylonSkeleton) {
  86691. skeletons.push(skin.babylonSkeleton);
  86692. }
  86693. }
  86694. }
  86695. return skeletons;
  86696. };
  86697. GLTFLoader.prototype._startAnimations = function () {
  86698. var animations = this._gltf.animations;
  86699. if (!animations) {
  86700. return;
  86701. }
  86702. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  86703. var animation = animations_1[_i];
  86704. animation.babylonAnimationGroup.normalize();
  86705. }
  86706. switch (this.animationStartMode) {
  86707. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  86708. // do nothing
  86709. break;
  86710. }
  86711. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  86712. var animation = animations[0];
  86713. animation.babylonAnimationGroup.start(true);
  86714. break;
  86715. }
  86716. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  86717. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  86718. var animation = animations_2[_a];
  86719. animation.babylonAnimationGroup.start(true);
  86720. }
  86721. break;
  86722. }
  86723. default: {
  86724. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  86725. return;
  86726. }
  86727. }
  86728. };
  86729. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  86730. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  86731. if (!scene) {
  86732. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  86733. }
  86734. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  86735. };
  86736. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  86737. var _this = this;
  86738. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  86739. switch (this.coordinateSystemMode) {
  86740. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  86741. if (!this._babylonScene.useRightHandedSystem) {
  86742. this._rootNode.rotation = [0, 1, 0, 0];
  86743. this._rootNode.scale = [1, 1, -1];
  86744. this._loadTransform(this._rootNode);
  86745. }
  86746. break;
  86747. }
  86748. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  86749. this._babylonScene.useRightHandedSystem = true;
  86750. break;
  86751. }
  86752. default: {
  86753. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  86754. return;
  86755. }
  86756. }
  86757. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  86758. var nodeIndices = scene.nodes;
  86759. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  86760. node.parent = parentNode;
  86761. return true;
  86762. }, this._rootNode);
  86763. if (nodeNames) {
  86764. if (!(nodeNames instanceof Array)) {
  86765. nodeNames = [nodeNames];
  86766. }
  86767. var filteredNodeIndices_1 = new Array();
  86768. this._traverseNodes(context, nodeIndices, function (node) {
  86769. if (nodeNames.indexOf(node.name) !== -1) {
  86770. filteredNodeIndices_1.push(node.index);
  86771. node.parent = _this._rootNode;
  86772. return false;
  86773. }
  86774. return true;
  86775. }, this._rootNode);
  86776. nodeIndices = filteredNodeIndices_1;
  86777. }
  86778. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  86779. var index = nodeIndices_1[_i];
  86780. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  86781. if (!node) {
  86782. throw new Error(context + ": Failed to find node " + index);
  86783. }
  86784. this._loadNode("#/nodes/" + index, node);
  86785. }
  86786. // Disable the root mesh until the asset is ready to render.
  86787. this._rootNode.babylonMesh.setEnabled(false);
  86788. };
  86789. GLTFLoader.prototype._loadNode = function (context, node) {
  86790. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  86791. return;
  86792. }
  86793. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  86794. this._loadTransform(node);
  86795. if (node.mesh != null) {
  86796. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  86797. if (!mesh) {
  86798. throw new Error(context + ": Failed to find mesh " + node.mesh);
  86799. }
  86800. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  86801. }
  86802. node.babylonMesh.parent = node.parent.babylonMesh;
  86803. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  86804. node.babylonAnimationTargets.push(node.babylonMesh);
  86805. if (node.skin != null) {
  86806. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  86807. if (!skin_1) {
  86808. throw new Error(context + ": Failed to find skin " + node.skin);
  86809. }
  86810. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  86811. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  86812. node.babylonMesh._refreshBoundingInfo(true);
  86813. });
  86814. node.babylonMesh.parent = this._rootNode.babylonMesh;
  86815. node.babylonMesh.position = BABYLON.Vector3.Zero();
  86816. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86817. node.babylonMesh.scaling = BABYLON.Vector3.One();
  86818. }
  86819. if (node.camera != null) {
  86820. // TODO: handle cameras
  86821. }
  86822. if (node.children) {
  86823. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  86824. var index = _a[_i];
  86825. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  86826. if (!childNode) {
  86827. throw new Error(context + ": Failed to find child node " + index);
  86828. }
  86829. this._loadNode("#/nodes/" + index, childNode);
  86830. }
  86831. }
  86832. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  86833. };
  86834. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  86835. var _this = this;
  86836. var primitives = mesh.primitives;
  86837. if (!primitives || primitives.length === 0) {
  86838. throw new Error(context + ": Primitives are missing");
  86839. }
  86840. this._createMorphTargets(context, node, mesh);
  86841. this._loadAllVertexDataAsync(context, mesh, function () {
  86842. _this._loadMorphTargets(context, node, mesh);
  86843. var vertexData = new BABYLON.VertexData();
  86844. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  86845. var primitive = primitives_1[_i];
  86846. vertexData.merge(primitive.vertexData);
  86847. }
  86848. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  86849. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  86850. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  86851. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  86852. node.babylonMesh.subMeshes = [];
  86853. var verticesStart = 0;
  86854. var indicesStart = 0;
  86855. for (var index = 0; index < primitives.length; index++) {
  86856. var vertexData_1 = primitives[index].vertexData;
  86857. var verticesCount = vertexData_1.positions.length;
  86858. var indicesCount = vertexData_1.indices.length;
  86859. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  86860. verticesStart += verticesCount;
  86861. indicesStart += indicesCount;
  86862. }
  86863. ;
  86864. });
  86865. if (primitives.length === 1) {
  86866. var primitive = primitives[0];
  86867. if (primitive.material == null) {
  86868. node.babylonMesh.material = this._getDefaultMaterial();
  86869. }
  86870. else {
  86871. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  86872. if (!material) {
  86873. throw new Error(context + ": Failed to find material " + primitive.material);
  86874. }
  86875. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  86876. if (isNew) {
  86877. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  86878. }
  86879. node.babylonMesh.material = babylonMaterial;
  86880. });
  86881. }
  86882. }
  86883. else {
  86884. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  86885. node.babylonMesh.material = multiMaterial;
  86886. var subMaterials_1 = multiMaterial.subMaterials;
  86887. var _loop_1 = function (index) {
  86888. var primitive = primitives[index];
  86889. if (primitive.material == null) {
  86890. subMaterials_1[index] = this_1._getDefaultMaterial();
  86891. }
  86892. else {
  86893. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  86894. if (!material) {
  86895. throw new Error(context + ": Failed to find material " + primitive.material);
  86896. }
  86897. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  86898. if (isNew) {
  86899. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  86900. }
  86901. subMaterials_1[index] = babylonMaterial;
  86902. });
  86903. }
  86904. };
  86905. var this_1 = this;
  86906. for (var index = 0; index < primitives.length; index++) {
  86907. _loop_1(index);
  86908. }
  86909. ;
  86910. }
  86911. };
  86912. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  86913. var primitives = mesh.primitives;
  86914. var numRemainingPrimitives = primitives.length;
  86915. var _loop_2 = function (index) {
  86916. var primitive = primitives[index];
  86917. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  86918. primitive.vertexData = vertexData;
  86919. if (--numRemainingPrimitives === 0) {
  86920. onSuccess();
  86921. }
  86922. });
  86923. };
  86924. var this_2 = this;
  86925. for (var index = 0; index < primitives.length; index++) {
  86926. _loop_2(index);
  86927. }
  86928. };
  86929. /**
  86930. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  86931. * @param {ArrayBufferView} data
  86932. * @param {IGLTFAccessor} accessor
  86933. */
  86934. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  86935. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  86936. return data;
  86937. }
  86938. var buffer = data;
  86939. var factor = 1;
  86940. switch (accessor.componentType) {
  86941. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  86942. factor = 1 / 255;
  86943. break;
  86944. }
  86945. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  86946. factor = 1 / 65535;
  86947. break;
  86948. }
  86949. default: {
  86950. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  86951. }
  86952. }
  86953. var result = new Float32Array(accessor.count * 2);
  86954. for (var i = 0; i < result.length; ++i) {
  86955. result[i] = buffer[i] * factor;
  86956. }
  86957. return result;
  86958. };
  86959. /**
  86960. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  86961. * @param {ArrayBufferView} data
  86962. * @param {IGLTFAccessor} accessor
  86963. */
  86964. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  86965. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  86966. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  86967. return data;
  86968. }
  86969. var buffer = data;
  86970. var factor = 1;
  86971. switch (accessor.componentType) {
  86972. case GLTF2.EComponentType.FLOAT: {
  86973. factor = 1;
  86974. break;
  86975. }
  86976. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  86977. factor = 1 / 255;
  86978. break;
  86979. }
  86980. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  86981. factor = 1 / 65535;
  86982. break;
  86983. }
  86984. default: {
  86985. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  86986. }
  86987. }
  86988. var result = new Float32Array(accessor.count * 4);
  86989. if (colorComponentCount === 4) {
  86990. for (var i = 0; i < result.length; ++i) {
  86991. result[i] = buffer[i] * factor;
  86992. }
  86993. }
  86994. else {
  86995. var offset = 0;
  86996. for (var i = 0; i < result.length; ++i) {
  86997. if ((i + 1) % 4 === 0) {
  86998. result[i] = 1;
  86999. }
  87000. else {
  87001. result[i] = buffer[offset++] * factor;
  87002. }
  87003. }
  87004. }
  87005. return result;
  87006. };
  87007. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  87008. var _this = this;
  87009. var attributes = primitive.attributes;
  87010. if (!attributes) {
  87011. throw new Error(context + ": Attributes are missing");
  87012. }
  87013. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  87014. // TODO: handle other primitive modes
  87015. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  87016. }
  87017. var vertexData = new BABYLON.VertexData();
  87018. var numRemainingAttributes = Object.keys(attributes).length;
  87019. var _loop_3 = function (attribute) {
  87020. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  87021. if (!accessor) {
  87022. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  87023. }
  87024. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  87025. switch (attribute) {
  87026. case "POSITION": {
  87027. vertexData.positions = data;
  87028. break;
  87029. }
  87030. case "NORMAL": {
  87031. vertexData.normals = data;
  87032. break;
  87033. }
  87034. case "TANGENT": {
  87035. vertexData.tangents = data;
  87036. break;
  87037. }
  87038. case "TEXCOORD_0": {
  87039. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  87040. break;
  87041. }
  87042. case "TEXCOORD_1": {
  87043. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  87044. break;
  87045. }
  87046. case "JOINTS_0": {
  87047. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  87048. break;
  87049. }
  87050. case "WEIGHTS_0": {
  87051. //TODO: need to add support for normalized weights.
  87052. vertexData.matricesWeights = data;
  87053. break;
  87054. }
  87055. case "COLOR_0": {
  87056. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  87057. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  87058. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  87059. mesh.hasVertexAlpha = hasVertexAlpha;
  87060. }
  87061. break;
  87062. }
  87063. default: {
  87064. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  87065. break;
  87066. }
  87067. }
  87068. if (--numRemainingAttributes === 0) {
  87069. if (primitive.indices == null) {
  87070. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  87071. for (var i = 0; i < vertexData.indices.length; i++) {
  87072. vertexData.indices[i] = i;
  87073. }
  87074. onSuccess(vertexData);
  87075. }
  87076. else {
  87077. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  87078. if (!indicesAccessor) {
  87079. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  87080. }
  87081. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  87082. vertexData.indices = data;
  87083. onSuccess(vertexData);
  87084. });
  87085. }
  87086. }
  87087. });
  87088. };
  87089. var this_3 = this;
  87090. for (var attribute in attributes) {
  87091. _loop_3(attribute);
  87092. }
  87093. };
  87094. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  87095. var primitives = mesh.primitives;
  87096. var targets = primitives[0].targets;
  87097. if (!targets) {
  87098. return;
  87099. }
  87100. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  87101. var primitive = primitives_2[_i];
  87102. if (!primitive.targets || primitive.targets.length != targets.length) {
  87103. throw new Error(context + ": All primitives are required to list the same number of targets");
  87104. }
  87105. }
  87106. var morphTargetManager = new BABYLON.MorphTargetManager();
  87107. node.babylonMesh.morphTargetManager = morphTargetManager;
  87108. for (var index = 0; index < targets.length; index++) {
  87109. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  87110. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  87111. }
  87112. };
  87113. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  87114. var morphTargetManager = node.babylonMesh.morphTargetManager;
  87115. if (!morphTargetManager) {
  87116. return;
  87117. }
  87118. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  87119. var numTargets = morphTargetManager.numTargets;
  87120. for (var index = 0; index < numTargets; index++) {
  87121. var vertexData = new BABYLON.VertexData();
  87122. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  87123. var primitive = _a[_i];
  87124. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  87125. }
  87126. if (!vertexData.positions) {
  87127. throw new Error(context + ": Positions are missing");
  87128. }
  87129. var target = morphTargetManager.getTarget(index);
  87130. target.setPositions(vertexData.positions);
  87131. target.setNormals(vertexData.normals);
  87132. target.setTangents(vertexData.tangents);
  87133. }
  87134. });
  87135. };
  87136. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  87137. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  87138. var _loop_4 = function (primitive) {
  87139. var targets = primitive.targets;
  87140. primitive.targetsVertexData = new Array(targets.length);
  87141. var _loop_5 = function (index) {
  87142. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  87143. primitive.targetsVertexData[index] = vertexData;
  87144. if (--numRemainingTargets === 0) {
  87145. onSuccess();
  87146. }
  87147. });
  87148. };
  87149. for (var index = 0; index < targets.length; index++) {
  87150. _loop_5(index);
  87151. }
  87152. };
  87153. var this_4 = this;
  87154. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  87155. var primitive = _a[_i];
  87156. _loop_4(primitive);
  87157. }
  87158. };
  87159. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  87160. var targetVertexData = new BABYLON.VertexData();
  87161. var numRemainingAttributes = Object.keys(attributes).length;
  87162. var _loop_6 = function (attribute) {
  87163. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  87164. if (!accessor) {
  87165. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  87166. }
  87167. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  87168. // glTF stores morph target information as deltas while babylon.js expects the final data.
  87169. // As a result we have to add the original data to the delta to calculate the final data.
  87170. var values = data;
  87171. switch (attribute) {
  87172. case "POSITION": {
  87173. for (var i = 0; i < values.length; i++) {
  87174. values[i] += vertexData.positions[i];
  87175. }
  87176. targetVertexData.positions = values;
  87177. break;
  87178. }
  87179. case "NORMAL": {
  87180. for (var i = 0; i < values.length; i++) {
  87181. values[i] += vertexData.normals[i];
  87182. }
  87183. targetVertexData.normals = values;
  87184. break;
  87185. }
  87186. case "TANGENT": {
  87187. // Tangent data for morph targets is stored as xyz delta.
  87188. // The vertexData.tangent is stored as xyzw.
  87189. // So we need to skip every fourth vertexData.tangent.
  87190. for (var i = 0, j = 0; i < values.length; i++, j++) {
  87191. values[i] += vertexData.tangents[j];
  87192. if ((i + 1) % 3 == 0) {
  87193. j++;
  87194. }
  87195. }
  87196. targetVertexData.tangents = values;
  87197. break;
  87198. }
  87199. default: {
  87200. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  87201. break;
  87202. }
  87203. }
  87204. if (--numRemainingAttributes === 0) {
  87205. onSuccess(targetVertexData);
  87206. }
  87207. });
  87208. };
  87209. var this_5 = this;
  87210. for (var attribute in attributes) {
  87211. _loop_6(attribute);
  87212. }
  87213. };
  87214. GLTFLoader.prototype._loadTransform = function (node) {
  87215. var position = BABYLON.Vector3.Zero();
  87216. var rotation = BABYLON.Quaternion.Identity();
  87217. var scaling = BABYLON.Vector3.One();
  87218. if (node.matrix) {
  87219. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  87220. matrix.decompose(scaling, rotation, position);
  87221. }
  87222. else {
  87223. if (node.translation)
  87224. position = BABYLON.Vector3.FromArray(node.translation);
  87225. if (node.rotation)
  87226. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  87227. if (node.scale)
  87228. scaling = BABYLON.Vector3.FromArray(node.scale);
  87229. }
  87230. node.babylonMesh.position = position;
  87231. node.babylonMesh.rotationQuaternion = rotation;
  87232. node.babylonMesh.scaling = scaling;
  87233. };
  87234. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  87235. var _this = this;
  87236. if (skin.babylonSkeleton) {
  87237. onSuccess();
  87238. return;
  87239. }
  87240. var skeletonId = "skeleton" + skin.index;
  87241. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  87242. if (skin.inverseBindMatrices == null) {
  87243. this._loadBones(context, skin, null);
  87244. onSuccess();
  87245. }
  87246. else {
  87247. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  87248. if (!accessor) {
  87249. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  87250. }
  87251. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  87252. _this._loadBones(context, skin, data);
  87253. onSuccess();
  87254. });
  87255. }
  87256. };
  87257. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  87258. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  87259. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  87260. node.babylonAnimationTargets.push(babylonBone);
  87261. return babylonBone;
  87262. };
  87263. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  87264. var babylonBones = {};
  87265. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  87266. var index = _a[_i];
  87267. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  87268. if (!node) {
  87269. throw new Error(context + ": Failed to find joint " + index);
  87270. }
  87271. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  87272. }
  87273. };
  87274. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  87275. var babylonBone = babylonBones[node.index];
  87276. if (babylonBone) {
  87277. return babylonBone;
  87278. }
  87279. var boneIndex = skin.joints.indexOf(node.index);
  87280. var baseMatrix = BABYLON.Matrix.Identity();
  87281. if (inverseBindMatrixData && boneIndex !== -1) {
  87282. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  87283. baseMatrix.invertToRef(baseMatrix);
  87284. }
  87285. var babylonParentBone = null;
  87286. if (node.parent !== this._rootNode) {
  87287. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  87288. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  87289. }
  87290. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  87291. babylonBones[node.index] = babylonBone;
  87292. return babylonBone;
  87293. };
  87294. GLTFLoader.prototype._getNodeMatrix = function (node) {
  87295. return node.matrix ?
  87296. BABYLON.Matrix.FromArray(node.matrix) :
  87297. 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());
  87298. };
  87299. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  87300. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  87301. var index = indices_1[_i];
  87302. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  87303. if (!node) {
  87304. throw new Error(context + ": Failed to find node " + index);
  87305. }
  87306. this._traverseNode(context, node, action, parentNode);
  87307. }
  87308. };
  87309. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  87310. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  87311. return;
  87312. }
  87313. if (!action(node, parentNode)) {
  87314. return;
  87315. }
  87316. if (node.children) {
  87317. this._traverseNodes(context, node.children, action, node);
  87318. }
  87319. };
  87320. GLTFLoader.prototype._loadAnimations = function () {
  87321. var animations = this._gltf.animations;
  87322. if (!animations) {
  87323. return;
  87324. }
  87325. for (var index = 0; index < animations.length; index++) {
  87326. var animation = animations[index];
  87327. this._loadAnimation("#/animations/" + index, animation);
  87328. }
  87329. };
  87330. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  87331. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  87332. for (var index = 0; index < animation.channels.length; index++) {
  87333. var channel = GLTFLoader._GetProperty(animation.channels, index);
  87334. if (!channel) {
  87335. throw new Error(context + ": Failed to find channel " + index);
  87336. }
  87337. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  87338. if (!sampler) {
  87339. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  87340. }
  87341. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  87342. }
  87343. };
  87344. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  87345. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  87346. if (!targetNode) {
  87347. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  87348. }
  87349. var targetPath;
  87350. var animationType;
  87351. switch (channel.target.path) {
  87352. case "translation": {
  87353. targetPath = "position";
  87354. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  87355. break;
  87356. }
  87357. case "rotation": {
  87358. targetPath = "rotationQuaternion";
  87359. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  87360. break;
  87361. }
  87362. case "scale": {
  87363. targetPath = "scaling";
  87364. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  87365. break;
  87366. }
  87367. case "weights": {
  87368. targetPath = "influence";
  87369. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  87370. break;
  87371. }
  87372. default: {
  87373. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  87374. }
  87375. }
  87376. var inputData;
  87377. var outputData;
  87378. var checkSuccess = function () {
  87379. if (!inputData || !outputData) {
  87380. return;
  87381. }
  87382. var outputBufferOffset = 0;
  87383. var getNextOutputValue;
  87384. switch (targetPath) {
  87385. case "position": {
  87386. getNextOutputValue = function () {
  87387. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  87388. outputBufferOffset += 3;
  87389. return value;
  87390. };
  87391. break;
  87392. }
  87393. case "rotationQuaternion": {
  87394. getNextOutputValue = function () {
  87395. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  87396. outputBufferOffset += 4;
  87397. return value;
  87398. };
  87399. break;
  87400. }
  87401. case "scaling": {
  87402. getNextOutputValue = function () {
  87403. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  87404. outputBufferOffset += 3;
  87405. return value;
  87406. };
  87407. break;
  87408. }
  87409. case "influence": {
  87410. getNextOutputValue = function () {
  87411. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  87412. var value = new Array(numTargets);
  87413. for (var i = 0; i < numTargets; i++) {
  87414. value[i] = outputData[outputBufferOffset++];
  87415. }
  87416. return value;
  87417. };
  87418. break;
  87419. }
  87420. }
  87421. sampler.interpolation = sampler.interpolation || "LINEAR";
  87422. var getNextKey;
  87423. switch (sampler.interpolation) {
  87424. case "STEP": {
  87425. getNextKey = function (frameIndex) { return ({
  87426. frame: inputData[frameIndex],
  87427. value: getNextOutputValue(),
  87428. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  87429. }); };
  87430. break;
  87431. }
  87432. case "LINEAR": {
  87433. getNextKey = function (frameIndex) { return ({
  87434. frame: inputData[frameIndex],
  87435. value: getNextOutputValue()
  87436. }); };
  87437. break;
  87438. }
  87439. case "CUBICSPLINE": {
  87440. getNextKey = function (frameIndex) { return ({
  87441. frame: inputData[frameIndex],
  87442. inTangent: getNextOutputValue(),
  87443. value: getNextOutputValue(),
  87444. outTangent: getNextOutputValue()
  87445. }); };
  87446. break;
  87447. }
  87448. default: {
  87449. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  87450. }
  87451. }
  87452. ;
  87453. var keys;
  87454. if (inputData.length === 1) {
  87455. var key = getNextKey(0);
  87456. keys = [
  87457. { frame: key.frame, value: key.value },
  87458. { frame: key.frame + 1, value: key.value }
  87459. ];
  87460. }
  87461. else {
  87462. keys = new Array(inputData.length);
  87463. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  87464. keys[frameIndex] = getNextKey(frameIndex);
  87465. }
  87466. }
  87467. if (targetPath === "influence") {
  87468. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  87469. var _loop_7 = function (targetIndex) {
  87470. var morphTarget = morphTargetManager.getTarget(targetIndex);
  87471. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  87472. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  87473. babylonAnimation.setKeys(keys.map(function (key) { return ({
  87474. frame: key.frame,
  87475. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  87476. value: key.value[targetIndex],
  87477. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  87478. }); }));
  87479. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  87480. };
  87481. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  87482. _loop_7(targetIndex);
  87483. }
  87484. }
  87485. else {
  87486. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  87487. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  87488. babylonAnimation.setKeys(keys);
  87489. if (targetNode.babylonAnimationTargets) {
  87490. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  87491. var target = _a[_i];
  87492. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  87493. }
  87494. }
  87495. }
  87496. };
  87497. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  87498. if (!inputAccessor) {
  87499. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  87500. }
  87501. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  87502. inputData = data;
  87503. checkSuccess();
  87504. });
  87505. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  87506. if (!outputAccessor) {
  87507. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  87508. }
  87509. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  87510. outputData = data;
  87511. checkSuccess();
  87512. });
  87513. };
  87514. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  87515. var _this = this;
  87516. this._addPendingData(buffer);
  87517. if (buffer.loadedData) {
  87518. onSuccess(buffer.loadedData);
  87519. this._removePendingData(buffer);
  87520. }
  87521. else if (buffer.loadedObservable) {
  87522. buffer.loadedObservable.add(function (buffer) {
  87523. onSuccess(buffer.loadedData);
  87524. _this._removePendingData(buffer);
  87525. });
  87526. }
  87527. else {
  87528. if (!buffer.uri) {
  87529. throw new Error(context + ": Uri is missing");
  87530. }
  87531. buffer.loadedObservable = new BABYLON.Observable();
  87532. buffer.loadedObservable.add(function (buffer) {
  87533. onSuccess(buffer.loadedData);
  87534. _this._removePendingData(buffer);
  87535. });
  87536. this._loadUriAsync(context, buffer.uri, function (data) {
  87537. buffer.loadedData = data;
  87538. buffer.loadedObservable.notifyObservers(buffer);
  87539. buffer.loadedObservable = undefined;
  87540. });
  87541. }
  87542. };
  87543. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  87544. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  87545. if (!buffer) {
  87546. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  87547. }
  87548. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  87549. var data;
  87550. try {
  87551. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  87552. }
  87553. catch (e) {
  87554. throw new Error(context + ": " + e.message);
  87555. }
  87556. onSuccess(data);
  87557. });
  87558. };
  87559. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  87560. var _this = this;
  87561. if (accessor.sparse) {
  87562. throw new Error(context + ": Sparse accessors are not currently supported");
  87563. }
  87564. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  87565. if (!bufferView) {
  87566. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  87567. }
  87568. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  87569. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  87570. var data;
  87571. var byteOffset = accessor.byteOffset || 0;
  87572. var byteStride = bufferView.byteStride;
  87573. if (byteStride === 0) {
  87574. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  87575. }
  87576. try {
  87577. switch (accessor.componentType) {
  87578. case GLTF2.EComponentType.BYTE: {
  87579. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87580. break;
  87581. }
  87582. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  87583. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87584. break;
  87585. }
  87586. case GLTF2.EComponentType.SHORT: {
  87587. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87588. break;
  87589. }
  87590. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  87591. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87592. break;
  87593. }
  87594. case GLTF2.EComponentType.UNSIGNED_INT: {
  87595. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87596. break;
  87597. }
  87598. case GLTF2.EComponentType.FLOAT: {
  87599. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87600. break;
  87601. }
  87602. default: {
  87603. throw new Error(context + ": Invalid component type " + accessor.componentType);
  87604. }
  87605. }
  87606. }
  87607. catch (e) {
  87608. throw new Error(context + ": " + e);
  87609. }
  87610. onSuccess(data);
  87611. });
  87612. };
  87613. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  87614. byteOffset += data.byteOffset;
  87615. var targetLength = count * numComponents;
  87616. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  87617. return new typedArray(data.buffer, byteOffset, targetLength);
  87618. }
  87619. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  87620. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  87621. var targetBuffer = new typedArray(targetLength);
  87622. var sourceIndex = 0;
  87623. var targetIndex = 0;
  87624. while (targetIndex < targetLength) {
  87625. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  87626. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  87627. targetIndex++;
  87628. }
  87629. sourceIndex += elementStride;
  87630. }
  87631. return targetBuffer;
  87632. };
  87633. GLTFLoader.prototype._addPendingData = function (data) {
  87634. if (!this._renderReady) {
  87635. this._renderPendingCount++;
  87636. }
  87637. this._addLoaderPendingData(data);
  87638. };
  87639. GLTFLoader.prototype._removePendingData = function (data) {
  87640. var _this = this;
  87641. if (!this._renderReady) {
  87642. if (--this._renderPendingCount === 0) {
  87643. this._addLoaderPendingData(this);
  87644. this._compileMaterialsAsync(function () {
  87645. _this._compileShadowGeneratorsAsync(function () {
  87646. _this._removeLoaderPendingData(_this);
  87647. _this._renderReady = true;
  87648. _this._onRenderReady();
  87649. });
  87650. });
  87651. }
  87652. }
  87653. this._removeLoaderPendingData(data);
  87654. };
  87655. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  87656. this._loaderPendingCount++;
  87657. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  87658. var tracker = _a[_i];
  87659. tracker._addPendingData(data);
  87660. }
  87661. };
  87662. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  87663. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  87664. var tracker = _a[_i];
  87665. tracker._removePendingData(data);
  87666. }
  87667. if (--this._loaderPendingCount === 0) {
  87668. this._onComplete();
  87669. }
  87670. };
  87671. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  87672. var _this = this;
  87673. var tracker = new GLTFLoaderTracker(function () {
  87674. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  87675. onComplete();
  87676. });
  87677. this._loaderTrackers.push(tracker);
  87678. this._addLoaderPendingData(tracker);
  87679. action();
  87680. this._removeLoaderPendingData(tracker);
  87681. };
  87682. GLTFLoader.prototype._getDefaultMaterial = function () {
  87683. if (!this._defaultMaterial) {
  87684. var id = "__gltf_default";
  87685. var material = this._babylonScene.getMaterialByName(id);
  87686. if (!material) {
  87687. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  87688. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  87689. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  87690. material.metallic = 1;
  87691. material.roughness = 1;
  87692. }
  87693. this._defaultMaterial = material;
  87694. }
  87695. return this._defaultMaterial;
  87696. };
  87697. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  87698. var babylonMaterial = material.babylonMaterial;
  87699. // Ensure metallic workflow
  87700. babylonMaterial.metallic = 1;
  87701. babylonMaterial.roughness = 1;
  87702. var properties = material.pbrMetallicRoughness;
  87703. if (!properties) {
  87704. return;
  87705. }
  87706. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  87707. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  87708. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  87709. if (properties.baseColorTexture) {
  87710. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  87711. if (!texture) {
  87712. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  87713. }
  87714. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  87715. }
  87716. if (properties.metallicRoughnessTexture) {
  87717. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  87718. if (!texture) {
  87719. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  87720. }
  87721. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  87722. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  87723. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  87724. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  87725. }
  87726. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  87727. };
  87728. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  87729. if (material.babylonMaterial) {
  87730. assign(material.babylonMaterial, false);
  87731. return;
  87732. }
  87733. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  87734. return;
  87735. }
  87736. this._createPbrMaterial(material);
  87737. this._loadMaterialBaseProperties(context, material);
  87738. this._loadMaterialMetallicRoughnessProperties(context, material);
  87739. assign(material.babylonMaterial, true);
  87740. };
  87741. GLTFLoader.prototype._createPbrMaterial = function (material) {
  87742. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  87743. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  87744. material.babylonMaterial = babylonMaterial;
  87745. };
  87746. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  87747. var babylonMaterial = material.babylonMaterial;
  87748. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  87749. if (material.doubleSided) {
  87750. babylonMaterial.backFaceCulling = false;
  87751. babylonMaterial.twoSidedLighting = true;
  87752. }
  87753. if (material.normalTexture) {
  87754. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  87755. if (!texture) {
  87756. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  87757. }
  87758. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  87759. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  87760. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  87761. if (material.normalTexture.scale != null) {
  87762. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  87763. }
  87764. }
  87765. if (material.occlusionTexture) {
  87766. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  87767. if (!texture) {
  87768. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  87769. }
  87770. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  87771. babylonMaterial.useAmbientInGrayScale = true;
  87772. if (material.occlusionTexture.strength != null) {
  87773. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  87774. }
  87775. }
  87776. if (material.emissiveTexture) {
  87777. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  87778. if (!texture) {
  87779. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  87780. }
  87781. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  87782. }
  87783. };
  87784. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  87785. var babylonMaterial = material.babylonMaterial;
  87786. var alphaMode = material.alphaMode || "OPAQUE";
  87787. switch (alphaMode) {
  87788. case "OPAQUE": {
  87789. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  87790. break;
  87791. }
  87792. case "MASK": {
  87793. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  87794. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  87795. if (colorFactor) {
  87796. if (colorFactor[3] == 0) {
  87797. babylonMaterial.alphaCutOff = 1;
  87798. }
  87799. else {
  87800. babylonMaterial.alphaCutOff /= colorFactor[3];
  87801. }
  87802. }
  87803. if (babylonMaterial.albedoTexture) {
  87804. babylonMaterial.albedoTexture.hasAlpha = true;
  87805. }
  87806. break;
  87807. }
  87808. case "BLEND": {
  87809. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  87810. if (colorFactor) {
  87811. babylonMaterial.alpha = colorFactor[3];
  87812. }
  87813. if (babylonMaterial.albedoTexture) {
  87814. babylonMaterial.albedoTexture.hasAlpha = true;
  87815. babylonMaterial.useAlphaFromAlbedoTexture = true;
  87816. }
  87817. break;
  87818. }
  87819. default: {
  87820. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  87821. }
  87822. }
  87823. };
  87824. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  87825. var _this = this;
  87826. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  87827. if (!sampler) {
  87828. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  87829. }
  87830. this._loadSampler("#/samplers/" + sampler.index, sampler);
  87831. this._addPendingData(texture);
  87832. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  87833. _this._tryCatchOnError(function () {
  87834. _this._removePendingData(texture);
  87835. });
  87836. }, function (message) {
  87837. _this._tryCatchOnError(function () {
  87838. throw new Error(context + ": " + message);
  87839. });
  87840. });
  87841. if (texture.url) {
  87842. babylonTexture.updateURL(texture.url);
  87843. }
  87844. else if (texture.dataReadyObservable) {
  87845. texture.dataReadyObservable.add(function (texture) {
  87846. babylonTexture.updateURL(texture.url);
  87847. });
  87848. }
  87849. else {
  87850. texture.dataReadyObservable = new BABYLON.Observable();
  87851. texture.dataReadyObservable.add(function (texture) {
  87852. babylonTexture.updateURL(texture.url);
  87853. });
  87854. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  87855. if (!image_1) {
  87856. throw new Error(context + ": Failed to find source " + texture.source);
  87857. }
  87858. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  87859. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  87860. texture.dataReadyObservable.notifyObservers(texture);
  87861. texture.dataReadyObservable = undefined;
  87862. });
  87863. }
  87864. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  87865. babylonTexture.wrapU = sampler.wrapU;
  87866. babylonTexture.wrapV = sampler.wrapV;
  87867. babylonTexture.name = texture.name || "texture" + texture.index;
  87868. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  87869. return babylonTexture;
  87870. };
  87871. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  87872. if (sampler.noMipMaps != undefined) {
  87873. return;
  87874. }
  87875. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  87876. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  87877. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  87878. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  87879. };
  87880. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  87881. if (image.uri) {
  87882. this._loadUriAsync(context, image.uri, onSuccess);
  87883. }
  87884. else {
  87885. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  87886. if (!bufferView) {
  87887. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  87888. }
  87889. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  87890. }
  87891. };
  87892. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  87893. var _this = this;
  87894. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  87895. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  87896. return;
  87897. }
  87898. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  87899. throw new Error(context + ": Uri '" + uri + "' is invalid");
  87900. }
  87901. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  87902. _this._tryCatchOnError(function () {
  87903. onSuccess(new Uint8Array(data));
  87904. });
  87905. }, function (event) {
  87906. _this._tryCatchOnError(function () {
  87907. if (request && !_this._renderReady) {
  87908. request._lengthComputable = event.lengthComputable;
  87909. request._loaded = event.loaded;
  87910. request._total = event.total;
  87911. _this._onProgress();
  87912. }
  87913. });
  87914. }, this._babylonScene.database, true, function (request, exception) {
  87915. _this._tryCatchOnError(function () {
  87916. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  87917. });
  87918. });
  87919. this._requests.push(request);
  87920. };
  87921. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  87922. if (this._disposed) {
  87923. return;
  87924. }
  87925. try {
  87926. handler();
  87927. }
  87928. catch (e) {
  87929. BABYLON.Tools.Error("glTF Loader: " + e.message);
  87930. if (this._errorCallback) {
  87931. this._errorCallback(e.message, e);
  87932. }
  87933. this.dispose();
  87934. }
  87935. };
  87936. GLTFLoader._AssignIndices = function (array) {
  87937. if (array) {
  87938. for (var index = 0; index < array.length; index++) {
  87939. array[index].index = index;
  87940. }
  87941. }
  87942. };
  87943. GLTFLoader._GetProperty = function (array, index) {
  87944. if (!array || index == undefined || !array[index]) {
  87945. return null;
  87946. }
  87947. return array[index];
  87948. };
  87949. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  87950. // Set defaults if undefined
  87951. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  87952. switch (mode) {
  87953. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  87954. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  87955. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87956. default:
  87957. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  87958. return BABYLON.Texture.WRAP_ADDRESSMODE;
  87959. }
  87960. };
  87961. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  87962. // Set defaults if undefined
  87963. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  87964. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  87965. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  87966. switch (minFilter) {
  87967. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  87968. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  87969. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  87970. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  87971. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  87972. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  87973. default:
  87974. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  87975. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  87976. }
  87977. }
  87978. else {
  87979. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  87980. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  87981. }
  87982. switch (minFilter) {
  87983. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  87984. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  87985. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  87986. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  87987. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  87988. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  87989. default:
  87990. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  87991. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  87992. }
  87993. }
  87994. };
  87995. GLTFLoader._GetNumComponents = function (context, type) {
  87996. switch (type) {
  87997. case "SCALAR": return 1;
  87998. case "VEC2": return 2;
  87999. case "VEC3": return 3;
  88000. case "VEC4": return 4;
  88001. case "MAT2": return 4;
  88002. case "MAT3": return 9;
  88003. case "MAT4": return 16;
  88004. }
  88005. throw new Error(context + ": Invalid type " + type);
  88006. };
  88007. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  88008. var _this = this;
  88009. if (this.useClipPlane) {
  88010. babylonMaterial.forceCompilation(babylonMesh, function () {
  88011. babylonMaterial.forceCompilation(babylonMesh, function () {
  88012. _this._tryCatchOnError(onSuccess);
  88013. }, { clipPlane: true });
  88014. });
  88015. }
  88016. else {
  88017. babylonMaterial.forceCompilation(babylonMesh, function () {
  88018. _this._tryCatchOnError(onSuccess);
  88019. });
  88020. }
  88021. };
  88022. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  88023. if (!this.compileMaterials || !this._gltf.materials) {
  88024. onSuccess();
  88025. return;
  88026. }
  88027. var meshes = this._getMeshes();
  88028. var remaining = 0;
  88029. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  88030. var mesh = meshes_1[_i];
  88031. if (mesh.material instanceof BABYLON.MultiMaterial) {
  88032. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  88033. var subMaterial = _b[_a];
  88034. if (subMaterial) {
  88035. remaining++;
  88036. }
  88037. }
  88038. }
  88039. else if (mesh.material) {
  88040. remaining++;
  88041. }
  88042. }
  88043. if (remaining === 0) {
  88044. onSuccess();
  88045. return;
  88046. }
  88047. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  88048. var mesh = meshes_2[_c];
  88049. if (mesh.material instanceof BABYLON.MultiMaterial) {
  88050. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  88051. var subMaterial = _e[_d];
  88052. if (subMaterial) {
  88053. this._compileMaterialAsync(subMaterial, mesh, function () {
  88054. if (--remaining === 0) {
  88055. onSuccess();
  88056. }
  88057. });
  88058. }
  88059. }
  88060. }
  88061. else if (mesh.material) {
  88062. this._compileMaterialAsync(mesh.material, mesh, function () {
  88063. if (--remaining === 0) {
  88064. onSuccess();
  88065. }
  88066. });
  88067. }
  88068. }
  88069. };
  88070. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  88071. var _this = this;
  88072. if (!this.compileShadowGenerators) {
  88073. onSuccess();
  88074. return;
  88075. }
  88076. var lights = this._babylonScene.lights;
  88077. var remaining = 0;
  88078. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  88079. var light = lights_1[_i];
  88080. var generator = light.getShadowGenerator();
  88081. if (generator) {
  88082. remaining++;
  88083. }
  88084. }
  88085. if (remaining === 0) {
  88086. onSuccess();
  88087. return;
  88088. }
  88089. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  88090. var light = lights_2[_a];
  88091. var generator = light.getShadowGenerator();
  88092. if (generator) {
  88093. generator.forceCompilation(function () {
  88094. if (--remaining === 0) {
  88095. _this._tryCatchOnError(onSuccess);
  88096. }
  88097. });
  88098. }
  88099. }
  88100. };
  88101. GLTFLoader.prototype._abortRequests = function () {
  88102. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  88103. var request = _a[_i];
  88104. request.abort();
  88105. }
  88106. this._requests.length = 0;
  88107. };
  88108. GLTFLoader.prototype._releaseResources = function () {
  88109. if (this._gltf.textures) {
  88110. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  88111. var texture = _a[_i];
  88112. if (texture.url) {
  88113. URL.revokeObjectURL(texture.url);
  88114. texture.url = undefined;
  88115. }
  88116. }
  88117. }
  88118. };
  88119. GLTFLoader.Extensions = {};
  88120. return GLTFLoader;
  88121. }());
  88122. GLTF2.GLTFLoader = GLTFLoader;
  88123. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  88124. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88125. })(BABYLON || (BABYLON = {}));
  88126. //# sourceMappingURL=babylon.glTFLoader.js.map
  88127. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88128. var BABYLON;
  88129. (function (BABYLON) {
  88130. var GLTF2;
  88131. (function (GLTF2) {
  88132. /**
  88133. * Utils functions for GLTF
  88134. */
  88135. var GLTFUtils = /** @class */ (function () {
  88136. function GLTFUtils() {
  88137. }
  88138. /**
  88139. * If the uri is a base64 string
  88140. * @param uri: the uri to test
  88141. */
  88142. GLTFUtils.IsBase64 = function (uri) {
  88143. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  88144. };
  88145. /**
  88146. * Decode the base64 uri
  88147. * @param uri: the uri to decode
  88148. */
  88149. GLTFUtils.DecodeBase64 = function (uri) {
  88150. var decodedString = atob(uri.split(",")[1]);
  88151. var bufferLength = decodedString.length;
  88152. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  88153. for (var i = 0; i < bufferLength; i++) {
  88154. bufferView[i] = decodedString.charCodeAt(i);
  88155. }
  88156. return bufferView.buffer;
  88157. };
  88158. GLTFUtils.ValidateUri = function (uri) {
  88159. return (uri.indexOf("..") === -1);
  88160. };
  88161. return GLTFUtils;
  88162. }());
  88163. GLTF2.GLTFUtils = GLTFUtils;
  88164. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88165. })(BABYLON || (BABYLON = {}));
  88166. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  88167. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88168. var BABYLON;
  88169. (function (BABYLON) {
  88170. var GLTF2;
  88171. (function (GLTF2) {
  88172. var GLTFLoaderExtension = /** @class */ (function () {
  88173. function GLTFLoaderExtension() {
  88174. this.enabled = true;
  88175. }
  88176. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  88177. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  88178. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  88179. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  88180. var _this = this;
  88181. if (!property.extensions) {
  88182. return false;
  88183. }
  88184. var extension = property.extensions[this.name];
  88185. if (!extension) {
  88186. return false;
  88187. }
  88188. // Clear out the extension before executing the action to avoid recursing into the same property.
  88189. property.extensions[this.name] = undefined;
  88190. action(context + "extensions/" + this.name, extension, function () {
  88191. // Restore the extension after completing the action.
  88192. property.extensions[_this.name] = extension;
  88193. });
  88194. return true;
  88195. };
  88196. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  88197. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  88198. };
  88199. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  88200. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  88201. };
  88202. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  88203. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  88204. };
  88205. GLTFLoaderExtension._ApplyExtensions = function (action) {
  88206. var extensions = GLTFLoaderExtension._Extensions;
  88207. if (!extensions) {
  88208. return false;
  88209. }
  88210. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  88211. var extension = extensions_1[_i];
  88212. if (extension.enabled && action(extension)) {
  88213. return true;
  88214. }
  88215. }
  88216. return false;
  88217. };
  88218. //
  88219. // Utilities
  88220. //
  88221. GLTFLoaderExtension._Extensions = [];
  88222. return GLTFLoaderExtension;
  88223. }());
  88224. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  88225. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88226. })(BABYLON || (BABYLON = {}));
  88227. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  88228. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  88229. var BABYLON;
  88230. (function (BABYLON) {
  88231. var GLTF2;
  88232. (function (GLTF2) {
  88233. var Extensions;
  88234. (function (Extensions) {
  88235. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  88236. var MSFTLOD = /** @class */ (function (_super) {
  88237. __extends(MSFTLOD, _super);
  88238. function MSFTLOD() {
  88239. var _this = _super !== null && _super.apply(this, arguments) || this;
  88240. /**
  88241. * Specify the minimal delay between LODs in ms (default = 250)
  88242. */
  88243. _this.Delay = 250;
  88244. return _this;
  88245. }
  88246. Object.defineProperty(MSFTLOD.prototype, "name", {
  88247. get: function () {
  88248. return "MSFT_lod";
  88249. },
  88250. enumerable: true,
  88251. configurable: true
  88252. });
  88253. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  88254. return this._loadExtension(context, node, function (context, extension, onComplete) {
  88255. for (var i = extension.ids.length - 1; i >= 0; i--) {
  88256. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  88257. if (!lodNode) {
  88258. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  88259. }
  88260. loader._traverseNode(context, lodNode, action, parentNode);
  88261. }
  88262. loader._traverseNode(context, node, action, parentNode);
  88263. onComplete();
  88264. });
  88265. };
  88266. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  88267. var _this = this;
  88268. return this._loadExtension(context, node, function (context, extension, onComplete) {
  88269. var nodes = [node];
  88270. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  88271. var index = _a[_i];
  88272. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  88273. if (!lodNode) {
  88274. throw new Error(context + ": Failed to find node " + index);
  88275. }
  88276. nodes.push(lodNode);
  88277. }
  88278. loader._addLoaderPendingData(node);
  88279. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  88280. loader._removeLoaderPendingData(node);
  88281. onComplete();
  88282. });
  88283. });
  88284. };
  88285. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  88286. var _this = this;
  88287. loader._whenAction(function () {
  88288. loader._loadNode(context, nodes[index]);
  88289. }, function () {
  88290. if (index !== nodes.length - 1) {
  88291. var previousNode = nodes[index + 1];
  88292. previousNode.babylonMesh.setEnabled(false);
  88293. }
  88294. if (index === 0) {
  88295. onComplete();
  88296. return;
  88297. }
  88298. setTimeout(function () {
  88299. loader._tryCatchOnError(function () {
  88300. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  88301. });
  88302. }, _this.Delay);
  88303. });
  88304. };
  88305. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  88306. var _this = this;
  88307. return this._loadExtension(context, material, function (context, extension, onComplete) {
  88308. var materials = [material];
  88309. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  88310. var index = _a[_i];
  88311. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  88312. if (!lodMaterial) {
  88313. throw new Error(context + ": Failed to find material " + index);
  88314. }
  88315. materials.push(lodMaterial);
  88316. }
  88317. loader._addLoaderPendingData(material);
  88318. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  88319. loader._removeLoaderPendingData(material);
  88320. onComplete();
  88321. });
  88322. });
  88323. };
  88324. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  88325. var _this = this;
  88326. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  88327. if (index === materials.length - 1) {
  88328. assign(babylonMaterial, isNew);
  88329. // Load the next LOD when the loader is ready to render.
  88330. loader._executeWhenRenderReady(function () {
  88331. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  88332. });
  88333. }
  88334. else {
  88335. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  88336. assign(babylonMaterial, isNew);
  88337. if (index === 0) {
  88338. onComplete();
  88339. }
  88340. else {
  88341. setTimeout(function () {
  88342. loader._tryCatchOnError(function () {
  88343. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  88344. });
  88345. }, _this.Delay);
  88346. }
  88347. });
  88348. }
  88349. });
  88350. };
  88351. return MSFTLOD;
  88352. }(GLTF2.GLTFLoaderExtension));
  88353. Extensions.MSFTLOD = MSFTLOD;
  88354. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  88355. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  88356. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88357. })(BABYLON || (BABYLON = {}));
  88358. //# sourceMappingURL=MSFT_lod.js.map
  88359. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  88360. var BABYLON;
  88361. (function (BABYLON) {
  88362. var GLTF2;
  88363. (function (GLTF2) {
  88364. var Extensions;
  88365. (function (Extensions) {
  88366. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  88367. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  88368. function KHRMaterialsPbrSpecularGlossiness() {
  88369. return _super !== null && _super.apply(this, arguments) || this;
  88370. }
  88371. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  88372. get: function () {
  88373. return "KHR_materials_pbrSpecularGlossiness";
  88374. },
  88375. enumerable: true,
  88376. configurable: true
  88377. });
  88378. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  88379. var _this = this;
  88380. return this._loadExtension(context, material, function (context, extension, onComplete) {
  88381. loader._createPbrMaterial(material);
  88382. loader._loadMaterialBaseProperties(context, material);
  88383. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  88384. assign(material.babylonMaterial, true);
  88385. onComplete();
  88386. });
  88387. };
  88388. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  88389. var babylonMaterial = material.babylonMaterial;
  88390. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  88391. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  88392. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  88393. if (properties.diffuseTexture) {
  88394. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  88395. if (!texture) {
  88396. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  88397. }
  88398. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  88399. }
  88400. if (properties.specularGlossinessTexture) {
  88401. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  88402. if (!texture) {
  88403. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  88404. }
  88405. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  88406. babylonMaterial.reflectivityTexture.hasAlpha = true;
  88407. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  88408. }
  88409. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  88410. };
  88411. return KHRMaterialsPbrSpecularGlossiness;
  88412. }(GLTF2.GLTFLoaderExtension));
  88413. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  88414. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  88415. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  88416. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88417. })(BABYLON || (BABYLON = {}));
  88418. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  88419. (function universalModuleDefinition(root, factory) {
  88420. var f = factory();
  88421. if (root && root["BABYLON"]) {
  88422. return;
  88423. }
  88424. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  88425. globalObject["BABYLON"] = f;
  88426. if(typeof exports === 'object' && typeof module === 'object')
  88427. module.exports = f;
  88428. else if(typeof define === 'function' && define.amd)
  88429. define(["BABYLON"], factory);
  88430. else if(typeof exports === 'object')
  88431. exports["BABYLON"] = f;
  88432. else {
  88433. root["BABYLON"] = f;
  88434. }
  88435. })(this, function() {
  88436. return BABYLON;
  88437. });